Registry / serialization / react-pdf

react-pdf

JSON →
library10.4.1jsnpmunverified

React-PDF (currently at v10.4.1) is a JavaScript library for displaying PDF documents within React applications, leveraging Mozilla's PDF.js for rendering. It aims to simplify PDF integration by providing React components like `Document` and `Page`, abstracting the complexities of PDF.js. Major releases, such as v10.0.0, incorporate significant upgrades to the underlying PDF.js library, leading to enhanced stability and performance. The project maintains an active release cadence, with patch and minor updates released frequently to address bugs and introduce new features like customizable page colors and annotation filtering. A key differentiator since v10.1.0 is the support for functions as children within the `Document` component, which streamlines the API by offering direct access to PDF properties (e.g., `numPages`) without requiring manual state management or `onLoadSuccess` handlers, simplifying development. It ships with its own TypeScript definitions, making it well-suited for TypeScript projects.

npm install react-pdf
INSTALL
IMPORT
SIG · REACT-PDF
R
react-pdf
serializationjavascriptv10.4.1
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Document
import { Document } from 'react-pdf'
import Document from 'react-pdf'
The main component for loading and managing a PDF file. It's a named export.
Page
import { Page } from 'react-pdf'
Component for rendering an individual page of the PDF. It's a named export.
pdfjs
import { pdfjs } from 'react-pdf'
import * as pdfjs from 'pdfjs-dist'
Provides access to the underlying PDF.js library, primarily used for setting `GlobalWorkerOptions.workerSrc`. It's a named export re-exporting from pdfjs-dist.
AnnotationLayer.css
import 'react-pdf/dist/Page/AnnotationLayer.css'
import 'react-pdf/dist/esm/Page/AnnotationLayer.css'
Required stylesheet for displaying annotations. Since v10.0.0, the `/esm` path is removed and `/dist` is the direct path for ESM-only builds.

Demonstrates a basic PDF viewer using `Document` and `Page` components with the recommended 'functions as children' pattern (since v10.1.0) for dynamic page rendering and crucial `pdfjs.GlobalWorkerOptions.workerSrc` setup. It includes styling for a presentable viewer.

