20

I have an ArrayBuffer of data for a PDF file and I would like to open it using the built-in PDF viewer for the browser.

Here is the code I am using:

const blob = new Blob([pdfBuffer], { type: 'application/pdf' });
const a = document.createElement('a');
a.href = window.URL.createObjectURL(blob);
a.download = fileName;
a.style.position = 'fixed';
a.target = '_blank';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);

This always results in the PDF file being downloaded to the downloads folder on the device rather than opening in a new tab with the PDF viewer in the browser. I have tested this in Chrome, Opera, and Firefox with the same results.

I have done this before when the PDF was actually downloaded from the server itself by just setting the Content-Disposition header in the response, but I am unsure how to do this with a client-side Blob like this.

1
  • 2
    Have you tried passing the string returned from createObjectURL to window.open()?
    – hbentlov
    Nov 6, 2018 at 13:31

2 Answers 2

24
+50

You can use window.open() on the result of window.URL.createObjectURL(blob) to open the PDF in a new window instead of downloading it. For example:

var blob = new Blob([pdfBuffer], {type: 'application/pdf'});
var blobURL = URL.createObjectURL(blob);
window.open(blobURL);
4
  • 3
    Great, thanks. Looks like I could just remove the a.download = fileName; part from my code as well.
    – kspearrin
    Nov 6, 2018 at 14:50
  • 4
    For me it's not working with Chome latest version Mar 15, 2022 at 16:45
  • 2
    What if I had to embed that blob onto the existing page instead of opening in new tab? Apr 7, 2022 at 0:20
  • For me it's working with Chrome version 122.0.6261.112
    – yaba
    Mar 19 at 10:22
3

Managed to do it very nicely in combination with pdfMake library.

//Preview PDF
export const previewDocument = (content) => {
  const pdfDocGenerator = pdfMake.createPdf(content);
  // Get PDF blob and open in new window
  pdfDocGenerator.getBlob((blob) => {
    let blobURL = URL.createObjectURL(blob);
    window.open(blobURL);
  });
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.