Problem:
Retrieve a binary string representing a PDF file from a web service and convert it into a viewable PDF in a cross-browser compatible manner.
Attempted Solution:
Embeding the binary string into a data URI, but encountering limitations in IE9 and Firefox.
Question:
Are there alternative methods for generating a PDF file for all major browsers, without requiring modifications to the web-service implementation?
Solution:
Utilizing the Blob API in conjunction with setting responseType of XMLHttpRequest to "blob":
<br>var request = new XMLHttpRequest();<br>request.open("GET", "/path/to/pdf", true); <br>request.responseType = "blob";<br>request.onload = function (e) {</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">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();
This approach allows users to download the PDF file rather than embedding it in a web page, providing a cross-browser compatible solution for viewing PDFs.
The above is the detailed content of How to Display a PDF File from a Binary String in All Major Browsers?. For more information, please follow other related articles on the PHP Chinese website!