首頁  >  文章  >  web前端  >  如何在所有主要瀏覽器中顯示二進位字串的 PDF 檔案?

如何在所有主要瀏覽器中顯示二進位字串的 PDF 檔案?

Patricia Arquette
Patricia Arquette原創
2024-10-28 17:54:02244瀏覽

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

如何在JavaScript 中從二進位字串建立PDF 檔案

問題:
從下列位置擷取表示PDF 檔案的二進位字元串一個Web 服務,並以跨瀏覽器相容的方式將其轉換為可檢視的PDF。

嘗試的解決方案:
將二進位字串嵌入到資料 URI 中,但在 IE9 中遇到限制和 Firefox。

問題:
是否有其他方法可以為所有主要瀏覽器產生 PDF 文件,而無需修改 Web 服務實作?

解決方案:
結合使用Blob API 並將XMLHttpRequest 的responseType 設定為「blob」:

<br> var request = newVttpRe ();<br>request.open("GET", "/path/to/pdf", true); <br>request.responseType = "blob";<br>request.onload = function (e) {<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();

;

這種方法允許使用者下載PDF 文件,而不是將其嵌入網頁中,為查看PDF 提供跨瀏覽器相容的解決方案。

以上是如何在所有主要瀏覽器中顯示二進位字串的 PDF 檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn