Reputation: 10788
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.
Upvotes: 20
Views: 44369
Reputation: 41
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);
});
}
Upvotes: 3
Reputation: 3360
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);
Upvotes: 26