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.
CodePudding user response:
Try;
const blob = new Blob([arrayBuffer], { type: "application/pdf" });
const url = URL.createObjectURL(blob);
window.open(url, '_blank');
CodePudding user response:
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" });