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.
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.)
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.
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.
Making a PDF non-downloadable is as simple as adding #toolbar=0 to the URL.
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);
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);
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With