13

I am using a react pdf viewer and I would like to set up worker locally. I have tried doing that like this:

import pdfjsWorker from "pdfjs-dist/build/pdf.worker.entry";

<Worker workerUrl={pdfjsWorker}>
    <Viewer
      fileUrl={url}
      defaultScale={SpecialZoomLevel.PageFit}
      plugins={[
        defaultLayoutPluginInstance
      ]}
    />
  </Worker>

But, that throws a warning:

Warning: Setting up fake worker

What is the correct way of import a worker then, why do I get this warning?

11 Answers 11

8
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.0.279/pdf.worker.min.js'

Add this after you import pdfjs-dist and try matching the version(here 3.0.279) as per the console error. It worked for me.

Edit: As the pdfjs-dist version changed, i get errors again. So instead of of hardcoding the version, i started using dynamic version which pdfjs-dist exports.

So the updated code looks like:

import * as pdfjsLib from 'pdfjs-dist/build/pdf'

pdfjsLib.GlobalWorkerOptions.workerSrc = `https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjsLib.version}/pdf.worker.min.js`
Sign up to request clarification or add additional context in comments.

Comments

3

I was facing similar issues resolved them by adding the pdf.worker.js

Git Refrence

I added the js file in the head for the worker.js i.e https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.10.377/pdf.worker.js

Then I correct the version (2.10.377 to 2.3.200) as per the console error and it starts loading the pdf Console error after adding the worker.js

Comments

2

Watch out!

pdfjs version must be the same

Use it like below please

import { Worker, Viewer } from '@react-pdf-viewer/core';
import '@react-pdf-viewer/core/lib/styles/index.css';

import { pdfjs } from 'react-pdf';

const YourComponent = () => {
  return (
    <div>
      <Worker workerUrl={`https://unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.js`}>
        <Viewer fileUrl={fileUrl} />
      </Worker>
    </div>
  )
};

Comments

1

In my case, instead of write the code like this:

<script src="/js/pdf.worker.min.js"></script>
<script src="/js/pdf.min.js"></script>

I wrote it as:

<!--script src="/js/pdf.worker.min.js"></script--> // removed
<script src="/js/pdf.min.js"></script>

$(function() {
  pdfjsLib.GlobalWorkerOptions.workerSrc = '/js/pdf.worker.min.js';    
});

Which made the warning disappear ... even though my PDF was rendered anyway - i just wanted that warning removed.

4 Comments

Which version? I added the same code using the version 2.14.305 and still having the same error
/js/pdf.min.js is Version 2.13.148 ( i uploaded it for you here: filemail.com/d/akbmlpnrqzosgtw ) but i'm migrating the code now to python's reportlab module, which is much much much better approach to me. i render the pdf as A4 and I don't need to guess the dimensions of the screen etc.. everything just works out natively and also you have much more control over the components inside the PDF. because with pdf.min.js when I created a "space" between the image & rendering components in each screen the "space" was rended differently (height&width) - it has no consistency ..
I'm using only javascript in a .NET mvc project, not a react app
This is not react, it's native javascript with python behind it ... but ok then, i hope my file attachment will be helpful for you
1

My use case was to make the PDF viewer working even when user went offline after initial page load.

I managed to load PDF worker from /public folder while using @react-pdf-viewer/core.

  1. Add your worker file in public folder. E.g. public/pdf.worker.min.js

  2. Add a pre loader in your index.html. As soon as the page loads, it will also load your worker. You should see this happen in the Network-tab.

<link rel="preload" href="/pdf.worker.min.js" as="script" />
  1. Use it like this
import { Worker, Viewer } from '@react-pdf-viewer/core';

           ...
              <>
                <Worker workerUrl={'/pdf.worker.min.js'}> // Now accessible when user goes offline
                  <Grid
                    item
                    style={{
                      height: '750px',
                      width: '750px,
                    }}
                  >
                    <Viewer
                      fileUrl={`data:application/pdf;base64,${YOUR_BASE_64}`}
                    />
                  </Grid>
                </Worker>
              </>
           ...

Comments

0

Worker component expects a workerUrl which is of type string. You might have to replace pdfjsWorker in your code with actual pdf-worker url.

const pdfVersion = "2.6.347"
const pdfWorkerUrl = `https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfVersion}/pdf.worker.js`
<Worker workerUrl={pdfWorkerUrl}>
    <Viewer
      fileUrl={url}
      defaultScale={SpecialZoomLevel.PageFit}
      plugins={[
        defaultLayoutPluginInstance
      ]}
    />
