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?
2
Answers
You can try grant the
workerSrc
by//mozilla.github.io/pdf.js/build/pdf.worker.mjs
. Please refer to this document: https://mozilla.github.io/pdf.js/examples/Try importing from
pdfjs-dist/webpack.mjs
And for typing you can declare module in
.d.ts
file. Code from myindex.d.ts
file: