Display byte array as PDF in browser with print button?
In modern browsers, you can use a Blob to create an object URL which can then be used instead of a base64 URL (which has some limitations in different browsers, like length limits).
Here's a working example that does that. This sample displays the PDF inside an iframe
, but you can really do whatever you want with that objectURL
like open it in a new tab or whatever.
var xhr = new XMLHttpRequest();
xhr.responseType = 'arraybuffer';
xhr.onload = function() {
// Create the Blob URL:
var buffer = xhr.response;
var blob = new Blob([buffer], {
type: 'application/pdf'
});
var objectURL = URL.createObjectURL(blob);
// Create an iframe to demonstrate it:
var iframe = document.createElement('iframe');
iframe.className = 'sample-iframe';
iframe.src = objectURL;
document.body.appendChild(iframe);
console.log(objectURL);
};
xhr.open('GET', 'https://gist.githubusercontent.com/AlexanderOMara/4cd0ae77a3027a8363eecb5929b30ee3/raw/900734831709f3cb94718649ca8f7f9715adeb78/hello-world.pdf', true);
xhr.send();
html, body {
width: 100%;
height: 100%;
}
.sample-iframe {
width: 90%;
height: 90%;
}
Of course, the browser's built-in print function for the PDF will work also.
Manish Makkad
Updated on June 15, 2022Comments
-
Manish Makkad almost 2 years
I am working on an application where I have to display PDF on browser. I am getting PDF byte array from third party via webAPI. One of the way i found out to display pdf is as below.
var pdfAsDataUri = "data:application/pdf;base64,"+byteArray; window.open(pdfAsDataUri);
I don't like this approach because it displays base64 encoded format in URL, is there any other way to convert byte array into PDF and display in on HTML page along with the print dialog (
window.print()
). -
lukegf over 6 yearsThat code snippet doesn't work, at least not on Chrome. It shows a blank page.
-
Stephan almost 6 yearsAlso the pdf is not available under this url.
-
Alexander O'Mara almost 6 years@Stephan Unfortunately it seems crossorigin.me is having trouble serving the request at the moment.