reactjspdfreact-pdf

Create react app - how to copy pdf.worker.js file from pdfjs-dist/build to your project's output folder?


Since I can't use browser's pdf viewer in the network where the app is going to be used, I am testing a react-pdf package for loading PDF's with React. I have made a component where I am sending a url of my PDF that I get from backend:

import React, { useState } from 'react';
import { Document, Page } from 'react-pdf';

const PDFViewer = ({url}) => {
  const [numPages, setNumPages] = useState(null);
  const [pageNumber, setPageNumber] = useState(1);

  function onDocumentLoadSuccess({ numPages }) {
    setNumPages(numPages);
  }
 function onLoadError(error) {
   console.log(error);
 }

 function onSourceError(error) {
   console.log(error);
 }

  return (
    <div>
      <Document
        file={window.location.origin + url}
        onLoadSuccess={onDocumentLoadSuccess}
        onLoadError={onLoadError}
        onSourceError={onSourceError}
      >
        {[...Array(numPages).keys()].map((p) => (
          <Page pageNumber={p + 1} />
        ))}
      </Document>
    </div>
  );
};

export default PDFViewer;

But, on opening the PDFViewer I get an error

Error: Setting up fake worker failed: "Cannot read property 'WorkerMessageHandler' of undefined"

In documentation it says that you should set up service worker and that the recommended way is to do that with CDN:

import { pdfjs } from 'react-pdf';
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.min.js`;

But, I can't use CDN links for my project, and in the documentation it also says:

Create React App uses Webpack under the hood, but instructions for Webpack will not work. Standard instructions apply. Standard (Browserify and others) If you use Browserify or other bundling tools, you will have to make sure on your own that pdf.worker.js file from pdfjs-dist/build is copied to your project's output folder.

There are no instructions on how to do that with create-react-app. How can I set this up locally then?


Solution

  • 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