react-pdf vs @react-pdf/renderer
Generating PDF Documents in React Applications
react-pdf@react-pdf/rendererSimilar Packages:

Generating PDF Documents in React Applications

@react-pdf/renderer and react-pdf are both libraries used to handle PDFs in React, but they solve completely different problems. @react-pdf/renderer allows you to build PDF documents from scratch using React components and JSX, rendering them directly in the browser or on the server without needing external files. It is essentially a React renderer for PDFs. In contrast, react-pdf is a viewer library designed to display existing PDF files within a React application. It wraps the Mozilla PDF.js engine to render binary PDF data into HTML5 canvases, enabling features like zooming, paging, and text selection for documents that already exist.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
react-pdf5,800,48911,133309 kB235 months agoMIT
@react-pdf/renderer4,838,16116,712292 kB4233 months agoMIT

Generating vs. Viewing PDFs: @react-pdf/renderer vs. react-pdf

When working with PDFs in the React ecosystem, developers often confuse @react-pdf/renderer and react-pdf because their names sound similar. However, they serve opposite ends of the document lifecycle. One is a creation engine that turns JSX into binary PDF data, while the other is a viewing engine that turns binary PDF data into visible HTML. Understanding this distinction is critical for architectural decisions.

πŸ› οΈ Core Purpose: Creation vs. Consumption

@react-pdf/renderer is a document generator. It acts as a custom React renderer (similar to react-dom), but instead of outputting HTML to the browser DOM, it outputs a binary PDF stream. You write standard React components, apply styles using a CSS-in-JS approach, and the library compiles this into a valid PDF file. It runs entirely in JavaScript, meaning it works in the browser, Node.js, or serverless environments without needing external binaries like Ghostscript or Puppeteer.

// @react-pdf/renderer: Creating a dynamic invoice
import { Document, Page, Text, View, StyleSheet } from '@react-pdf/renderer';

const styles = StyleSheet.create({
  page: { padding: 30 },
  text: { fontSize: 12, marginBottom: 10 }
});

const InvoicePDF = ({ customerName, total }) => (
  <Document>
    <Page size="A4" style={styles.page}>
      <Text style={styles.text}>Invoice for: {customerName}</Text>
      <Text style={styles.text}>Total Due: ${total}</Text>
    </Page>
  </Document>
);

// Usage: <PDFDownloadLink document={<InvoicePDF name="John" total={50} />} fileName="inv.pdf" />

react-pdf is a document viewer. It does not create PDFs. Instead, it takes a URL or a binary blob of an existing PDF file and renders it onto an HTML5 <canvas> element using the PDF.js engine under the hood. Its primary job is to parse the complex binary structure of a PDF and paint it pixel-perfectly in the browser, handling interaction logic like scrolling, zooming, and page navigation.

// react-pdf: Displaying an existing manual
import { Document, Page, pdfjs } from 'react-pdf';
import 'react-pdf/dist/Page/AnnotationLayer.css';
import 'react-pdf/dist/Page/TextLayer.css';

