admin管理员组

文章数量:1252681

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?

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?

Share Improve this question asked Jan 29, 2021 at 14:05 LudwigLudwig 1,78114 gold badges68 silver badges142 bronze badges
Add a comment  | 

9 Answers 9

Reset to default 6
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`

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

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.

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>
  )
};

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/

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:

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.

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?

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>
              </>
           ...
"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.

本文标签: javascriptReact pdf jsWarning Setting up fake workerStack Overflow