问题
I am trying to serve a PDF file to the user, and I have a string containing the bytes in the PDF file. I want to write these bytes to the browser so the user can download the PDF file. However when I do this:
document.open('application/pdf');
document.write(myBytes);
I just get the bytes rendered as text, that is, they are in an HTML page (see screenshots). I want only the bytes specified to be rendered, without any HTML surrounding them. How can I do this?
回答1:
You can force file download with anchor
&& download
attribute trick or use iframe
Here's an example below
Snippet doesn't work because of sandboxed environment.
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>
来源:https://stackoverflow.com/questions/62437177/how-do-i-write-raw-bytes-to-the-browser-in-javascript