// Set up the worker source (required for react-pdf)
pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.js`;

function PdfViewer() {
  const [numPages, setNumPages] = useState(null);

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

  return (
    <div>
      <Document file="/manuals/user-guide.pdf" onLoadSuccess={onDocumentLoadSuccess}>
        <Page pageNumber={1} />
      </Document>
      <p>Page 1 of {numPages}</p>
    </div>
  );
}

🎨 Styling and Layout: CSS Subset vs. Fixed Rendering

@react-pdf/renderer requires you to define layout using a specific subset of CSS properties. It uses Flexbox for layout management, which feels very natural to web developers. However, it does not support the full CSS specification. Properties like grid, complex selectors, or certain advanced positioning techniques are not available. You must think in terms of static pages with fixed dimensions (e.g., A4, Letter).

// @react-pdf/renderer: Flexbox layout for a report header
const styles = StyleSheet.create({
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    padding: 20,
    backgroundColor: '#f0f0f0'
  },
  logo: { width: 50, height: 50 },
  title: { fontSize: 18, fontWeight: 'bold' }
});

const ReportHeader = () => (
  <View style={styles.header}>
    <Image style={styles.logo} src="/logo.png" />
    <Text style={styles.title}>Annual Report 2024</Text>
  </View>
);

react-pdf has no styling system for the document content itself because the content is already baked into the PDF file. You cannot change the font, color, or layout of the text inside the PDF using CSS. You can only style the container around the PDF viewer (e.g., the canvas wrapper, shadows, or margins). The internal rendering is determined strictly by the binary data of the source file.

// react-pdf: Styling the viewer container, NOT the PDF content
const viewerStyles = {
  container: {
    display: 'flex',
    justifyContent: 'center',
    backgroundColor: '#333',
    padding: '20px'
  },
  canvasWrapper: {
    boxShadow: '0 4px 6px rgba(0,0,0,0.3)',
    maxWidth: '100%'
  }
};

function StyledViewer({ file }) {
  return (
    <div style={viewerStyles.container}>
      <div style={viewerStyles.canvasWrapper}>
        <Document file={file}>
          <Page pageNumber={1} />
        </Document>
      </div>
    </div>
  );
}

⚑ Performance and Environment: Pure JS vs. Heavy Canvas

@react-pdf/renderer is lightweight in terms of runtime dependencies because it is pure JavaScript. It does not require a web worker to function, although it can be computationally expensive if you are generating massive documents with thousands of nodes on the main thread. It excels in server-side rendering (SSR) scenarios where you might generate a PDF on a Node.js server and stream it directly to the client as a download, saving the client from doing any work.

// @react-pdf/renderer: Server-side generation pattern (Node.js)
import { renderToStream } from '@react-pdf/renderer';

app.get('/generate-report', async (req, res) => {
  const data = await fetchData();
  const stream = await renderToStream(<MyReport data={data} />);
  
  res.setHeader('Content-Type', 'application/pdf');
  res.setHeader('Content-Disposition', 'attachment; filename=report.pdf');
  
  stream.pipe(res);
});

react-pdf relies heavily on Web Workers to parse PDF files without freezing the browser UI. Parsing a large PDF is CPU-intensive, so the library offloads this work to a separate thread. This requires proper configuration of the pdfjs-dist worker source. If not configured correctly, the main thread will block, causing the UI to freeze. It is strictly a client-side library; it cannot run in a Node.js environment to "view" a PDF since there is no DOM or Canvas.

// react-pdf: Configuring the worker is mandatory for performance
import { pdfjs } from 'react-pdf';

// Correctly pointing to the worker file prevents main-thread blocking
pdfjs.GlobalWorkerOptions.workerSrc = new URL(
  'pdfjs-dist/build/pdf.worker.min.js',
  import.meta.url,
).toString();

// Without this, large files will cause the browser to hang during load
function OptimizedViewer({ fileUrl }) {
  return <Document file={fileUrl} loading={<div>Loading PDF...</div>}>
    <Page pageNumber={1} />
  </Document>;
}

πŸ” Text Interactivity: Static vs. Selectable

@react-pdf/renderer generates text that is natively selectable in the resulting PDF. Since the library constructs the PDF structure from scratch, it maps your <Text> components directly to PDF text objects. When a user opens the generated file in Adobe Reader or a browser viewer, they can highlight, copy, and search the text immediately.

// @react-pdf/renderer: Text is inherently selectable in output
const SelectableDoc = () => (
  <Document>
    <Page>
      <Text>This text is generated by React and will be selectable in the final PDF.</Text>
      <Text>You can copy this sentence directly from the downloaded file.</Text>
    </Page>
  </Document>
);

react-pdf also supports text selection, but it requires extra setup. By default, it renders the PDF as an image on a canvas. To enable text selection, copying, and accessibility, you must explicitly import and render the TextLayer alongside the Page component. This layer overlays invisible HTML text on top of the canvas pixels to mimic the PDF's text content.

// react-pdf: Enabling text selection requires the TextLayer component
import { Document, Page, TextLayer } from 'react-pdf';

function SelectableViewer({ file }) {
  return (
    <Document file={file}>
      <Page 
        pageNumber={1} 
        renderTextLayer={true} // Enables the text layer
        renderAnnotationLayer={true} // Enables links/forms
      />
    </Document>
  );
}
// Note: You must include the CSS for the text layer to position correctly

🌐 Similarities: Shared React Patterns

Despite their different goals, both libraries leverage React's component model to manage state and props.

1. βš›οΈ Component-Based Architecture

Both libraries allow you to encapsulate logic within reusable components. Whether you are building a reusable invoice row or a custom page navigator, the mental model remains consistent with standard React development.

// Both use props to pass data
// @react-pdf/renderer
const Row = ({ label, value }) => <Text>{label}: {value}</Text>;

// react-pdf
const PageNavigator = ({ currentPage, totalPages }) => (
  <div>Page {currentPage} of {totalPages}</div>
);

2. πŸ”„ State Management

Both rely on React state hooks (useState, useEffect) to handle dynamic updates. In the renderer, state might trigger a re-generation of the PDF blob. In the viewer, state controls the current page number or zoom level.

// Managing page state in react-pdf
const [pageNum, setPageNum] = useState(1);
<Document file={file}>
  <Page pageNumber={pageNum} />
</Document>
<button onClick={() => setPageNum(prev => prev + 1)}>Next</button>

3. πŸ“¦ Ecosystem Integration

Both integrate well with modern React tooling like TypeScript, Next.js, and Vite. They provide type definitions and work seamlessly within the standard build pipelines of create-react-app or custom Webpack configurations.

πŸ“Š Summary: Key Differences

Feature@react-pdf/rendererreact-pdf
Primary GoalCreate/Generate PDFs from scratchView/Render existing PDF files
InputReact Components (JSX)PDF File URL or Blob
OutputBinary PDF StreamHTML5 Canvas + DOM Layers
StylingCSS-in-JS (Flexbox subset)CSS for container only
EnvironmentBrowser, Node.js, ServerlessBrowser only (Client-side)
DependenciesPure JS (no external workers needed)Requires pdfjs-dist worker
Use CaseInvoices, Reports, TicketsDocument Readers, Archives

πŸ’‘ The Big Picture

The choice between these two libraries is not about which one is "better," but about which phase of the document lifecycle you are addressing.

@react-pdf/renderer is your factory. Use it when the document does not exist yet and needs to be assembled dynamically from your application's data. It replaces the need for backend-heavy solutions like Puppeteer or headless Chrome, allowing you to keep your PDF generation logic inside your React codebase.

react-pdf is your window. Use it when the document already exists and you need to present it to the user without forcing them to download it or leave your site. It provides a seamless, native-feeling experience for consuming static content.

Final Thought: In many mature applications, you will likely use both. You might use @react-pdf/renderer to generate a contract on the server, save it to storage, and then use react-pdf to display that same contract to the user for review and signature within the same React interface.

How to Choose: react-pdf vs @react-pdf/renderer

  • react-pdf:

    Choose react-pdf if you need to display existing PDF files to your users inside your web application. This library is the standard solution for building document viewers, e-book readers, or admin panels where users need to inspect uploaded contracts, manuals, or forms. It is not designed to create or edit PDFs, but rather to provide a high-performance, interactive interface for viewing binary PDF assets that are already stored on your server or CDN.

  • @react-pdf/renderer:

    Choose @react-pdf/renderer if your goal is to generate new PDF documents dynamically from data within your application. This is the correct tool for creating invoices, reports, certificates, or tickets where the content changes based on user input or database records. It allows you to define the layout using familiar React patterns and styles, making it ideal for projects that need to produce custom PDFs on the fly without relying on a backend service to generate the file.

README for react-pdf

npm downloads CI

React-PDF

Display PDFs in your React app as easily as if they were images.

Lost?

This package is used to display existing PDFs. If you wish to create PDFs using React, you may be looking for @react-pdf/renderer.

tl;dr

  • Install by executing npm install react-pdf or yarn add react-pdf.
  • Import by adding import { Document } from 'react-pdf'.
  • Use by adding <Document file="..." />. file can be a URL, base64 content, Uint8Array, and more.
  • Put <Page /> components inside <Document /> to render pages.
  • Import stylesheets for annotations and text layer if applicable.

Demo

A minimal demo page can be found in sample directory.

Online demo is also available!

Before you continue

React-PDF is under constant development. This documentation is written for React-PDF 10.x branch. If you want to see documentation for other versions of React-PDF, use dropdown on top of GitHub page to switch to an appropriate tag. Here are quick links to the newest docs from each branch:

Getting started

Compatibility

Browser support

React-PDF supports the latest versions of all major modern browsers.

Browser compatibility for React-PDF primarily depends on PDF.js support. For details, refer to the PDF.js documentation.

You may extend the list of supported browsers by providing additional polyfills (e.g. Array.prototype.at, Promise.allSettled or Promise.withResolvers) and configuring your bundler to transpile pdfjs-dist.

React

To use the latest version of React-PDF, your project needs to use React 16.8 or later.

Preact

React-PDF may be used with Preact.

Installation

Add React-PDF to your project by executing npm install react-pdf or yarn add react-pdf.

Next.js

If you use Next.js prior to v15 (v15.0.0-canary.53, specifically), you may need to add the following to your next.config.js:

module.exports = {
+ swcMinify: false,
}

Configure PDF.js worker

For React-PDF to work, PDF.js worker needs to be provided. You have several options.

Import worker (recommended)

For most cases, the following example will work:

import { pdfjs } from 'react-pdf';

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

[!WARNING] The workerSrc must be set in the same module where you use React-PDF components (e.g., <Document>, <Page>). Setting it in a separate file like main.tsx and then importing React-PDF in another component may cause the default value to overwrite your custom setting due to module execution order. Always configure the worker in the file where you render the PDF components.

[!NOTE] In Next.js, make sure to skip SSR when importing the module you're using this code in. Here's how to do this in Pages Router and App Router.

[!NOTE] pnpm requires an .npmrc file with public-hoist-pattern[]=pdfjs-dist for this to work.

See more examples
Parcel 2

For Parcel 2, you need to use a slightly different code:

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

Copy worker to public directory

You will have to make sure on your own that pdf.worker.mjs file from pdfjs-dist/build is copied to your project's output folder.

For example, you could use a custom script like:

import path from 'node:path';
import fs from 'node:fs';

const pdfjsDistPath = path.dirname(require.resolve('pdfjs-dist/package.json'));
const pdfWorkerPath = path.join(pdfjsDistPath, 'build', 'pdf.worker.mjs');

fs.cpSync(pdfWorkerPath, './dist/pdf.worker.mjs', { recursive: true });

Use external CDN

import { pdfjs } from 'react-pdf';

pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.mjs`;

