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:
<code class="javascript">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();</code>
Benefits:
This method offers the following advantages:
The above is the detailed content of How to Generate a PDF from a Binary Web-Service Response in JavaScript Across Browsers?. For more information, please follow other related articles on the PHP Chinese website!