0

I'm following the tutorial here for React-PDF

I essentially added the sample github repository to my codesandbox. My CodeSandbox file is linked here

in my codesandbox I've created a page with the PDF to be displayed at https://ynk0g.csb.app/ But I'm always getting a message that the PDF cannot load. I know the PDF file is valid

I found additional helpful resources on this on StackOverflow such as here: Unable to display pdf file using react-pdf That adds some additional imports .. but the PDF is still unable to load

When I Inspect the error in the browser I get

Error: Worker was destroyed
    at _fetchDocument (https://ynk0g.csb.app/node_modules/pdfjs-dist/legacy/build/pdf.js:10039:27)

    at eval (https://ynk0g.csb.app/node_modules/pdfjs-dist/legacy/build/pdf.js:9990:27)

I'm not sure how to go about fixing this.

My component with the PDF reader is below, called <PDFReader />:

import React, { useState } from "react";
import { Document, Page } from "react-pdf/dist/esm/entry.parcel";
import "react-pdf/dist/esm/Page/AnnotationLayer.css";
import { pdfjs } from 'react-pdf';


import "./Sample.less";

import pdfFile from "./sample.pdf";

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

const options = {
  cMapUrl: "cmaps/",
  cMapPacked: true
};

export default function Sample() {
  const [file, setFile] = useState(pdfFile);
  const [numPages, setNumPages] = useState(null);

  function onFileChange(event) {
    setFile(event.target.files[0]);
  }

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

  return (
    <div className="Example">
      <header>
        <h1>react-pdf sample page</h1>
      </header>
      <div className="Example__container">
        <div className="Example__container__load">
          <label htmlFor="file">Load from file:</label>{" "}
          <input onChange={onFileChange} type="file" />
        </div>
        <div className="Example__container__document">
          <Document
            file={file}
            onLoadSuccess={onDocumentLoadSuccess}
            options={options}
          >
            {Array.from(new Array(numPages), (el, index) => (
              <Page key={`page_${index + 1}`} pageNumber={index + 1} />
            ))}
          </Document>
        </div>
      </div>
    </div>
  );
}

Thanks so much

Katie Melosto
  • 1,047
  • 2
  • 14
  • 35
  • Thanks the the heads up, @KJ I fixed the CodeSandbox - sorry about that – Katie Melosto Jan 06 '22 at 20:53
  • 1
    On a project I use the same library and it works fine, the only difference I see is that i import Document and Page from 'react-pdf' not from the librery you specify on your code. Also, on the Document component, i define a prop called onContextMenu={(e)=> e.preventDefault()} you can try if this changes make it work – Hector Toro Jan 06 '22 at 21:16

0 Answers0