I tried to display a PDF file on website with react-pdf and react-pdf-viwer, but all failed.

The error showed in console is: SyntaxError: expected expression, got ‘<‘

This is caused by pdf.worker.js in pdfjs-dist, which is the dependency of the both two packages.

For React-pdf, you can eject by yourself follow the instruction in Readme.md on offical github page.

There is another simpler way, change the configuration to load the worker from an external CDN:

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

For React-pdf-viewer, this official guide may help you. But it does not work for me.

Later, I found another solution on StackOverflow. It’s not a beautiful solution but really works.

  1. Copy node_modules/pdfjs-dist/build to public/pdfjs-dist
  2. For React-pdf: options={{workerSrc: “/pdfjs-dist/build/pdf.worker.js”}} Add this props inside the Document component from react-pdf
    For React-pdf-viewer: Add <Worker workerUrl=’/pdfjs-dist/build/pdf.worker.js’> outside <Viewer>. Don’t forget import { Worker } from ‘@react-pdf-viewer/core’

Now, it should works well.


0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *