Home > Web Front-end > JS Tutorial > How to Download a PDF File from a Binary String Returned by a Web Service Using JavaScript?

How to Download a PDF File from a Binary String Returned by a Web Service Using JavaScript?

Mary-Kate Olsen
Release: 2024-10-29 05:40:02
Original
604 people have browsed it

How to Download a PDF File from a Binary String Returned by a Web Service Using JavaScript?

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
Copy after login

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>
Copy after login

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!

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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template