Reputation: 177
I want to display a PDF file that is stored using IPFS.
I'm using the React PDF package to display the file.
<div>
<Document
file = {"https://ipfs.io/ipfs/" + this.state.IPFSlink}
onLoadSuccess={this.onDocumentLoadSuccess}
>
<Page pageNumber={pageNumber} />
</Document>
</div>
However, when I run the page and get the IPFSlink (Which is correct) I get the error message
Failed to load PDF file.
and this error in the console
index.js:1446 Error: Setting up fake worker failed: "Cannot read property 'WorkerMessageHandler' of undefined". at pdf.js:11664
Has anyone experience trying to do this?
Upvotes: 1
Views: 3650
Reputation: 1367
It actually says it in their documentation here:
Create React App uses Webpack under the hood, so you can follow Webpack instructions.
Standard instructions will also work. In Create React App, you can copy
pdf.worker.js file from pdfjs-dist/build to public directory in order for
it to be copied to your project's output folder at build time.
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.
If you don't need to debug pdf.worker.js, you can use pdf.worker.min.js file instead, which is roughly half the size. For this to work, however, you will
need to specify workerSrc manually like so:
and here is the important bits (note if you use this method, you are responsible for placing the file pdf.worker.min.js
somewhere that your application can see it -- for example, the path below assumes that the pdf.worker.min.js
is at the root of your React Application -->
import { pdfjs } from 'react-pdf';
pdfjs.GlobalWorkerOptions.workerSrc = 'pdf.worker.min.js';
If you wanted to keep life really simple and just use a cloud available CDN, you could do -->:
import { pdfjs } from 'react-pdf';
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;
Just remember if you are using the CDN, and it is not part of your react app, you may need to include it in your Content Security Policy (CSP) exception list (if you use CSP)
Upvotes: 1
Reputation: 177
I was missing this at the top of the file:
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;
Upvotes: 4