Home > Web Front-end > JS Tutorial > body text

How to Display a PDF File from a Binary String in All Major Browsers?

Patricia Arquette
Release: 2024-10-28 17:54:02
Original
243 people have browsed it

How to Display a PDF File from a Binary String in All Major Browsers?

How to Build a PDF File from a Binary String in JavaScript

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)
    }
};
Copy after login

};
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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!