Download PDF on button click using jQuery
Introduction: Hello Guys, “Welcome back” Today i am here with another one new great article. In this article, I will explain with that how to download PDF File on click of button using jQuery. Firstly PDF file will be downloaded as BLOB using jQuery AJAX and XmlHttpRequest (XHR) and then will be sent for download in the Browser by using jQuery. The PDF file that you want to download on button click will be stored in a folder named download_pdf inside the main root folder of the project. On the other hand you can also set URL of the PDF as same server on which your project is running or any other server path.
Implementation: On the click of downoload buttom with the id named download_file, the JavaScript function named download_file will be called. Using the download_file JavaScript function, the path of the ile will be passed as a parameter to the jQuery AJAX function. Inside the jQuery AJAX function, using the XmlHttpRequest (XHR) call, the PDF file is downloaded as Byte Array (Binary Data).Please note that the XmlHttpRequest (XHR) call is work only in jQuery version 3.0 and its higher version. At the end, the received Byte Array (Binary Data) is converted to BLOB object and the File is downloaded in Browser.
Here i am giving the complete HTML code for HTML page. You can copy and paste this code to your HTML page to enjoy the execution of the Article.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<input type="button" value="Download PDF File" onclick="DownloadFile('Sample.pdf')" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<script type="text/javascript">
function download_file(fileName) {
//Set the File URL.
var url = "download_pdf/" + fileName;
$.ajax({
url: url,
cache: false,
xhr: function () {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 2) {
if (xhr.status == 200) {
xhr.responseType = "blob";
} else {
xhr.responseType = "text";
}
}
};
return xhr;
},
success: function (data) {
//Convert the Byte Data to BLOB object.
var blob = new Blob([data], { type: "application/octetstream" });
//Check the Browser type and download the File.
var isIE = false || !!document.documentMode;
if (isIE) {
window.navigator.msSaveBlob(blob, fileName);
} else {
var url = window.URL || window.webkitURL;
link = url.createObjectURL(blob);
var a = $("<a />");
a.attr("download", fileName);
a.attr("href", link);
$("body").append(a);
a[0].click();
$("body").remove(a);
}
}
});
};
</script>
</body>
</html>
Conclusion: In above code, I explained about the implementation how to download PDF File on click of button using jQuery. This code is very helpful for every developer. Bye Bye and take care of you all Developers. We will come back shortly with the new article.
Regards
Using Asp.net
Comments
Post a Comment