4

I am trying to display pdf using react-pdf in create-react-app application. I followed the instructions but the pdf is not displayed.

import { makeStyles, Box, Grid } from "@material-ui/core";
import React, { useState } from "react";
import Header from "./header";
import contractPdf from "../../sample.pdf";
import { Document, Page } from "react-pdf";

const useStyles = makeStyles((theme) => ({
  root: {
    padding: "32px 24px 14px 24px",
  },
  pdfArea: {
    borderRight: "1px solid #DDDDDD",
    height: "calc(100vh - 195px)",
  },
}));


const BasicComponent = (props) => {
  const classes = useStyles();
  const [numPages, setNumPages] = useState(null);
  const [pageNumber, setPageNumber] = useState(1);

  function onDocumentLoadSuccess({ numPages: nextNumPages }) {
    setNumPages(nextNumPages);
  }

  return (
    <Box className={classes.root}>
      <Header />
      <Grid container>
        <Grid item xs={8}>
          <Box className={classes.pdfArea}>
            <Document
              file={contractPdf}
              onLoadSuccess={onDocumentLoadSuccess}
              options={options}
            >
              <Page pageNumber={1} />
            </Document>
          </Box>
        </Grid>
        <Grid item xs={4}>
          <Box className={classes.inputArea}>User input</Box>
        </Grid>
      </Grid>
    </Box>
  );
};

export default BasicComponent;

I checked the debug in development mode and it shows Uncaught SyntaxError: Unexpected token '<' in pdf.worker.js

Can anyone help me? I appreciate your help. Thank you

3 Answers 3

3

I wasted so much time that I decided to write an answer to this question to help anybody in my situation avoid the waste of time. The instructions as described in the github site for react-pdf do not work with react 17.02 CRA 5 and Webpack 5.6.6 regarding the pdf.worker.js worker.

As the site indicates without giving a clear solution,

import { Document, Page } from 'react-pdf/dist/esm/entry.webpack5';

creates a heap out of memory error during compilation that is not fixed even by allocating 8 gigabytes of memory.

Using the standard instructions doesn't work either, creating an error that is dependent of the last web directory that was used in your react-router routes. This creates a weird bug, because sometimes it works and sometimes it doesn't.

The standard instructions say:

that you should add:

import { pdfjs } from 'react-pdf';
pdfjs.GlobalWorkerOptions.workerSrc = 'pdf.worker.min.js';

when using the .min file, instead of the regular .js file, that gave me the idea of adding the following:

import { pdfjs } from 'react-pdf';
pdfjs.GlobalWorkerOptions.workerSrc = 'pdf.worker.js';

But it didn't work either. To make it work I had to do the following:

  1. copy pdf.worker.js and pdf.worker.js.map from pdfjs-dist/legacy/build to public directory (it also works if you copy from the build - not legacy directory)

and,

  1. add to my code the following:

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

Yes, the '/' did it. Otherwise it'd go back to load my index.html from my /public directory.

Sign up to request clarification or add additional context in comments.

Comments

3

As per documentation you have to add this line in your code.(react-pdf)

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

4 Comments

I have the same issue: Uncaught SyntaxError: Unexpected token '<', but the funny part is that eventhough I implemented is as a component, and to test it I called a fixed string. It works from when called from some areas of my code and it doesn't from others. It's like it is interacting in ways that it is not supposed to with the rest of my react code.
I found that the times it works it is reading the correct worker file pdf.worker.js, but that the times it fails with this error code it is reding my index.html file and failing on the <!DOCTYPE html> tag of the html. Very weird, why does it find the correct worker file when the component is called from one place in the code and not when called from another? The worker files .js and .map are located in the /public file of the project.
found the source of the problem, the location where react-pdf searches for the pdf.worker.js file is history dependent on your react-router location stack. When it work it was loading from localhost:3000/pdf.worker.js and when it doesn't it loads from localhost:3000/p/pdf.worker.js where it ends up loading the index.html as if it was the worker file.
found the problem and the solution and decided to post an answer to the question, to save others my day of straggle...
0

Been racking my brain over being able to import the library locally.

Basically the documentation hands off the responsibility of making pdfjs-dist locally. Meaning it's required to install that dependency to be able to import it locally.

pnpm add pdfjs-dist
import { Document, Page, pdfjs } from 'react-pdf';

import 'react-pdf/dist/Page/AnnotationLayer.css';
import 'react-pdf/dist/esm/Page/TextLayer.css';
import './PDFViewer.css';

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

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.