Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open PDF Blob using browser's PDF viewer rather than downloading?

Tags:

javascript

pdf

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.

like image 850
kspearrin Avatar asked Oct 30 '18 14:10

kspearrin


People also ask

How do I get a PDF to open in browser instead of downloading?

At the top right, click More Settings. At the bottom, click Show advanced settings. Under “Privacy”, click Content settings. Under “PDF Documents," check the box next to "Open PDF files in the default PDF viewer application.” (Uncheck this box if you want PDFs to open automatically when you click them.)

How do I force a file to open in browser instead of download?

Click on "Settings" and you'll see a new page pop up in your Chrome browser window. Scroll down to Advanced Settings, click Downloads, and clear your Auto Open options. Next time you download an item, it will be saved instead of opened automatically.

How do I open a BLOB file in browser?

If you cannot open your BLOB file correctly, try to right-click or long-press the file. Then click "Open with" and choose an application. You can also display a BLOB file directly in the browser: Just drag the file onto this browser window and drop it.

How do I make a PDF not downloadable?

Making a PDF non-downloadable is as simple as adding #toolbar=0 to the URL.


2 Answers

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);
like image 90
Matthew Schlachter Avatar answered Oct 09 '22 12:10

Matthew Schlachter


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);
  });
}
like image 3
Sarunas Avatar answered Oct 09 '22 14:10

Sarunas