Getting error when displaying a PDF file using react-pdf

9.8k Views Asked by At

I integrated the file uploader from the base UI and tried to display the uploaded file using react-pdf package. I tried converting the file as Blob and then uploaded it with the below code

const test = new Blob([file], { type: "application/pdf" });
    const fileURL = URL.createObjectURL(test);

Instead, I tried directly assigning the uploaded file to the Document tag but getting that file prop is accepting string instead received file type.

I tried using the file reader also but was unable to achieve it

Below is my code sandbox link:- https://codesandbox.io/s/base-web-file-uploader-basic-usage-forked-z8zpkr?file=/src/example.js:1712-1820

can anyone please help me in getting this issue resolved

And one more thing which i noticed is in the onLoadError prop was getting the below err

Error: Setting up fake worker failed: "Cannot read properties of undefined (reading 'WorkerMessageHandler'
2

There are 2 best solutions below

0
On BEST ANSWER

import the library from an alternetive folder, and add pdf worker using cdn:

import { Document, Page, pdfjs } from 'react-pdf/dist/esm/entry.webpack';
pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/legacy/build/pdf.worker.min.js`;

works for me

0
On

What worked for me was:

  1. Copy node_modules/pdfjs-dist/build/pdf.worker.js to public/pdf.worker.js
  2. options={{workerSrc: "pdf.worker.js"}} Add this props inside the Document component from react-pdf