</Worker>

Note: Please make sure to set the same version for both pdfjs-dist and worker.

The official documentation mentions the same thing here: https://react-pdf-viewer.dev/docs/basic-usage/

Comments

0

I'm writing the following code in next.js and it works!

import "./index.css";

import * as PDFJS from "pdfjs-dist/build/pdf";
import * as PDFJSWorker from "pdfjs-dist/build/pdf.worker";

export default async function ReaderScreen(props: { filepath: string }) {
  PDFJS.GlobalWorkerOptions.workerSrc = PDFJSWorker;

  const pdf = await PDFJS.getDocument(props.filepath).promise;
  const pages = pdf["_pdfInfo"].numPages;

  return <div>Pages: {pages}</div>;
}

If, you see the following error in your code:

Typings Error

Then, create a index.d.ts file in typings directory and write the following code:

declare module "pdfjs-dist/build/pdf";
declare module "pdfjs-dist/build/pdf.worker";

And it should be works now.

Comments

0

The workerUrl of the Worker component from react-pdf-viewer expects an URL, but you tried to assign an imported file.

You should provide the URL of a valid pdf-worker.js file, i.e. the version of the worker must match the used pdfjs version.

You could use an own URL under your domain, or the URL from unpkg.com, or from cloudflare, or anywhere else, but you can not just import it as you did.

To host the pdf-worker.js file yourself you need to make it available under some specific URL under your domain. How you do that, depends on your environment. E.g. you might need to put it into a designated folder called /public, or /static, or create a specific route in some config file, or something different. Find out how you are supposed to host static or public files in your enviroments or frameworks.

You can copy the correct pdf-worker.js file from anywhere (so that you then can host it under some URL), but as you already have pdfjs-dist, you should find the pdf-worker.js file (or pdf-worker-min.js) somewhere under that folder (which is under the node_modules folder), and can copy it from there.

See also: pdfjs - What is a fake worker?

Comments

0

The solution is simple you just have to sync your pdf-dist from react-pdf to the the current pdf-dist dependency :

Uninstall the current version of pdfjs-dist:

npm uninstall pdfjs-dist

Install the compatible version:

npm install [email protected]

Verify the installation:

npm list pdfjs-dist react-pdf

You should see now:

[email protected]
├── [email protected]
└── [email protected] 
 -----pdfjs-dist@(should be the same here)    

So, the general idea is to have the same versions of pdf-dist when you run the command:

npm list pdfjs-dist react-pdf

Comments

-1
"use client";

import { Document, Page } from "react-pdf";

// Import the styles
import "@react-pdf-viewer/core/lib/styles/index.css";

import { pdfjs } from "react-pdf";

pdfjs.GlobalWorkerOptions.workerSrc = new URL(
  "pdfjs-dist/build/pdf.worker.min.js",
  import.meta.url
).toString();

interface IProps {
  url: string;
  pageNumber: number;
  onDocumentLoadSuccess?: (totalPages: number) => void;
}
const PdfViewer: React.FC<IProps> = ({
  pageNumber,
  url,
  onDocumentLoadSuccess,
}) => {
  function handleDocumentLoadSuccess({
    totalPages,
  }: {
    totalPages: number;
  }): void {
    if (onDocumentLoadSuccess) {
      onDocumentLoadSuccess(totalPages);
    }
  }
  return (
    <Document
      file={url}
      onLoadSuccess={({ numPages }) => {
        handleDocumentLoadSuccess({ totalPages: numPages });
      }}
      error="Failed to load Lecture"
      onError={(error) => console.error(error)}
    >
      <Page
        pageNumber={pageNumber}
        renderAnnotationLayer={false}
        renderTextLayer={false}
      />
    </Document>
  );
};

export default PdfViewer;

This working fine with me, i am using it with typescript and next js 14 version.

Comments

-1

This is how i solved this issue, first ensure that these dependencies are added in your package.json

"pdfjs": "^2.5.0",
"pdfjs-dist": "^3.7.107",

After that use these line in your js file

import * as pdfjs from "pdfjs-dist";
import pdfjsWorker from "pdfjs-dist/build/pdf.worker.entry";
pdfjs.GlobalWorkerOptions.workerSrc = pdfjsWorker;

And I think it should work fine after this,

I encountered this problem and tried several solutions suggested here, but none of them worked until I applied this fix. I found this solution in a GitHub repository called Open-Resume, so a big shout-out to them!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.