Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I load a PDF from url in React with react-pdf

The pdf I'm loading is coming from firebase. When I try to run the program, the app renders but the pdf document fails to load. Here are the errors:

Uncaught SyntaxError: Unexpected token '<' (at pdf.worker.js:1:1)

Error: Setting up fake worker failed: "Cannot read properties of undefined (reading 'WorkerMessageHandler')". at api.js:2285:1

These are the npm versions:

"@react-pdf/renderer": "^3.0.0",

"react-pdf": "^5.7.2"

Here's the component setup:

import { Document } from 'react-pdf'

function PDFPage() {

  return (
    <div>
      <Document file={{
      url:
        'https://firebasestorage.googleapis.com/v0/b/url-for-project-search.appspot.com/o/pdfs%2F%23000001.pdf?alt=media&token=94b5fb97',
    }} onLoadError={console.error} >
      </Document>
    </div>
  );
}

export default PDFPage;

Should i be loading the file from one Document's child components? What could be causing the syntax error in my node module from error 1?

The closest solution I could find was this one. This solution is for a different npm package. I tried it but it no progress was made. here are the new errors:

Access to fetch at 'https://firebasestorage.googleapis.com/v0/b/id-to-resource' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

https://firebasestorage.googleapis.com/v0/b/id-to-resource Failed to load resource: net::ERR_FAILED core.js:1961 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'message') at core.js:1961:1

The alternative setup:

import { Worker, Viewer } from '@react-pdf-viewer/core';


function PDFPage() {

  return (
    <div style= {{height:550}}>
    <Worker workerUrl="https://unpkg.com/[email protected]/build/pdf.worker.min.js">
        <Viewer fileUrl="https://firebasestorage.googleapis.com/v0/b/id-to-rearource" />

    ...
    </Worker>
    </div>
  );
}

export default PDFPage;
like image 963
codechef Avatar asked Dec 19 '25 16:12

codechef


1 Answers

Below solution works for me

  • STEP 1: Enable CORS in your cloud provider where pdf file is uploaded. In my case It was AWS and I added this for the CORS config for the bucket.
[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "GET"
        ],
        "AllowedOrigins": [
            "http://localhost:5173" // allowing this url to use GET
        ],
        "ExposeHeaders": []
    }
]
  • STEP 2: Fetch the pdf and render like below.

const arrayBuffer = await fetch(YOUR_PDF_URL);
const blob = await arrayBuffer.blob();
const url = await blobToURL(blob);


// utils
function blobToURL(blob) {
   return new Promise((resolve) => {
      const reader = new FileReader();
      reader.readAsDataURL(blob);
      reader.onloadend = function () {
         const base64data = reader.result;
         resolve(base64data);
      };
   });
}

// use the url here
return  <Document renderMode="canvas" file={url}> ... 

like image 50
Suman Biswas Avatar answered Dec 21 '25 05:12

Suman Biswas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!