This is incorrect:
let Document = require('react-pdf');
let Page = require('react-pdf');
You are importing the entire module when you do this. That means that Document and Page both contain all the modules of react-pdf. Instead what you want to do is either import ReactPDF and reference those modules:
const ReactPDF = require('react-pdf');
<ReactPDF.Document />
<ReactPDF.Page />
or you could use destructuring:
import { Document, Page } from 'react-pdf';
//or
const { Document, Page } = require('react-pdf');
If TypeScript complains about missing declarations, just add a @types folder to your project, create a subfolder inside of it called react-pdf and file inside that folder called index.d.ts with one line:
declare module "react-pdf"
Answer from Robbie Milejczak on Stack OverflowThis is incorrect:
let Document = require('react-pdf');
let Page = require('react-pdf');
You are importing the entire module when you do this. That means that Document and Page both contain all the modules of react-pdf. Instead what you want to do is either import ReactPDF and reference those modules:
const ReactPDF = require('react-pdf');
<ReactPDF.Document />
<ReactPDF.Page />
or you could use destructuring:
import { Document, Page } from 'react-pdf';
//or
const { Document, Page } = require('react-pdf');
If TypeScript complains about missing declarations, just add a @types folder to your project, create a subfolder inside of it called react-pdf and file inside that folder called index.d.ts with one line:
declare module "react-pdf"
- first add types
- if you are using create react app you should add:
import { Document, Page, pdfjs } from "react-pdf/dist/esm/entry.webpack";
pdfjs.GlobalWorkerOptions.workerSrc =`//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;
» npm install @types/react-pdf
Videos
» npm install react-pdf
This worked for me:
Import the package as below
import * as pdfjsLib from "pdfjs-dist";
Copy the pdf.worker.min.mjs file from node_modules/pdfjs-dist/build/ directory into your public folder
Set the worker to point to the file in your public folder
pdfjsLib.GlobalWorkerOptions.workerSrc = window.location.origin + "/pdf.worker.min.mjs";
Helpful articles:
https://medium.com/@hesseclaus/using-pdfjs-with-react-app-rewired-f1f3a2527c45
https://mozilla.github.io/pdf.js/examples/index.html#interactive-examples
I'm also running pdfjs v4 in vite and found this works:
import { GlobalWorkerOptions } from 'pdfjs-dist/legacy/build/pdf.mjs';
GlobalWorkerOptions.workerSrc = new URL('pdfjs-dist/legacy/build/pdf.worker.min.mjs', import.meta.url).toString();
(We're running a legacy build, but I assume the main build works the same way)
Vite won't recognise it's a js module and hence won't minify it, so I'm using the min.mjs version here.
» npm install @react-pdf/renderer
» npm install @pdf-viewer/react