1

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.

Foxocube
  • 710
  • 9
  • 32
  • 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: https://stackoverflow.com/questions/19327749/javascript-blob-filename-without-link ... and also more in general here: https://blog.logrocket.com/programmatic-file-downloads-in-the-browser-9a5186298d5c/ – Diego D Mar 11 '22 at 13:33

2 Answers2

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" });
Foxocube
  • 710
  • 9
  • 32
3

Try;

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