Introduction: Hello Guys, “Welcome back” Today, I am here with another one new great article. In this article I explained how to automatically download PDF File using JavaScript. The PDF file will be downloaded as BLOB using XmlHttpRequest AJAX call and then will be sent for download in the Browser using JavaScript. You can also set link or URL of the PDF which can belong to either same server or any other server location. The PDF file will be stored in a folder named download_pdf inside the project directory.
Join our Channel on Whtsapp and Telagram for All Updates
Automatically download PDF File using JavaScript
Implementation: On the event handler window.onload, the JavaScript function named download_pdf_file will be called. Inside the download_pdf_file JavaScript function, the URL or link of the PDF File will be passed through parameter to the GET call of the JavaScript XmlHttpRequest call. After that on the onload event handler, the received Byte Array (Binary Data) is converted to BLOB object and the File is downloaded in Browser. You can copy and paste the whole code on your HTML page to enjoy the program.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
window.onload = function () {
setTimeout(function () {
DownloadFile("Sample.pdf");
}, 1000);
};
function download_pdf_file (fileName) {
//Set the File URL.
var url = "download_pdf/" + fileName;
//Create XMLHTTP Request.
var req = new XMLHttpRequest();
req.open("GET", url, true);
req.responseType = "blob";
req.onload = function () {
//Convert the Byte Data to BLOB object.
var blob = new Blob([req.response], { 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 = document.createElement("a");
a.setAttribute("download", fileName);
a.setAttribute("href", link);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
};
req.send();
};
</script>
</body>
</html>
Conclusion: In above code, I have been explained how to automatically download PDF File using JavaScript. Bye and take care of you Developers. We will come back again shortly with the new article.
Regards
Programming Hub
No comments:
Post a Comment