首页 > 解决方案 > 如何在 JavaScript 中将“原始”字节写入浏览器?

问题描述

我正在尝试向用户提供 PDF 文件,并且我有一个包含 PDF 文件中字节的字符串。我想将这些字节写入浏览器,以便用户下载 PDF 文件。但是,当我这样做时:

document.open('application/pdf');
document.write(myBytes);

我只是将字节呈现为文本,也就是说,它们位于 HTML 页面中(参见屏幕截图)。我只想渲染指定的字节,而不需要围绕它们的任何 HTML。我怎样才能做到这一点?

在 HTML 页面中呈现的 PDF 字节

我的 HTML 源代码

在此处输入图像描述

标签: javascriptpdf

解决方案


anchor您可以使用&&download属性技巧或使用强制文件下载iframe

下面是一个例子

由于沙盒环境,代码段不起作用。

const pdfView = document.querySelector("#pdfView");

fetch("https://cors-anywhere.herokuapp.com/https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf")
  .then(response => response.blob())
  .then(blob => blob.arrayBuffer())
  .then(myBytes => {
    const totalBlob = new Blob([myBytes], { type: 'application/pdf' });
    const url = window.URL.createObjectURL(totalBlob);
    const anchor = document.createElement("a");
    anchor.href = url;
    anchor.download = `document.pdf`;
    anchor.click();
    anchor.textContent = 'Download'
    document.body.appendChild(anchor);

    pdfView.src = url;  
  })
<iframe id="pdfView" src="" type="application/pdf" width="100%" height="100%" style="overflow: auto;">
    </iframe>


推荐阅读