[!WARNING] The workerSrc must be set in the same module where you use React-PDF components (e.g., <Document>, <Page>). Setting it in a separate file like main.tsx and then importing React-PDF in another component may cause the default value to overwrite your custom setting due to module execution order. Always configure the worker in the file where you render the PDF components.

Usage

Here's an example of basic usage:

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

function MyApp() {
  const [numPages, setNumPages] = useState<number>();
  const [pageNumber, setPageNumber] = useState<number>(1);

  function onDocumentLoadSuccess({ numPages }: { numPages: number }): void {
    setNumPages(numPages);
  }

  return (
    <div>
      <Document file="somefile.pdf" onLoadSuccess={onDocumentLoadSuccess}>
        <Page pageNumber={pageNumber} />
      </Document>
      <p>
        Page {pageNumber} of {numPages}
      </p>
    </div>
  );
}

Check the sample directory in this repository for a full working example. For more examples and more advanced use cases, check Recipes in React-PDF Wiki.

Support for annotations

If you want to use annotations (e.g. links) in PDFs rendered by React-PDF, then you would need to include stylesheet necessary for annotations to be correctly displayed like so:

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

Support for text layer

If you want to use text layer in PDFs rendered by React-PDF, then you would need to include stylesheet necessary for text layer to be correctly displayed like so:

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

