0

I am using pdf.js (version 3.6.172) in a project and are trying to use react-pdf (version 6.2.2). The problem is setting workerSrc as each package tries to use their own version and refuses to use a wrong version.

To load pdf.js I use:

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

and then, set workerSrc:

pdfjsLib.GlobalWorkerOptions.workerSrc = pdfjsWorker;

In the component that uses react-pdf, I use:

import { Document, Page, pdfjs } from 'react-pdf';
import pdfjsWorker from "react-pdf/node_modules/pdfjs-dist/build/pdf.worker.entry";
pdfjs.GlobalWorkerOptions.workerSrc = pdfjsWorker;

If I comment the react-pdf code, the pdf.js code works flawlessly. The same happens otherwise (when I comment the pdf.js code, the react-pdf code works OK).

Is there a way to both libraries be loaded in the same project?

MarcosCunhaLima
  • 191
  • 2
  • 11

1 Answers1

0

You can try to use the pdfjs directly from pdfjs-dist dependency instead of from react-pdf in the component that uses react-pdf, it may work if it's luck enough. In case of failure, there is no apparent solution as both rely on identical global variables, leading to overwriting of one another. it's the reason why you comment one, the other will work.

import { Document, Page } from 'react-pdf';
import * as pdfjs from 'pdfjs-dist';
import pdfjsWorker from 'pdfjs-dist/build/pdf.worker.entry';

pdfjs.GlobalWorkerOptions.workerSrc = pdfjsWorker;
Priestch
  • 21
  • 1
  • 4
  • HI, I've tried this too and it doesn't work, even if I change the name of the imported package (* as pdfjs1 for example) it seems that the name doesn't matter, it always keeps the pdfjs and pdfjsworker name (and overwrites the other). Thanks anyway – MarcosCunhaLima May 28 '23 at 14:45
  • The name of the imported package is just a local variable when you use it, so it's fine to have the same name. The real problem of `pdfjs-dist` is that when you use the package, it will set some properties of the global window, the properties are overwritten by the other package. I solved a similar problem, I can try to figure out how to resolve if you can setup a minimum repository. – Priestch May 28 '23 at 22:27
  • What I did is create my own pdfWiewer with pdf-js and stopped using react-pdf. Thanks for the help anyway. – MarcosCunhaLima May 30 '23 at 12:19