Use mozilla pdf.js in create-react-app with typescript

3.1k views Asked by At

I try to find some documentation for how to include the mozilla pdf.js into a create-react-app with typescript configured. Unfortunately I only find a lot of people who are asking the same quetion but no working solutions.
At the moment I use the following approach and it seems to work. But I'm not sure if that is a good way of doing it.

I installed the dependencies with npm as shown below.

npm install --save @types/pdfjs-dist
npm install --save pdfjs-dist

And importing / configure it this way.

// Import pdf.js    
import * as pdfjsLib from 'pdfjs-dist';
pdfjsLib.GlobalWorkerOptions.workerSrc = process.env.PUBLIC_URL + '/assets/js/pdfjs/pdf.worker.min.js';

// Load pdf
pdfjsLib.getDocument('pdf_url').promise.then((promise: pdfjsLib.PDFDocumentProxy) => {
    console.log(promise.fingerprint);
});

Therefore I have to make sure that the files pdf.worker.js.map and pdf.worker.min.js were present inside the folder public/assets/js/pdfjs. Is there a more elegant way of solving the import of pdf.js?

Attached the react and pdfjs-dist version:

"pdfjs-dist": "^2.5.207",
"react": "^16.13.1",
"react-scripts": "3.4.3",
"typescript": "^3.7.5"
1

There are 1 answers

0
Karan Khirsariya On

I faced the similar issue. There are some solutions provided in github issue e.g. Here and Here but nothing worked for me. what worked for me in create-react-app with javascript is using es5 version of the build files from pdfjs-dist which are available at pdfjs-dist/es5/build/

import * as pdfjs from 'pdfjs-dist/es5/build/pdf';
import pdfjsWorker from 'pdfjs-dist/es5/build/pdf.worker.entry';

pdfjs.GlobalWorkerOptions.workerSrc = pdfjsWorker;

I'm not sure about typescript but should work the same.

versions:

"pdfjs-dist": "^2.7.570",
"react": "^17.0.1",