reactjstypescriptpdf.jspdfjs-dist

how to use pdfjs worker in react and typescript?


I'm trying to use pdfjs in a react+ts project.

import React from "react";
import * as pdfjs from "pdfjs-dist"

export default function EditPdf() {
  React.useEffect(()=>{    
    const doc = pdfjs.getDocument("helloworld.pdf");
    doc.promise.then((pdf)=>{
      console.log(pdf)
    })
  },[])  
  return (
        <div>
            content
        </div>
    )
  }

Here I import it but I get the error:

Error: No "GlobalWorkerOptions.workerSrc" specified.
    at get workerSrc (http://localhost:5173/node_modules/.vite/deps/pdfjs-dist.js?v=aab08523:12098:11)
    at _PDFWorker._initialize (http://localhost:5173/node_modules/.vite/deps/pdfjs-dist.js?v=aab08523:11983:7)
    at new _PDFWorker (http://localhost:5173/node_modules/.vite/deps/pdfjs-dist.js?v=aab08523:11956:10)
    at getDocument (http://localhost:5173/node_modules/.vite/deps/pdfjs-dist.js?v=aab08523:11120:69)
    at http://localhost:5173/src/EditPdf.tsx?t=1727811223984:24:17
    at commitHookEffectListMount (http://localhost:5173/node_modules/.vite/deps/chunk-W6L2VRDA.js?v=2bfcffa6:16915:34)
    at invokePassiveEffectMountInDEV (http://localhost:5173/node_modules/.vite/deps/chunk-W6L2VRDA.js?v=2bfcffa6:18324:19)
    at invokeEffectsInDev (http://localhost:5173/node_modules/.vite/deps/chunk-W6L2VRDA.js?v=2bfcffa6:19701:19)
    at commitDoubleInvokeEffectsInDEV (http://localhost:5173/node_modules/.vite/deps/chunk-W6L2VRDA.js?v=2bfcffa6:19686:15)
    at flushPassiveEffectsImpl (http://localhost:5173/node_modules/.vite/deps/chunk-W6L2VRDA.js?v=2bfcffa6:19503:13)

Well online it seems "easy" enough... I can do something like:

import pdfjsWorker from "pdfjs-dist/build/pdf.worker.entry";

// ...
pdfjs.GlobalWorkerOptions.workerSrc = pdfjsWorker

but pdf.worker.entry doesn't exist. I searched in the node_modules folder and found a similarly named pdf.worker.mjs file. I tried to import with import pfdjsWorker from "pdfjs-dist/build/pdf.worker.entry" but it cannot find the declaration for this. Finally I noticed that there exists a pdfjs.PDFWorker type declaration, but I am not sure how to use it (no documentation).

How can I successfully import and use pdfjs + a worker in a React+TS proj?


Solution

  • This worked for me:

    Helpful articles:

    https://medium.com/@hesseclaus/using-pdfjs-with-react-app-rewired-f1f3a2527c45

    https://mozilla.github.io/pdf.js/examples/index.html#interactive-examples