You have to set GlobalWorkerOptions.workerSrc to /build/pdf.worker(.min).js of same version:
pdfjsLib.GlobalWorkerOptions.workerSrc =
"https://cdn.jsdelivr.net/npm/[email protected]/build/pdf.worker.min.js";
pdfjsLib.getDocument('./ahmed.pdf').promise.then(doc => {
console.log(`This document has ${doc._pdfInfo.numPages} pages.");
});
And, as @Pasi has mentioned, you have to promisify .getDocument() by chaining .promise on it. Without it, there is no .then().
You have to set GlobalWorkerOptions.workerSrc to /build/pdf.worker(.min).js of same version:
pdfjsLib.GlobalWorkerOptions.workerSrc =
"https://cdn.jsdelivr.net/npm/[email protected]/build/pdf.worker.min.js";
pdfjsLib.getDocument('./ahmed.pdf').promise.then(doc => {
console.log(`This document has ${doc._pdfInfo.numPages} pages.");
});
And, as @Pasi has mentioned, you have to promisify .getDocument() by chaining .promise on it. Without it, there is no .then().
See the "Hello World with document load error handling" example on this page to get started: https://mozilla.github.io/pdf.js/examples/
(Your snippet is missing .promise after getDocument() and setting the workerSrc property)
Install pdfjs-dist
import { Document, Page, pdfjs } from "react-pdf";
import pdfjsWorker from "pdfjs-dist/build/pdf.worker.entry";
pdfjs.GlobalWorkerOptions.workerSrc = pdfjsWorker;
Reference: https://github.com/mozilla/pdf.js/issues/8305
UPDATE
react-pdf >= 9.0.0
import { Document, Page, pdfjs } from "react-pdf";
import { WorkerMessageHandler } from "pdfjs-dist/build/pdf.worker.min.mjs";
pdfjs.GlobalWorkerOptions.workerSrc = new URL(
WorkerMessageHandler,
import.meta.url
).toString();
This also fixed a known issue:
Failed to load module script: Expected a JavaScript-or-Wasm module script but the server responded with a MIME type of "application/octet-stream". Strict MIME type checking is enforced for module scripts per HTML spec.
https://github.com/wojtekmaj/react-pdf/issues/1825
found a more efficient way of including the worker by including the library from the dependencies of react-pdf itself, this way you will never get a version mismatch like this The API version "2.3.45" does not match the Worker version "2.1.266"
if you install pdfjs-dist manually you will have to check react pdf dependency version on every build
import { Document, Page, pdfjs } from "react-pdf";
import pdfjsWorker from "react-pdf/node_modules/pdfjs-dist/build/pdf.worker.entry";
pdfjs.GlobalWorkerOptions.workerSrc = pdfjsWorker;
see similar error on pdfjs library : https://github.com/mozilla/pdf.js/issues/10997
hope it helps people
» npm install react-pdf