Building PDF from Binary Web-Service Response in JavaScript
Background:
This question addresses the challenge of generating a PDF file from a binary string retrieved via an Ajax request. The provided binary stream consists of the PDF header and content. While the data-uri method works in some browsers, it fails in Internet Explorer 9 and Firefox.
The Issue:
The concern lies in finding a cross-browser solution that allows building a PDF file from the binary response without relying on editing the web-service implementation.
Solution:
To resolve this issue, the following approach is suggested:
Leveraging Blobs and Download Attributes:
By setting the responseType of the XMLHttpRequest object to "blob," the response will be received as a Blob object. This Blob represents the PDF file. Subsequently, you can create a download link using the createObjectURL method to allow users to download the PDF.
To demonstrate this solution, the following code snippet can be employed:
var request = new XMLHttpRequest();
request.open("GET", "/path/to/pdf", true);
request.responseType = "blob";
request.onload = function (e) {
if (this.status === 200) {
// `blob` response
console.log(this.response);
// create `objectURL` of `this.response` : `.pdf` as `Blob`
var file = window.URL.createObjectURL(this.response);
var a = document.createElement("a");
a.href = file;
a.download = this.response.name || "detailPDF";
document.body.appendChild(a);
a.click();
// remove `a` following `Save As` dialog,
// `window` regains `focus`
window.onfocus = function () {
document.body.removeChild(a)
}
};
};
request.send();
Benefits:
This method offers the following advantages:
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3