Support for non-latin characters

If you want to ensure that PDFs with non-latin characters will render perfectly, or you have encountered the following warning:

Warning: The CMap "baseUrl" parameter must be specified, ensure that the "cMapUrl" and "cMapPacked" API parameters are provided.

then you would also need to include cMaps in your build and tell React-PDF where they are.

Copying cMaps

First, you need to copy cMaps from pdfjs-dist (React-PDF's dependency - it should be in your node_modules if you have React-PDF installed). cMaps are located in pdfjs-dist/cmaps.

Vite

Add vite-plugin-static-copy by executing npm install vite-plugin-static-copy --save-dev or yarn add vite-plugin-static-copy --dev and add the following to your Vite config:

+import path from 'node:path';
+import { createRequire } from 'node:module';

-import { defineConfig } from 'vite';
+import { defineConfig, normalizePath } from 'vite';
+import { viteStaticCopy } from 'vite-plugin-static-copy';

+const require = createRequire(import.meta.url);
+
+const pdfjsDistPath = path.dirname(require.resolve('pdfjs-dist/package.json'));
+const cMapsDir = normalizePath(path.join(pdfjsDistPath, 'cmaps'));

export default defineConfig({
  plugins: [
+   viteStaticCopy({
+     targets: [
+       {
+         src: cMapsDir,
+         dest: '',
+       },
+     ],
+   }),
  ]
});
Webpack

Add copy-webpack-plugin by executing npm install copy-webpack-plugin --save-dev or yarn add copy-webpack-plugin --dev and add the following to your Webpack config:

+import path from 'node:path';
+import CopyWebpackPlugin from 'copy-webpack-plugin';

+const pdfjsDistPath = path.dirname(require.resolve('pdfjs-dist/package.json'));
+const cMapsDir = path.join(pdfjsDistPath, 'cmaps');

module.exports = {
  plugins: [
+   new CopyWebpackPlugin({
+     patterns: [
+       {
+         from: cMapsDir,
+         to: 'cmaps/'
+       },
+     ],
+   }),
  ],
};
Other tools

If you use other bundlers, you will have to make sure on your own that cMaps are copied to your project's output folder.

For example, you could use a custom script like:

import path from 'node:path';
import fs from 'node:fs';

const pdfjsDistPath = path.dirname(require.resolve('pdfjs-dist/package.json'));
const cMapsDir = path.join(pdfjsDistPath, 'cmaps');

fs.cpSync(cMapsDir, 'dist/cmaps/', { recursive: true });

Setting up React-PDF

Now that you have cMaps in your build, pass required options to Document component by using options prop, like so:

// Outside of React component
const options = {
  cMapUrl: '/cmaps/',
};

// Inside of React component
<Document options={options} />;

[!NOTE] Make sure to define options object outside of your React component or use useMemo if you can't.

Alternatively, you could use cMaps from external CDN:

// Outside of React component
import { pdfjs } from 'react-pdf';

const options = {
  cMapUrl: `https://unpkg.com/pdfjs-dist@${pdfjs.version}/cmaps/`,
};

// Inside of React component
<Document options={options} />;

Support for JPEG 2000

If you want to ensure that JPEG 2000 images in PDFs will render, or you have encountered the following warning:

Warning: Unable to decode image "img_p0_1": "JpxError: OpenJPEG failed to initialize".

then you would also need to include wasm directory in your build and tell React-PDF where it is.

Copying wasm directory

First, you need to copy wasm from pdfjs-dist (React-PDF's dependency - it should be in your node_modules if you have React-PDF installed). cMaps are located in pdfjs-dist/wasm.

Vite

Add vite-plugin-static-copy by executing npm install vite-plugin-static-copy --save-dev or yarn add vite-plugin-static-copy --dev and add the following to your Vite config:

+import path from 'node:path';
+import { createRequire } from 'node:module';

-import { defineConfig } from 'vite';
+import { defineConfig, normalizePath } from 'vite';
+import { viteStaticCopy } from 'vite-plugin-static-copy';

+const require = createRequire(import.meta.url);
+
+const pdfjsDistPath = path.dirname(require.resolve('pdfjs-dist/package.json'));
+const wasmDir = normalizePath(path.join(pdfjsDistPath, 'wasm'));

export default defineConfig({
  plugins: [
+   viteStaticCopy({
+     targets: [
+       {
+         src: wasmDir,
+         dest: '',
+       },
+     ],
+   }),
  ]
});
Webpack

Add copy-webpack-plugin by executing npm install copy-webpack-plugin --save-dev or yarn add copy-webpack-plugin --dev and add the following to your Webpack config:

+import path from 'node:path';
+import CopyWebpackPlugin from 'copy-webpack-plugin';

+const pdfjsDistPath = path.dirname(require.resolve('pdfjs-dist/package.json'));
+const wasmDir = path.join(pdfjsDistPath, 'wasm');

module.exports = {
  plugins: [
+   new CopyWebpackPlugin({
+     patterns: [
+       {
+         from: wasmDir,
+         to: 'wasm/'
+       },
+     ],
+   }),
  ],
};
Other tools

If you use other bundlers, you will have to make sure on your own that wasm directory is copied to your project's output folder.

For example, you could use a custom script like:

import path from 'node:path';
import fs from 'node:fs';

const pdfjsDistPath = path.dirname(require.resolve('pdfjs-dist/package.json'));
const wasmDir = path.join(pdfjsDistPath, 'wasm');

fs.cpSync(wasmDir, 'dist/wasm/', { recursive: true });

Setting up React-PDF

Now that you have wasm directory in your build, pass required options to Document component by using options prop, like so:

// Outside of React component
const options = {
  wasmUrl: '/wasm/',
};

// Inside of React component
<Document options={options} />;

[!NOTE] Make sure to define options object outside of your React component or use useMemo if you can't.

Alternatively, you could use wasm directory from external CDN:

// Outside of React component
import { pdfjs } from 'react-pdf';

const options = {
  wasmUrl: `https://unpkg.com/pdfjs-dist@${pdfjs.version}/wasm/`,
};

// Inside of React component
<Document options={options} />;

Support for standard fonts

If you want to support PDFs using standard fonts (deprecated in PDF 1.5, but still around), or you have encountered the following warning:

The standard font "baseUrl" parameter must be specified, ensure that the "standardFontDataUrl" API parameter is provided.

then you would also need to include standard fonts in your build and tell React-PDF where they are.

Copying fonts

First, you need to copy standard fonts from pdfjs-dist (React-PDF's dependency - it should be in your node_modules if you have React-PDF installed). Standard fonts are located in pdfjs-dist/standard_fonts.

Vite

Add vite-plugin-static-copy by executing npm install vite-plugin-static-copy --save-dev or yarn add vite-plugin-static-copy --dev and add the following to your Vite config:

+import path from 'node:path';
+import { createRequire } from 'node:module';

-import { defineConfig } from 'vite';
+import { defineConfig, normalizePath } from 'vite';
+import { viteStaticCopy } from 'vite-plugin-static-copy';

+const require = createRequire(import.meta.url);
+const standardFontsDir = normalizePath(
+  path.join(path.dirname(require.resolve('pdfjs-dist/package.json')), 'standard_fonts')
+);

export default defineConfig({
  plugins: [
+   viteStaticCopy({
+     targets: [
+       {
+         src: standardFontsDir,
+         dest: '',
+       },
+     ],
+   }),
  ]
});
Webpack

Add copy-webpack-plugin by executing npm install copy-webpack-plugin --save-dev or yarn add copy-webpack-plugin --dev and add the following to your Webpack config:

+import path from 'node:path';
+import CopyWebpackPlugin from 'copy-webpack-plugin';

+const standardFontsDir = path.join(path.dirname(require.resolve('pdfjs-dist/package.json')), 'standard_fonts');

module.exports = {
  plugins: [
+   new CopyWebpackPlugin({
+     patterns: [
+       {
+         from: standardFontsDir,
+         to: 'standard_fonts/'
+       },
+     ],
+   }),
  ],
};
Other tools

If you use other bundlers, you will have to make sure on your own that standard fonts are copied to your project's output folder.

For example, you could use a custom script like:

import path from 'node:path';
import fs from 'node:fs';

const pdfjsDistPath = path.dirname(require.resolve('pdfjs-dist/package.json'));
const standardFontsDir = path.join(pdfjsDistPath, 'standard_fonts');

fs.cpSync(standardFontsDir, 'dist/standard_fonts/', { recursive: true });

Setting up React-PDF

Now that you have standard fonts in your build, pass required options to Document component by using options prop, like so:

// Outside of React component
const options = {
  standardFontDataUrl: '/standard_fonts/',
};

// Inside of React component
<Document options={options} />;

[!NOTE] Make sure to define options object outside of your React component or use useMemo if you can't.

Alternatively, you could use standard fonts from external CDN:

// Outside of React component
import { pdfjs } from 'react-pdf';

const options = {
  standardFontDataUrl: `https://unpkg.com/pdfjs-dist@${pdfjs.version}/standard_fonts/`,
};

// Inside of React component
<Document options={options} />;

User guide

Document

Loads a document passed using file prop.

Props

Prop nameDescriptionDefault valueExample values
classNameClass name(s) that will be added to rendered element along with the default react-pdf__Document.n/a
  • String:
    "custom-class-name-1 custom-class-name-2"
  • Array of strings:
    ["custom-class-name-1", "custom-class-name-2"]
errorWhat the component should display in case of an error."Failed to load PDF file."
  • String:
    "An error occurred!"
  • React element:
    <p>An error occurred!</p>
  • Function:
    this.renderError
externalLinkRelLink rel for links rendered in annotations."noopener noreferrer nofollow"One of valid values for rel attribute.
  • "noopener"
  • "noreferrer"
  • "nofollow"
  • "noopener noreferrer"
externalLinkTargetLink target for external links rendered in annotations.unset, which means that default behavior will be usedOne of valid values for target attribute.
  • "_self"
  • "_blank"
  • "_parent"
  • "_top"
fileWhat PDF should be displayed.
Its value can be an URL, a file (imported using import … from … or from file input form element), or an object with parameters (url - URL; data - data, preferably Uint8Array; range - PDFDataRangeTransport.
Warning: Since equality check (===) is used to determine if file object has changed, it must be memoized by setting it in component's state, useMemo or other similar technique.
n/a
  • URL:
    "https://example.com/sample.pdf"
  • File:
    import importedPdf from '../static/sample.pdf' and then
    sample
  • Parameter object:
    { url: 'https://example.com/sample.pdf' }
imageResourcesPathThe path used to prefix the src attributes of annotation SVGs.n/a (pdf.js will fallback to an empty string)"/public/images/"
inputRefA prop that behaves like ref, but it's passed to main <div> rendered by <Document> component.n/a
  • Function:
    (ref) => { this.myDocument = ref; }
  • Ref created using createRef:
    this.ref = createRef();
    …
    inputRef={this.ref}
  • Ref created using useRef:
    const ref = useRef();
    …
    inputRef={ref}
loadingWhat the component should display while loading."Loading PDF…"
  • String:
    "Please wait!"
  • React element:
    <p>Please wait!</p>
  • Function:
    this.renderLoader
noDataWhat the component should display in case of no data."No PDF file specified."
  • String:
    "Please select a file."
  • React element:
    <p>Please select a file.</p>
  • Function:
    this.renderNoData
onItemClickFunction called when an outline item or a thumbnail has been clicked. Usually, you would like to use this callback to move the user wherever they requested to.n/a({ dest, pageIndex, pageNumber }) => alert('Clicked an item from page ' + pageNumber + '!')
onLoadErrorFunction called in case of an error while loading a document.n/a(error) => alert('Error while loading document! ' + error.message)
onLoadProgressFunction called, potentially multiple times, as the loading progresses.n/a({ loaded, total }) => alert('Loading a document: ' + (loaded / total) * 100 + '%')
onLoadSuccessFunction called when the document is successfully loaded.n/a(pdf) => alert('Loaded a file with ' + pdf.numPages + ' pages!')
onPasswordFunction called when a password-protected PDF is loaded.Function that prompts the user for password.(callback) => callback('s3cr3t_p4ssw0rd')
onSourceErrorFunction called in case of an error while retrieving document source from file prop.n/a(error) => alert('Error while retrieving document source! ' + error.message)
onSourceSuccessFunction called when document source is successfully retrieved from file prop.n/a() => alert('Document source retrieved!')
optionsAn object in which additional parameters to be passed to PDF.js can be defined. Most notably:
  • cMapUrl;
  • httpHeaders - custom request headers, e.g. for authorization);
  • withCredentials - a boolean to indicate whether or not to include cookies in the request (defaults to false)
For a full list of possible parameters, check PDF.js documentation on DocumentInitParameters.

Note: Make sure to define options object outside of your React component or use useMemo if you can't.
n/a{ cMapUrl: '/cmaps/' }
renderModeRendering mode of the document. Can be "canvas", "custom" or "none". If set to "custom", customRenderer must also be provided."canvas""custom"
rotateRotation of the document in degrees. If provided, will change rotation globally, even for the pages which were given rotate prop of their own. 90 = rotated to the right, 180 = upside down, 270 = rotated to the left.n/a90
scaleDocument scale.10.5

Page

Displays a page. Should be placed inside <Document />. Alternatively, it can have pdf prop passed, which can be obtained from <Document />'s onLoadSuccess callback function, however some advanced functions like rendering annotations and linking between pages inside a document may not be working correctly.

Props

Prop nameDescriptionDefault valueExample values
canvasBackgroundCanvas background color. Any valid canvas.fillStyle can be used.n/a"transparent"
canvasRefA prop that behaves like ref, but it's passed to <canvas> rendered by <Canvas> component.n/a
  • Function:
    (ref) => { this.myCanvas = ref; }
  • Ref created using createRef:
    this.ref = createRef();
    …
    inputRef={this.ref}
  • Ref created using useRef:
    const ref = useRef();
    …
    inputRef={ref}
classNameClass name(s) that will be added to rendered element along with the default react-pdf__Page.n/a
  • String:
    "custom-class-name-1 custom-class-name-2"
  • Array of strings:
    ["custom-class-name-1", "custom-class-name-2"]
customRendererFunction that customizes how a page is rendered. You must set renderMode to "custom" to use this prop.n/aMyCustomRenderer
customTextRendererFunction that customizes how a text layer is rendered.n/a({ str, itemIndex }) => str.replace(/ipsum/g, value => `<mark>${value}</mark>`)
devicePixelRatioThe ratio between physical pixels and device-independent pixels (DIPs) on the current device.window.devicePixelRatio1
errorWhat the component should display in case of an error."Failed to load the page."
  • String:
    "An error occurred!"
  • React element:
    <p>An error occurred!</p>
  • Function:
    this.renderError
filterAnnotationsFunction to filter annotations before they are rendered.n/a({ annotations }) => annotations.filter(annotation => annotation.subtype === 'Text')
heightPage height. If neither height nor width are defined, page will be rendered at the size defined in PDF. If you define width and height at the same time, height will be ignored. If you define height and scale at the same time, the height will be multiplied by a given factor.Page's default height300
imageResourcesPathThe path used to prefix the src attributes of annotation SVGs.n/a (pdf.js will fallback to an empty string)"/public/images/"
inputRefA prop that behaves like ref, but it's passed to main <div> rendered by <Page> component.n/a
  • Function:
    (ref) => { this.myPage = ref; }
  • Ref created using createRef:
    this.ref = createRef();
    …
    inputRef={this.ref}
  • Ref created using useRef:
    const ref = useRef();
    …
    inputRef={ref}
loadingWhat the component should display while loading."Loading page…"
  • String:
    "Please wait!"
  • React element:
    <p>Please wait!</p>
  • Function:
    this.renderLoader
noDataWhat the component should display in case of no data."No page specified."
  • String:
    "Please select a page."
  • React element:
    <p>Please select a page.</p>
  • Function:
    this.renderNoData
onGetAnnotationsErrorFunction called in case of an error while loading annotations.n/a(error) => alert('Error while loading annotations! ' + error.message)
onGetAnnotationsSuccessFunction called when annotations are successfully loaded.n/a(annotations) => alert('Now displaying ' + annotations.length + ' annotations!')
onGetStructTreeErrorFunction called in case of an error while loading structure tree.n/a(error) => alert('Error while loading structure tree! ' + error.message)
onGetStructTreeSuccessFunction called when structure tree is successfully loaded.n/a(structTree) => alert(JSON.stringify(structTree))
onGetTextErrorFunction called in case of an error while loading text layer items.n/a(error) => alert('Error while loading text layer items! ' + error.message)
onGetTextSuccessFunction called when text layer items are successfully loaded.n/a({ items, styles }) => alert('Now displaying ' + items.length + ' text layer items!')
onLoadErrorFunction called in case of an error while loading the page.n/a(error) => alert('Error while loading page! ' + error.message)
onLoadSuccessFunction called when the page is successfully loaded.n/a(page) => alert('Now displaying a page number ' + page.pageNumber + '!')
onRenderAnnotationLayerErrorFunction called in case of an error while rendering the annotation layer.n/a(error) => alert('Error while loading annotation layer! ' + error.message)
onRenderAnnotationLayerSuccessFunction called when annotations are successfully rendered on the screen.n/a() => alert('Rendered the annotation layer!')
onRenderErrorFunction called in case of an error while rendering the page.n/a(error) => alert('Error while loading page! ' + error.message)
onRenderSuccessFunction called when the page is successfully rendered on the screen.n/a() => alert('Rendered the page!')
onRenderTextLayerErrorFunction called in case of an error while rendering the text layer.n/a(error) => alert('Error while rendering text layer! ' + error.message)
onRenderTextLayerSuccessFunction called when the text layer is successfully rendered on the screen.n/a() => alert('Rendered the text layer!')
pageColorsColors used to render the page. If not provided, the default colors from PDF will be used.n/a{ background: 'black', foreground: '#ffff00' }
pageIndexWhich page from PDF file should be displayed, by page index. Ignored if pageNumber prop is provided.01
pageNumberWhich page from PDF file should be displayed, by page number. If provided, pageIndex prop will be ignored.12
pdfpdf object obtained from <Document />'s onLoadSuccess callback function.(automatically obtained from parent <Document />)pdf
renderAnnotationLayerWhether annotations (e.g. links) should be rendered.truefalse
renderFormsWhether forms should be rendered. renderAnnotationLayer prop must be set to true.falsetrue
renderModeRendering mode of the document. Can be "canvas", "custom" or "none". If set to "custom", customRenderer must also be provided."canvas""custom"
renderTextLayerWhether a text layer should be rendered.truefalse
rotateRotation of the page in degrees. 90 = rotated to the right, 180 = upside down, 270 = rotated to the left.Page's default setting, usually 090
scalePage scale.10.5
widthPage width. If neither height nor width are defined, page will be rendered at the size defined in PDF. If you define width and height at the same time, height will be ignored. If you define width and scale at the same time, the width will be multiplied by a given factor.Page's default width300

Outline

Displays an outline (table of contents). Should be placed inside <Document />. Alternatively, it can have pdf prop passed, which can be obtained from <Document />'s onLoadSuccess callback function.

Props

Prop nameDescriptionDefault valueExample values
classNameClass name(s) that will be added to rendered element along with the default react-pdf__Outline.n/a
  • String:
    "custom-class-name-1 custom-class-name-2"
  • Array of strings:
    ["custom-class-name-1", "custom-class-name-2"]
inputRefA prop that behaves like ref, but it's passed to main <div> rendered by <Outline> component.n/a
  • Function:
    (ref) => { this.myOutline = ref; }
  • Ref created using createRef:
    this.ref = createRef();
    …
    inputRef={this.ref}
  • Ref created using useRef:
    const ref = useRef();
    …
    inputRef={ref}
onItemClickFunction called when an outline item has been clicked. Usually, you would like to use this callback to move the user wherever they requested to.n/a({ dest, pageIndex, pageNumber }) => alert('Clicked an item from page ' + pageNumber + '!')
onLoadErrorFunction called in case of an error while retrieving the outline.n/a(error) => alert('Error while retrieving the outline! ' + error.message)
onLoadSuccessFunction called when the outline is successfully retrieved.n/a(outline) => alert('The outline has been successfully retrieved.')

Thumbnail

Displays a thumbnail of a page. Does not render the annotation layer or the text layer. Does not register itself as a link target, so the user will not be scrolled to a Thumbnail component when clicked on an internal link (e.g. in Table of Contents). When clicked, attempts to navigate to the page clicked (similarly to a link in Outline). Should be placed inside <Document />. Alternatively, it can have pdf prop passed, which can be obtained from <Document />'s onLoadSuccess callback function.

Props

Props are the same as in <Page /> component, but certain annotation layer and text layer-related props are not available:

  • customTextRenderer
  • onGetAnnotationsError
  • onGetAnnotationsSuccess
  • onGetTextError
  • onGetTextSuccess
  • onRenderAnnotationLayerError
  • onRenderAnnotationLayerSuccess
  • onRenderTextLayerError
  • onRenderTextLayerSuccess
  • renderAnnotationLayer
  • renderForms
  • renderTextLayer

On top of that, additional props are available:

Prop nameDescriptionDefault valueExample values
classNameClass name(s) that will be added to rendered element along with the default react-pdf__Thumbnail.n/a
  • String:
    "custom-class-name-1 custom-class-name-2"
  • Array of strings:
    ["custom-class-name-1", "custom-class-name-2"]
onItemClickFunction called when a thumbnail has been clicked. Usually, you would like to use this callback to move the user wherever they requested to.n/a({ dest, pageIndex, pageNumber }) => alert('Clicked an item from page ' + pageNumber + '!')

Useful links

License

The MIT License.

Author

Wojciech Maj Wojciech Maj

Thank you

This project wouldn't be possible without the awesome work of Niklas NΓ€rhinen who created its original version and without Mozilla, author of pdf.js. Thank you!

Sponsors

Thank you to all our sponsors! Become a sponsor and get your image on our README on GitHub.

Backers

Thank you to all our backers! Become a backer and get your image on our README on GitHub.

Top Contributors

Thank you to all our contributors that helped on this project!

Top Contributors