Last active
December 11, 2024 00:57
-
-
Save bondgeek/d44657b2a65e45cb3a645454845fe500 to your computer and use it in GitHub Desktop.
open pdf in pop-up from a blob
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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."); | |
} | |
}; |
let's say I had pdf xyz.pdf and I want to show it on a new window how I can.
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
What is blobdata in line 12