Generate a PDF file using a byte array and save it for download

I am working on an AJAX function that calls a server-side method which in turn calls an API and returns a byte array. My goal is to convert this byte array into a PDF file and then download the file. Here is the code I have:

AJAX function:

function ObtainFile(fileNumber) {
    debugger;
    $.ajax({
        type: 'POST',
        url: '/De.aspx/FindFile',
        data: JSON.stringify({ fileNumber: fileNumber }),
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (msg) {
            debugger;
            if (msg.d != null) {
                window.open();
            }
        },
        error: function () {
        }
    });
}

Code behind method:

[System.Web.Services.WebMethod]
public static byte[] FindFile(string fileNumber)
{
     var response = new Serv.L.SeL((U)HttpContext.Current.Session["UT"]).ObtainFile(fileNumber);
     if (response != null)
     {
         File.WriteAllBytes(@"~\Content\tmp\hello.pdf", response.F);
         return response.F;
     }
     else
         return null;
}

I attempted to use a relative path in the FindFile method, but faced difficulty with passing it into File.WriteAllBytes. I am unsure of how to automatically download the new PDF file or save it in the tmp folder within the project. Furthermore, I would like to open a new tab with the PDF file. While I can achieve this with an absolute path, it may not work if the project is deployed on another server. For example, it works on my local machine with a path like C:/User/Desktop.

Any suggestions or advice would be greatly appreciated. Thank you.

Answer №1

Avoid relying on ajax for PDF downloads as it can lead to bad habits. Instead, utilize the a tag or iframe tag for a more efficient solution.

Another option is to simply use window.location = '[your route]' to initiate the file download process.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Increasing an element in an array of objects using MongoDB and Mongoose

In my possession is a document structured as follows: { "id": "12345", "channels": [ { "id": "67890", "count": 1 } ] } My objective is to increase the count of a specific channel by one. When a user sends a message, I must locat ...

Is file timestamp utilized by Apache to verify if a resource has been changed?

Currently, I am working on an HTML page that references a large JavaScript file (1MB+) that is rarely updated. According to this source, the JavaScript file will not be resent if it hasn't been modified. I'm curious about how Apache determines i ...

I aim to showcase particular cookies within an input field using jQuery

I am seeking a way to create a responsive page that showcases cookies. My goal is to have the output of a function automatically appear in the input value upon loading the page, instead of requiring a click event. Here is the code snippet I have been worki ...

The Consequences of Using Undeclared Variables in JavaScript

What is the reason behind JavaScript throwing a reference error when attempting to use an undeclared variable, but allowing it to be set to a value? For example: a = 10; //creates global variable a and sets value to 10 even though it's undeclared al ...

Using jQuery to dynamically include option groups and options in a select box

Generate option groups and options dynamically using data retrieved via AJAX. <select name="catsndogs"> <optgroup label="Cats"> <option>Tiger</option> <option>Leopard</option> <option>Ly ...

Ways to evaluate and contrast two JSON values in JavaScript by their key names?

I am dealing with two JSON arrays that look like this: array1=[{a:1,b:2,c:3,d:4}] & array2=[{a:2,b:5,c:3,d:4}] Is there a way to determine which key in array2 has the same value as one of the keys in array1? For example, in array 1, key b has a value ...

Guide on creating dynamic datasets and multiple dynamic yAxes

To enhance my chart, I am interested in adding multiple Y Axes based on the examples provided below: script 1 script 2 Although I attempted to modify the code as shown below, it seems to not be functioning properly. function rdnum() { return Math.flo ...

Dynamic web page updates from server using an Ajax request

I have a JavaScript client application and an Express.js server. I am looking to update a page on my server with information sent through an AJAX call from my client application. I need the page to be updated in real-time. Here is the code snippet in my ...

What are the steps to deploy a React, Next.js, and Express.js application on Netlify?

I am currently in the process of deploying my application to Netlify, featuring a combination of React, Next.js, and Express.js. While there are no errors showing up in the Netlify console, unfortunately, the site is not live as expected. https://i.stack ...

"Combining multiple DIVs into a single DIV with jQuery - a step-by-step guide

I have multiple DIVs with the same class, and I am looking to group them into a single DIV using either jQuery or pure JS. <div class="a"> <div>1</div> </div> <div class="a"> <div>2</div> ...

The Angular JS field will only be considered valid if its value is more than zero

I have a text box in my form that changes its value dynamically when a user selects a category from a dropdown menu. Initially, the value is set to 0. $scope.validCats = "0"; HTML: <input ng-model="validCats" value="" type="text" class="form-control ...

Filling a martial arts training center's drop-down menu with choices using an Ajax response message

Within my application, there are two drop down menus. The first drop down menu allows users to select the type of institution, and I have added an onchange event that triggers a JavaScript function to make an AJAX call in order to populate the second drop ...

Preview multiple images while uploading in a React JS application

In order to achieve multiple image upload with preview using React JS, I attempted the code below. However, I encountered an error in the console: Uncaught DOMException: Failed to set the 'value' property on 'HTMLInputElement': This ...

Is there a way to find out the ultimate destination of a shortened URL without actually opening the webpage?

I am trying to implement a feature where I can click on links within email messages and have the full link displayed in a separate pane using jQuery. However, I am facing some challenges with this implementation. My plan is to use AJAX to call a PHP scrip ...

Using Selenium to ensure the webpage waits for the external URL request

My objective is to obtain a link to a m3u8 file that requires a secret token which changes daily. The file is requested when the page first loads and is only available once the page is fully loaded. Using Chrome developer tools, I can see this file being d ...

What is the best way to divide array data in vb.net?

I am currently working with a datatable that retrieves a column named "location" which consists of a combination of city, state, and zipcode. I have stored the values of this column in an array and now I need to split this array data and store it in anot ...

User events in the fullCalendar

I'm feeling stuck. I currently have a basic fullCalendar setup for the User model in Rails. I want to add 2 buttons, allowing the User to separate the calendar into two views. One view would display only their own events, while the other would show al ...

Creating a dynamic multi-series line chart in D3 version 4 that incorporates data points with matching colors to their respective lines

In my attempt to enhance a multi-series line chart with D3 V4 in Angular-cli, I have encountered a challenge. Below is the code snippet of what I have been working on. var lookBookData = z.domain().map(function (name) { return { name: name, ...

Ways to distinguish if Dynamics XRM javascript is being triggered from the unified interface (UCI) or the traditional web-client interface

Is there an official way to determine if code is being called from the UCI or the legacy web-client? I see the function Xrm.Internal.isUci(), but since it's labeled as Internal, it may not be recommended for use. However, I still need a method to diff ...

Using codedeploy to deploy a Next.js application onto an AWS EC2 instance

After creating a fresh NextJS app with only basic boilerplate files and folders, I uploaded it to a CodeCommit repository. I already had a functional CodePipeline and simply switched the Source stages. However, I am encountering deployment failures during ...