How to Build a PDF File from Binary String Returned from a Web Service Using JavaScript
Encounters arise when attempting to render a PDF file from a binary string received via an Ajax request. Web browsers, namely Firefox and Internet Explorer 9, pose challenges when using the data:uri solution.
Issue
The binary string received resembles the following:
%PDF-1.4.... ..... ....hole data representing the file .... %% EOF
Attempted Solution
Embedding the data via data:uri proves effective in Opera and Chrome but fails in Firefox and Internet Explorer.
Potential Solution
Consider building the PDF file on the file system to enable user download. This method requires a client-side solution and compatibility with major browsers.
Revised Solution
Modify the XMLHttpRequest responseType to "blob." Then, substitute the window.open function with a download attribute at an element. This process initiates the download of the XMLHttpRequest response as a ".pdf" file.
<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>
The above is the detailed content of How to Download a PDF File from a Binary String Returned by a Web Service Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!