Home >Web Front-end >JS Tutorial >How to Generate a PDF from a Binary Web-Service Response in JavaScript Across Browsers?

How to Generate a PDF from a Binary Web-Service Response in JavaScript Across Browsers?

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 21:33:29468browse

How to Generate a PDF from a Binary Web-Service Response in JavaScript Across Browsers?

Building PDF from Binary Web-Service Response in JavaScript

Background:

This question addresses the challenge of generating a PDF file from a binary string retrieved via an Ajax request. The provided binary stream consists of the PDF header and content. While the data-uri method works in some browsers, it fails in Internet Explorer 9 and Firefox.

The Issue:

The concern lies in finding a cross-browser solution that allows building a PDF file from the binary response without relying on editing the web-service implementation.

Solution:

To resolve this issue, the following approach is suggested:

Leveraging Blobs and Download Attributes:

By setting the responseType of the XMLHttpRequest object to "blob," the response will be received as a Blob object. This Blob represents the PDF file. Subsequently, you can create a download link using the createObjectURL method to allow users to download the PDF.

To demonstrate this solution, the following code snippet can be employed:

<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>

Benefits:

This method offers the following advantages:

  • Compatibility with all major browsers, including IE9, Firefox, Opera, Chrome, and Safari
  • Avoids the deficiencies encountered with the data-uri approach in some browsers
  • Allows users to conveniently download the PDF file

The above is the detailed content of How to Generate a PDF from a Binary Web-Service Response in JavaScript Across Browsers?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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