Search code examples
javascriptpdfiframeblob

Display file.pdf As a Blob


I am working on different ways of displaying a PDF to get better on a project at work. I am able to insert a url to a PDF into an iframe element and it displays the PDF fine. Sometimes we have a use case where the front end receives a pdf as application/pdf instead of a url in a json object.

For this, I turn the application/pdf into a blob and create a url for the blob. This worked great on everything except Android, so I am testing out some methods with iFrame.

I would like to take this sample pdf http://www.pdf995.com/samples/pdf.pdf, turn it into a blob, and insert the blob url in the src of an iframe element for the purposes of testing blobs as iframe sources on Android Chrome browsers.

function App() {
  const samplePdf = "http://www.pdf995.com/samples/pdf.pdf"

  const blob = new Blob([samplePdf], { type: 'application/pdf' });

  const url = URL.createObjectURL(blob)

  return (
    <>
      <h1>iFrame Rendering of PDF Blob</h1>
      <iframe title="pdf" src={url} style={{ height: '1250px', width: '100%' }}></iframe>
    </>
  );
}

export default App;

This is what renders in the React app

What am I missing to get the content of the pdf to display? React is not a requirement, just seemed an easy way to start a quick practice project.


Solution

  • You need the data to construct the blob while the URL just points to the data you need. Let's go & get it:

    const getLocalPdfUrl = async () => {
      const url = 'http://www.pdf995.com/samples/pdf.pdf';
    
      const response = await fetch(url);
      const blob = await response.blob();
    
      return URL.createObjectURL(blob);
    };
    

    This function returns a Promise that will (hopefully) resolve with the URL you can use to construct the iframe. It's async, so, don't forget to wait for the promise to resolve.

    Testing note
    Fetching external resources from the frontend is restricted by CORS, so, pdf995.com's link will not work. It's also not a trivial task to find a dummy PDF document that would allow fetching itself from the FE.

    To test if it works, I'd propose to place the PDF file in the /public folder (or similar) & serve it on the same localhost as the app.