import React from 'react'; import { Document, Page, pdfjs } from 'react-pdf'; import 'react-pdf/dist/Page/AnnotationLayer.css'; import 'react-pdf/dist/Page/TextLayer.css'; // Configure the PDF.js worker source. This is crucial for react-pdf to function. // For optimal performance and reliability, consider self-hosting pdf.worker.min.mjs // or using a robust CDN in production. The exact path may vary based on your bundler setup. // Example for modern bundlers: pdfjs.GlobalWorkerOptions.workerSrc = new URL('pdfjs-dist/build/pdf.worker.min.mjs', import.meta.url).toString(); // For simplicity in this example, we use unpkg.com, but be aware of CDN reliability for critical applications. pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.mjs`; function MyPdfViewer() { const fileUrl = 'https://pdfjs-express.com/sample-docs/webviewer-demo-advanced.pdf'; // Example public PDF URL return ( <div style={{ fontFamily: 'sans-serif', maxWidth: '800px', margin: '20px auto', padding: '15px', border: '1px solid #eee', borderRadius: '8px', boxShadow: '0 2px 10px rgba(0,0,0,0.05)' }}> <h1 style={{ textAlign: 'center', color: '#333' }}>React-PDF Document Viewer</h1> <p style={{ textAlign: 'center', color: '#666', marginBottom: '20px' }}> A simple demonstration of rendering a PDF using <code>react-pdf</code> with the "functions as children" pattern. </p> <div style={{ border: '1px solid #ccc', borderRadius: '4px', overflow: 'hidden', backgroundColor: '#f9f9f9' }}> <Document file={fileUrl} onLoadError={(error) => console.error('Error loading PDF:', error)} loading="Loading PDF..." noData="No PDF file specified." > {({ pdf }) => ( pdf && Array(pdf.numPages) .fill(null) .map((_, index) => ( <div key={`page_${index + 1}`} style={{ marginBottom: '10px', borderBottom: index < pdf.numPages - 1 ? '1px solid #eee' : 'none' }}> <Page pageIndex={index} // pageIndex is 0-based width={760} // Adjust width to fit container or specific size renderAnnotationLayer={true} renderTextLayer={true} /> </div> )) )} </Document> </div> <p style={{ textAlign: 'center', marginTop: '20px', color: '#777', fontSize: '0.9em' }}> The PDF is loaded dynamically. Scroll to view all pages. </p> </div> ); } export default MyPdfViewer;
Debug
Known issues
breakingVersion 10.0.0 introduced significant breaking changes, including dropping CommonJS build (making it ESM-only), removing support for older browsers/Node.js versions, and updating import paths. It also includes a major PDF.js upgrade.
fix
Review the 'Upgrade guide from version 9.x to 10.x' on the GitHub Wiki. Update import paths (e.g., from `/dist/esm/Page/AnnotationLayer.css` to `/dist/Page/AnnotationLayer.css`). If using Jest, consider migrating to Vitest or configuring Jest for ESM. Ensure your browser/Node.js environment is up-to-date.
affects: >=10.0.0
gotchaThe `workerSrc` for PDF.js must be configured correctly and set in the same module where `react-pdf` components are used. Incorrect module execution order or placement can lead to the default worker overriding your custom setting, resulting in 'Failed to load PDF' errors.
fix
Always set `pdfjs.GlobalWorkerOptions.workerSrc` in the component file where you render `<Document>` or `<Page>`. For modern bundlers, use `new URL('pdfjs-dist/build/pdf.worker.min.mjs', import.meta.url).toString()`. If self-hosting, ensure the path is correct and accessible. For Next.js, consider dynamic import with `ssr: false`.
affects: >=1.0.0
breakingThe `Document` component's API was significantly simplified in v10.1.0 with the introduction of 'functions as children'. This new pattern allows direct access to PDF properties (like `pdf.numPages`) and is now the recommended way to render pages dynamically, largely superseding the need for `onLoadSuccess` and managing `numPages` in component state.
fix
Refactor `Document` usage to utilize the 'functions as children' pattern. Instead of `onLoadSuccess`, wrap your `Page` components in a function that receives `{ pdf }` and iterate `Array(pdf.numPages)` to render pages.
affects: >=10.1.0
gotchaHTML returned by `customTextRenderer` was not sanitized prior to v10.4.1, which could potentially lead to cross-site scripting (XSS) vulnerabilities if untrusted PDF content is rendered.
fix
Upgrade to `react-pdf` version 10.4.1 or newer. If upgrading immediately is not feasible, ensure that any custom HTML generated by `customTextRenderer` is thoroughly sanitized before being rendered to prevent arbitrary script execution.
affects: <10.4.1
Errors
Common errors & fixes
Failed to load pdf.worker.js
The PDF.js worker script (e.g., `pdf.worker.min.mjs` or `pdf.worker.min.js`) is not found at the specified `workerSrc` path, or the path is incorrect. This is a common misconfiguration of `pdfjs.GlobalWorkerOptions.workerSrc`.
fix
Verify that `pdfjs.GlobalWorkerOptions.workerSrc` is set correctly to the absolute path of the worker file. For modern bundlers, `new URL('pdfjs-dist/build/pdf.worker.min.mjs', import.meta.url).toString()` is often recommended. If using a CDN, ensure the version matches. Ensure the worker is accessible (e.g., copied to `public` folder in Next.js).
Worker was terminated
This error often occurs when the worker script encounters an issue or is prematurely terminated, sometimes due to rapid unmounting/remounting of PDF components or memory constraints, especially in older versions.
fix
Upgrade to at least `react-pdf@9.1.1`, which includes a fix for this specific error. For large PDFs or performance-sensitive applications, ensure efficient component lifecycle management and optimize PDF rendering parameters (e.g., `scale`, `width`, `height`).
SyntaxError: Unexpected token 'export' (or similar ESM/CJS mismatch errors in Jest)
Since `react-pdf` v10, the package is ESM-only. Jest (especially older versions or default configurations) might struggle with ESM modules, leading to syntax errors during testing.
fix
Configure Jest to handle ESM by adjusting `transformIgnorePatterns` or enabling experimental ECMAScript module support. The maintainer strongly recommends migrating testing frameworks to Vitest, which has better native ESM support.
Access to fetch at '...' from origin '...' has been blocked by CORS policy
When loading PDF files from an external URL, the server hosting the PDF does not include the necessary `Access-Control-Allow-Origin` HTTP header, preventing the browser from accessing the resource due to the Same-origin Policy.
fix
If you control the PDF server, configure it to include the `Access-Control-Allow-Origin` header for your domain. If not, consider proxying the PDF request through your backend or hosting the PDF on the same origin as your application. Ensure the server supports Partial Content requests for optimal performance.
Upgrade
Version history
10.4.1latest on npm
Audit
Dependencies
@types/reactrequiredPeer dependency for React type definitions, required for TypeScript projects.
reactrequiredCore React library for UI components.
react-domrequiredNeeded for rendering React components to the DOM.
Agent activity
13 hits · last 30 days
node
12
Resources
react-pdf — npm install react-pdf · libregistry