Skip to content

Instantly share code, notes, and snippets.

@bondgeek
Last active July 26, 2023 13:38
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bondgeek/d44657b2a65e45cb3a645454845fe500 to your computer and use it in GitHub Desktop.
Save bondgeek/d44657b2a65e45cb3a645454845fe500 to your computer and use it in GitHub Desktop.
open pdf in pop-up from a blob
/* Use case: returning pdf as blob from XHR request,
for example when the endpoint is secure and needs an Authorization header
NB: responseType on fetch for blobData has to be "blob".
PDF files are not UTF-8, they are binary, so otherwise fonts won't appear properly
*/
const showFile = (blobData, reportName) => {
// Adapted from: https://blog.jayway.com/2017/07/13/open-pdf-downloaded-api-javascript/
const fileName = reportName && `${ reportName }.pdf` || 'myreport.pdf';
const newBlob = new Blob([blobData], {type: "application/pdf"});
const newWindow = window.open('', reportName, "width=800,height=1200");
if (!isNil(newWindow)) {
setTimeout( () => {
const dataUrl = window.URL.createObjectURL(newBlob);
const title = newWindow.document.createElement('title');
const iframe = newWindow.document.createElement('iframe');
title.appendChild(document.createTextNode(reportName));
newWindow.document.head.appendChild(title);
iframe.setAttribute('src', dataUrl);
iframe.setAttribute('width', "100%");
iframe.setAttribute('height', "100%");
newWindow.document.body.appendChild(iframe);
setTimeout( () => {
// For Firefox it is necessary to delay revoking the ObjectURL
window.URL.revokeObjectURL(dataUrl);
}, 100);
}, 100);
} else {
alert("To display reports, please disable any pop-blockers for this page and try again.");
}
};
@YogeshDhengale
Copy link

What is blobdata in line 12

@YogeshDhengale
Copy link

let's say I had pdf xyz.pdf and I want to show it on a new window how I can.

@bondgeek
Copy link
Author

blobData is the object into which you've read the pdf file. See this old SO question, which assumes you are using XMLHttpRequest.

I haven't tested this but you should be able to use Fetch in a similar fashion:

fetch("URL for xyz.pdf")
.then(res => res.blob())
.then(blobData => {
  showFile(blobData, 'myreport.pdf');
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment