Search code examples
javascripthtmlreactjsreact-pdfreact-pdf-viewer

Getting error when displaying a PDF file using react-pdf


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'

Solution

  • 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