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
2 Answers
Reset to default 5Eventually 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
版权声明:本文标题:Download PDF from javascript blob, without replacing the open page - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741622878a2388911.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论