wojtekmaj/react-pdf

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

README

npm downloads CI tested with jest

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 ``. `file` can be a URL, base64 content, Uint8Array, and more.- Put `` components inside `` to render pages.

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 6.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 all modern browsers. It is tested with the latest versions of Chrome, Edge, Safari, Firefox, and Opera.

The following browsers are supported in React-PDF v6:

- Chrome ≥76
- Edge (Chromium-based)
- Safari ≥14.1
- Firefox ≥90(?)

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

If you need to support older browsers, you will need to use React-PDF v5.

If you need to support Internet Explorer 11, you will need to use React-PDF v4.

React


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

If you use an older version of React, please refer to the table below to a find suitable React-PDF version.

ReactNewest
------------------------------------------------
≥16.8latest
≥16.35.x
≥15.54.x

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.

Usage


Here's an example of basic usage:

  1. ``` js
  2. import React, { useState } from 'react';
  3. import { Document, Page } from 'react-pdf';

  4. function MyApp() {
  5.   const [numPages, setNumPages] = useState(null);
  6.   const [pageNumber, setPageNumber] = useState(1);

  7.   function onDocumentLoadSuccess({ numPages }) {
  8.     setNumPages(numPages);
  9.   }

  10.   return (
  11.     <div>
  12.       <Document file="somefile.pdf" onLoadSuccess={onDocumentLoadSuccess}>
  13.         <Page pageNumber={pageNumber} />
  14.       </Document>
  15.       <p>
  16.         Page {pageNumber} of {numPages}
  17.       </p>
  18.     </div>
  19.   );
  20. }
  21. ```

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.

Configure PDF.js worker


For React-PDF to work, PDF.js worker needs to be provided.

To make it easier, special entry files were prepared for most popular bundlers. You can find them in the table below.

For example, if you want to use React-PDF with Webpack 5, instead of writing:

  1. ``` js
  2. import { Document, Page } from 'react-pdf';
  3. ```

write:

  1. ``` js
  2. import { Document, Page } from 'react-pdf/dist/esm/entry.webpack5';
  3. ```

BundlerEntry
--------------------------------------------
Parcel`react-pdf/dist/esm/entry.parcel`
Parcel`react-pdf/dist/esm/entry.parcel2`
Vite`react-pdf/dist/esm/entry.vite`
Webpack`react-pdf/dist/esm/entry.webpack`
Webpack`react-pdf/dist/esm/entry.webpack5`

Webpack 4


If you want to use React-PDF with Webpack 4, you'll need to manually install file-loader package.

Create React App


Create React App 4 (react-scripts@4.0.0) uses Webpack 4 under the hood, so you can use the entry file built for Webpack 4.

Create React App 5 (react-scripts@5.0.0) uses Webpack 5 under the hood, so the aim is to use the entry file built for Webpack 5. However, the way Webpack is configured in CRA 5 causes it to crash at build time on most machines with _JavaScript heap out of memory_ error.

Standard instructions will also work with Create React App. Please note that in CRA, you can copypdf.worker.js file from pdfjs-dist/build to public directory in order for it to be copied to your project's output folder at build time.

Standard (Browserify, esbuild and others)


If you use Browserify, esbuild, or other bundlers, you will have to make sure on your own that pdf.worker.js file from pdfjs-dist/build is copied to your project's output folder.

For example, you could use a custom script like:

  1. ``` js
  2. import path from 'path';
  3. import fs from 'fs';

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

  6. fs.copyFileSync(pdfWorkerPath, './dist/pdf.worker.js');
  7. ```

If you don't need to debug pdf.worker.js, you can use pdf.worker.min.js file instead, which is roughly half the size. For this to work, however, you will need to specify workerSrc manually like so:

  1. ``` js
  2. import { pdfjs } from 'react-pdf';
  3. pdfjs.GlobalWorkerOptions.workerSrc = 'pdf.worker.min.js';
  4. ```

