admin管理员组

文章数量:1295710

I have a PDF being generated in the browser, and converted to a blob object. The "traditional" method of downloading this by using javascript to inject an a tag (example code below) opens the PDF in the browser, however this replaces the page the user had open causing them to lose any unsaved work. Adding target="_blank" doesn't change this, and the document still opens in the same tab.

const blob = new Blob([arrayBuffer], { type: "application/pdf" });
const url = URL.createObjectURL(blob);

const anchorElement = document.createElement('a');
anchorElement.href = url;
anchorElement.download = fileName;
anchorElement.target = "_blank";

anchorElement.click();
anchorElement.remove();
URL.revokeObjectURL(url);

I'd be happy with either opening the PDF in a new tab, or forcing it to be downloaded. As the PDF isn't being loaded from a URL, it's not possible to set any headers on it.

I have a PDF being generated in the browser, and converted to a blob object. The "traditional" method of downloading this by using javascript to inject an a tag (example code below) opens the PDF in the browser, however this replaces the page the user had open causing them to lose any unsaved work. Adding target="_blank" doesn't change this, and the document still opens in the same tab.

const blob = new Blob([arrayBuffer], { type: "application/pdf" });
const url = URL.createObjectURL(blob);

const anchorElement = document.createElement('a');
anchorElement.href = url;
anchorElement.download = fileName;
anchorElement.target = "_blank";

anchorElement.click();
anchorElement.remove();
URL.revokeObjectURL(url);

I'd be happy with either opening the PDF in a new tab, or forcing it to be downloaded. As the PDF isn't being loaded from a URL, it's not possible to set any headers on it.

Share asked Mar 11, 2022 at 13:23 FoxocubeFoxocube 7402 gold badges9 silver badges33 bronze badges 1
  • 1 afaik the download attribute is the key here and you set it already... so the only question arising is: did you correctly populate the fileName var with a valid string? There's a detailed discussion here about it: stackoverflow./questions/19327749/… ... and also more in general here: blog.logrocket./… – Diego D Commented Mar 11, 2022 at 13:33
Add a ment  | 

2 Answers 2

Reset to default 5

Eventually found a solution, incorrectly setting the MIME type on the blob breaks the browser's file type detection, and stops the built-in preview from starting.

const blob = new Blob([arrayBuffer], { type: "application/octet-stream" });

Try;

const blob = new Blob([arrayBuffer], { type: "application/pdf" });
const url = URL.createObjectURL(blob);
window.open(url, '_blank');

本文标签: Download PDF from javascript blobwithout replacing the open pageStack Overflow