In today’s web development landscape, the ability to generate and download files directly from a webpage is a valuable feature. Whether you’re creating invoices, reports, or any other type of document, providing users with the option to export data as a PDF can greatly enhance their experience. In this post, I’ll walk you through how to implement a PDF export feature using jQuery and AJAX.
The Scenario
Imagine you have a web application where users can view detailed information about orders. You want to give them the option to download these order details as a PDF file. To achieve this, we’ll create a button that triggers an AJAX call to generate the PDF on the server side and then download it on the client side.
Step-by-Step Implementation
Let’s break down the code that makes this possible.
1. HTML Structure
First, you need a button that users can click to export the PDF. Here’s a simple example:
<button id="btnExportToPdf">Export to PDF</button>
This button has an id
of btnExportToPdf
, which we will reference in our jQuery code.
2. The jQuery Code
Now, let’s dive into the jQuery code that handles the button click, sends an AJAX request, and facilitates the PDF download.
$("#btnExportToPdf").click(function (e) {
e.preventDefault(); // Prevent the default action (e.g., navigating to another page)
$.ajax({
url: 'PrintOrderDetails.aspx/GeneratePdf', // The URL to the server-side method that generates the PDF
type: "POST", // The HTTP method to use for the request
contentType: 'application/json; charset=utf-8', // The content type of the request
dataType: 'json', // The type of data that is expected back from the server
success: function (r) {
var fileName = "order-details.pdf"; // The name of the PDF file to download
// Convert Base64 string to Byte Array.
var bytes = Base64ToBytes(r.d);
// Convert Byte Array to BLOB.
var blob = new Blob([bytes], { type: "application/octetstream" });
// Check the Browser type and download the File.
var isIE = false || !!document.documentMode; // Check if the browser is Internet Explorer
if (isIE) {
window.navigator.msSaveBlob(blob, fileName); // For IE, use the msSaveBlob method
} else {
var url = window.URL || window.webkitURL;
var link = url.createObjectURL(blob); // Create a URL for the BLOB
var a = $("<a />");
a.attr("download", fileName); // Set the download attribute with the file name
a.attr("href", link); // Set the href to the BLOB URL
$("body").append(a); // Append the anchor to the body
a[0].click(); // Programmatically click the anchor to trigger the download
$("body").remove(a); // Remove the anchor from the DOM
}
},
failure: function (msg) {
// Handle failure case
alert('Failed to generate the PDF.');
},
error: function (xhr, status, error) {
// Handle error case
alert('Error: ' + error);
}
});
});
How It Works
- AJAX Call: When the button is clicked, an AJAX call is made to the server-side URL
PrintOrderDetails.aspx/GeneratePdf
. This URL corresponds to a method on your server that generates the PDF. - Base64 to Byte Array: The server returns the PDF file as a Base64 encoded string. The
Base64ToBytes
function (which you’ll need to define) converts this string into a byte array. - Byte Array to Blob: The byte array is then converted into a Blob object, which represents the file data.
- Browser Check and File Download: The script checks whether the user is using Internet Explorer. If so, it uses
msSaveBlob
to save the file. For other browsers, a temporary anchor element (<a>
) is created, and the Blob URL is assigned to itshref
attribute. The anchor is then clicked programmatically to trigger the download.
4. Handling Browser Differences
The code handles differences between Internet Explorer and other modern browsers. IE requires a special method (msSaveBlob
) to save files, whereas other browsers allow the use of a temporary anchor element with a Blob URL.
5. Error Handling
The script also includes basic error handling to alert the user if the PDF generation fails or if there is an error during the AJAX request.
Conclusion
This approach is a simple yet effective way to allow users to download data as a PDF directly from your web application. By leveraging jQuery and AJAX, you can create a seamless and user-friendly experience. If you’re working with order details, invoices, or any similar data, integrating this functionality will add significant value to your application.
Remember to implement the Base64ToBytes
function in your JavaScript and ensure that your server-side code correctly generates and returns the PDF in Base64 format. Happy coding!