Alternatively, you could use the minified pdf.worker.min.js from an external CDN:

  1. ``` js
  2. import { pdfjs } from 'react-pdf';
  3. pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.js`;
  4. ```

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:

  1. ``` js
  2. import 'react-pdf/dist/esm/Page/AnnotationLayer.css';
  3. ```

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:

  1. ``` js
  2. import 'react-pdf/dist/esm/Page/TextLayer.css';
  3. ```

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:

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

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.

Webpack

Add copy-webpack-plugin to your project if you haven't already:

  1. ```
  2. npm install copy-webpack-plugin --save-dev
  3. ```

Now, in your Webpack config, import the plugin:

  1. ``` js
  2. import path from 'path';
  3. import CopyWebpackPlugin from 'copy-webpack-plugin';
  4. ```

and in plugins section of your config, add the following:

  1. ``` js
  2. new CopyWebpackPlugin({
  3.   patterns: [
  4.     {
  5.       from: path.join(path.dirname(require.resolve('pdfjs-dist/package.json')), 'cmaps'),
  6.       to: 'cmaps/'
  7.     },
  8.   ],
  9. }),
  10. ```

Parcel, Browserify and others

If you use Parcel, Browserify or other bundling tools, 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:

  1. ``` js
  2. import path from 'path';
  3. import fs from 'fs';

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

  5. function copyDir(from, to) {
  6.   // Ensure target directory exists
  7.   fs.mkdirSync(to, { recursive: true });

  8.   const files = fs.readdirSync(from);
  9.   files.forEach((file) => {
  10.     fs.copyFileSync(path.join(from, file), path.join(to, file));
  11.   });
  12. }

  13. copyDir(cMapsDir, 'dist/cmaps/');
  14. ```

Setting up React-PDF


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

  1. ``` js
  2. <Document
  3.   options={{
  4.     cMapUrl: 'cmaps/',
  5.     cMapPacked: true,
  6.   }}
  7. />
  8. ```

Alternatively, you could use cMaps from external CDN:

  1. ``` js
  2. import { pdfjs } from 'react-pdf';

  3. <Document
  4.   options={{
  5.     cMapUrl: `https://unpkg.com/pdfjs-dist@${pdfjs.version}/cmaps/`,
  6.     cMapPacked: true,
  7.   }}
  8. />;
  9. ```

Support for standard fonts


If you want to support PDFs using standard fonts (deprecated in PDF 1.5, but still around), 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.

Webpack

Add copy-webpack-plugin to your project if you haven't already:

  1. ```
  2. npm install copy-webpack-plugin --save-dev
  3. ```

Now, in your Webpack config, import the plugin:

  1. ``` js
  2. import path from 'path';
  3. import CopyWebpackPlugin from 'copy-webpack-plugin';
  4. ```

and in plugins section of your config, add the following:

  1. ``` js
  2. new CopyWebpackPlugin({
  3.   patterns: [
  4.     {
  5.       from: path.join(path.dirname(require.resolve('pdfjs-dist/package.json')), 'standard_fonts'),
  6.       to: 'standard_fonts/'
  7.     },
  8.   ],
  9. }),
  10. ```

Parcel, Browserify and others

If you use Parcel, Browserify or other bundling tools, 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:

  1. ``` js
  2. import path from 'path';
  3. import fs from 'fs';

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

  8. function copyDir(from, to) {
  9.   // Ensure target directory exists
  10.   fs.mkdirSync(to, { recursive: true });

  11.   const files = fs.readdirSync(from);
  12.   files.forEach((file) => {
  13.     fs.copyFileSync(path.join(from, file), path.join(to, file));
  14.   });
  15. }

  16. copyDir(standardFontsDir, 'dist/standard_fonts/');
  17. ```

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:

  1. ``` js
  2. <Document
  3.   options={{
  4.     standardFontDataUrl: 'standard_fonts/',
  5.   }}
  6. />
  7. ```

Alternatively, you could use standard fonts from external CDN:

  1. ``` js
  2. import { pdfjs } from 'react-pdf';

  3. <Document
  4.   options={{
  5.     standardFontDataUrl: `https://unpkg.com/pdfjs-dist@${pdfjs.version}/standard_fonts`,
  6.   }}
  7. />;
  8. ```

User guide


Document


Loads a document passed using file prop.

Props


PropDescriptionDefaultExample
------------
classNameClassn/a
  • String:
errorWhat`"Failed
  • String:
externalLinkRelLink`"noopenerOne
externalLinkTargetLinkunset,One
fileWhatn/a
  • URL:
imageResourcesPathThen/a`"/public/images/"`
inputRefAn/a
  • Function:
loadingWhat`"Loading
  • String:
noDataWhat`"No
  • String:
onItemClickFunctionn/a`({
onLoadErrorFunctionn/a`(error)
onLoadProgressFunctionn/a`({
onLoadSuccessFunctionn/a`(pdf)
onPasswordFunctionFunction`(callback)
onSourceErrorFunctionn/a`(error)
onSourceSuccessFunctionn/a`()
optionsAnn/a`{
renderModeRendering`"canvas"``"svg"`
rotateRotationn/a`90`

Page


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

Props


PropDescriptionDefaultExample
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
canvasBackgroundCanvasn/a`"transparent"`
canvasRefAn/a
  • Function:
classNameClassn/a
  • String:
customTextRendererFunctionn/a``
devicePixelRatioThe`window.devicePixelRatio``1`
errorWhat`"Failed
  • String:
heightPagePage's`300`
imageResourcesPathThen/a`"/public/images/"`
inputRefAn/a
  • Function:
loadingWhat`"Loading
  • String:
noDataWhat`"No
  • String:
onLoadErrorFunctionn/a`(error)
onLoadSuccessFunctionn/a`(page)
onRenderErrorFunctionn/a`(error)
onRenderSuccessFunctionn/a`()
onRenderTextLayerErrorFunctionn/a`(error)
onRenderTextLayerSuccessFunctionn/a`()
onGetAnnotationsSuccessFunctionn/a`(annotations)
onGetAnnotationsErrorFunctionn/a`(error)
onGetTextSuccessFunctionn/a`({
onGetTextErrorFunctionn/a`(error)
pageIndexWhich`0``1`
pageNumberWhich`1``2`
renderAnnotationLayerWhether`true``false`
renderFormsWhether`false``true`
renderModeRendering`"canvas"``"svg"`
renderTextLayerWhether`true``false`
rotateRotationPage's`90`
scalePage`1.0``0.5`
widthPagePage's`300`

Outline


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

Props


PropDescriptionDefaultExample
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
classNameClassn/a
  • String:
inputRefAn/a
  • Function:
onItemClickFunctionn/a`({
onLoadErrorFunctionn/a`(error)
onLoadSuccessFunctionn/a`(outline)

Useful links



License


The MIT License.

Author


Wojciech Maj
kontakt@wojtekmaj.pl
https://wojtekmaj.pl

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](http://mozilla.github.io/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