Constructing PDF Documents from Web Service Responses in JavaScript
Building PDF documents from binary strings returned by web services presents a cross-browser challenge. The data-uri method, while effective in certain browsers like Chrome and Opera, falls short in IE9 and Firefox.
Alternative Approach: Client-Side File Download
To overcome these limitations, an alternative approach involves creating PDF files on the file system for user download. To accomplish this, consider the following:
Setting Response Type to Blob
Configure the responseType property of the XMLHttpRequest object to "blob" instead of "text". This allows the client to receive the PDF data as a Blob object.
Utilizing the Blob Object
Create a new Blob object using the response obtained from the web service request.
Generating an Object URL
Generate an object URL for the Blob object, which represents the PDF file.
Creating a Download Link
Triggering the Download
Append the element to the document body and click on it to initiate the file download.
Example Code
The following JavaScript code demonstrates this approach:
<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) { // Generate .pdf name as `Blob` from `this.response` 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` after `Save As` dialog window.onfocus = function () { document.body.removeChild(a); }; }; }; request.send();</code>
This method ensures a reliable file download across multiple browsers, including IE9, Firefox, Chrome, Opera, and Safari.
The above is the detailed content of How can I reliably download a PDF file from a web service response across different browsers using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!