react-pdf: pdf.worker.js returns Error 404

Hi,

When i try to use the webpack.entry import my app crashes and I can see a network request going to the current path/cba38462455a43d162b5.worker.js which is returning 404.

I am importing import { Document, Page } from 'react-pdf/build/entry.webpack'

Here is my webpack config:

const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');

const settings = {
  entry: {
    bundle: [
      'babel-polyfill',
      "./src/frontend/index.js"
    ]
  },
  output: {
    filename: "[name].js",
    path: path.resolve("build")
  },
  resolve: {
    extensions: [".js", ".jsx", ".json", ".css"]
  },
  devtool: "eval-source-map",
  module: {
    rules: [
      {
        test: /\.(js|jsx)?$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        options: {
          presets: [
            ["es2015", { modules: false }],
            "stage-0",
            "react"
          ],
          plugins: [
            "transform-decorators-legacy",
            "transform-node-env-inline"
          ],
          env: {
            development: {
              presets: ['react-hmre'],
              plugins: ["react-hot-loader/babel"]
            }
          }
        }
      },
      {
        test: /\.css$/,
         use: [ 'style-loader', 'css-loader','less-loader'],
        include: [/flexboxgrid/,/react-star-rating/]
      }
    ]
  },
  devServer: {
    contentBase: path.resolve("src/www"),
    publicPath: "http://localhost:8080/", // full URL is necessary for Hot Module Replacement if additional path will be added.
    quiet: false,
    hot: true,
    historyApiFallback: true,
    inline: true
  },
  plugins: [
    new webpack.NamedModulesPlugin(),
    new webpack.LoaderOptionsPlugin({
      debug: true
    }),
  ],
};

module.exports = settings;

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 2
  • Comments: 40 (13 by maintainers)

Most upvoted comments

I got it working ! as i am using commonjs as set in my tsconfig I must import it like this: import {Document, Page} from 'react-pdf/dist/umd/entry.webpack' not like import {Document, Page} from 'react-pdf' //BAD not working !

So its working now in my node/ express app

in my other app that just users dev server and react static I am using esnext, that is set in my tsconfig.json there i am importing it like

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

that works!

This means depending on the what module is set to will require it to be imported differently.

for commonjs ` import {Document, Page} from ‘react-pdf’

for esnext import {Document, Page} from 'react-pdf/dist/umd/entry.webpack'

For anyone trying to enable it in Next.js with webpack5

Tell webpack to treat pdf.worker.js as an asset

...
webpack(config) {
  config.module.rules.push({
    test: /pdfjs-dist\/build\/pdf\.worker\.js$/,
    type: "asset/resource",
    generator: {
      filename: "static/chunks/[name].[hash][ext]",
    },
  });
}
...

import it in your code and set URL manually

import { FC } from "react";
import { Document, Page, pdfjs } from "react-pdf";
import url from "pdfjs-dist/build/pdf.worker";

pdfjs.GlobalWorkerOptions.workerSrc = url;

its so tricky, you can use default cdn from PDF.js

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

For anyone looking for another solution for Typescript complaining about the import statement. Try to add this at the top of your tsx file. It worked for me.

const reactPdf = require('react-pdf/dist/esm/entry.webpack5')
const { Document, Page } = reactPdf

Dear Friends,

after I spent some time with this issue here are my solutions that worked.

I always had a typescript situation. @wojtekmaj I am very thankful to you for this library but I think this issue is undermining its usability. As each time I am using it, its always a topic.

Probably you can mention this thread in the docu.

Pointing to the cloudsource is rather not an option for many companies.

If you have a free configurable webpack config this is what worked. { test: /pdf\.worker\.min\.js$/, loader: 'url-loader', options: { name: 'pdfWorker.[ext]', limit: 1000, }, type: 'javascript/auto', },

Second time a had a create react app setup and didnt want to eject, so I hosted the min file just in the public folder of CRA

cp node_modules/pdfjs-dist/build/pdf.worker.min.js public/js/

Then in your code

pdfjs.GlobalWorkerOptions.workerSrc = /js/pdf.worker.min.js;

The workout around in above comment doesn’t work anymore as setOptions seems to have been deprecated or moved somewhere in the mean time. Reading the documentation leads to believe that the following could work:

import { pdfjs } from 'react-pdf';
pdfjs.GlobalWorkerOptions.workerSrc = `/path/to/your/worker.js`

It however does not work, as the path I see being tried in DevTools is still relative to the current url and is not absolute.

Update: Got it working. Would be keen to hear back on your opinion of this solution:

webpack updated to build my own pdf.worker

 entry: {
    bundle: [
      'babel-polyfill',
      "./src/frontend/index.js"
    ],
    'pdf.worker': 'pdfjs-dist/build/pdf.worker.entry'
  },
  output: {
    filename: "js/[name].js",
    path: path.resolve("build"),
    publicPath: 'js/'
}

setting workerSrc manually to the js output path

import Document from 'react-pdf/build/Document';
import Outline from 'react-pdf/build/Outline';
import Page from 'react-pdf/build/Page';
import React from 'react';
const pdfjs = require('pdfjs-dist');
pdfjs.PDFJS.workerSrc = '/js/pdf.worker.js';

i got a few deadlines to achieve right now. i can help out when i finish that stuff . the issue must be small , just an annoying type issue .

i noticed in the pass for libs that dont fully support typescript it was not worth my time working out types for them . my time is limited and i spend it it on building and fixing kick ass components. i surgest you do the same . 😀

Thanks Nick.

On Mon, 28 Sep 2020, 8:01 pm Rob Rendell, notifications@github.com wrote:

@nickjohngray https://github.com/nickjohngray I can’t use any as a type (it’s an import statement), but I can precede the import with a line saying // @ts-ignore to ignore the error. When I do that, everything works fine.

Ideally, I’d like to work out how to add the proper types. I’m trying to extend the module declaration by adding a .d.ts file:

import {pdfjs, Document, Page, Outline} from ‘react-pdf’;

declare module ‘react-pdf/dist/umd/entry.webpack’ { export {pdfjs, Document, Page, Outline}; }

… but that didn’t seem to fix the problem for me. I’m not proficient enough in Typescript to know what’s going on with that.

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/wojtekmaj/react-pdf/issues/97#issuecomment-699818238, or unsubscribe https://github.com/notifications/unsubscribe-auth/AD3TSIQUIASADKB6UASTNRDSIAYEZANCNFSM4ECOS2TQ .

I thank for all answers here but rather than using CDN

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

I would like to use the output file of my project to avoid cross-domain request but it doesn’t work if I set

pdfjs.GlobalWorkerOptions.workerSrc = '/dist/vendors~pdfjsWorker.js';

I liked a lot this tool but for me it seems it’s an error to ignore absolute path. I am working on a SPA app and if I try to access http://example.com/check/id/language the package doesn’t work.

Thanks.

Vite user here as well … or a workaround for “pdf.worker.js 404 (Not Found)”?

Thx

Any solutions for vite users? Getting

pdf.worker.js:1          GET http://localhost:5173/.../pdf.worker.js 404 (Not Found)
util.js:400 Warning: Setting up fake worker.
display_utils.js:526          GET http://localhost:5173/.../pdf.worker.js net::ERR_ABORTED 404 (Not Found)

@b-asaf Sometimes, specially on modern apps which have client-side routing instead of 404, a HTML page is returned, so you don’t see actual HTTP 404 error code, you see 200.