Display PDFs in your React app as easily as if they were images.
Display PDFs in your React app as easily as if they were images.
This package is used to display existing PDFs. If you wish to create PDFs using React, you may be looking for @react-pdf/renderer.
npm install react-pdfor
yarn add react-pdf.
import { Document } from 'react-pdf'.
filecan be a URL, base64 content, Uint8Array, and more.
A minimal demo page can be found in
sampledirectory.
Online demo is also available!
React-PDF is under constant development. This documentation is written for React-PDF 5.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:
To use the latest version of React-PDF, your project needs to use React 16.3 or later.
If you use an older version of React, please refer to the table below to a find suitable React-PDF version. Don't worry - as long as you're running React 15.5 or later, you won't be missing out a lot!
| React version | Newest compatible React-PDF version | |-------|--------| | ≥16.3 | latest | | ≥15.5 | 4.x |
Internet Explorer is not supported in React-PDF 5.x or later. If you need Internet Explorer support, you will need to use React-PDF 4.x instead. Don't worry - it still receives bug fixes and even occasional small features!
Add React-PDF to your project by executing
npm install react-pdfor
yarn add react-pdf.
Here's an example of basic usage:
import React, { useState } from 'react'; import { Document, Page } from 'react-pdf';function MyApp() { const [numPages, setNumPages] = useState(null); const [pageNumber, setPageNumber] = useState(1);
function onDocumentLoadSuccess({ numPages }) { setNumPages(numPages); }
return (
); }Page {pageNumber} of {numPages}
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.
It is crucial for performance to use PDF.js worker whenever possible. This ensures that PDF files will be rendered in a separate thread without affecting page performance. To make things a little easier, we've prepared several entry points you can use.
Instead of directly importing/requiring
'react-pdf', import it like so:
// using ES6 modules import { Document } from 'react-pdf/dist/esm/entry.webpack';// using CommonJS modules import { Document } from 'react-pdf/dist/umd/entry.webpack';
Instead of directly importing/requiring
'react-pdf', import it like so:
// using ES6 modules import { Document } from 'react-pdf/dist/esm/entry.parcel';// using CommonJS modules import { Document } from 'react-pdf/dist/umd/entry.parcel';
Create React App uses Webpack under the hood, so you can follow Webpack instructions.
Standard instructions will also work. In Create React App, you can copy
pdf.worker.jsfile from
pdfjs-dist/buildto
publicdirectory in order for it to be copied to your project's output folder at build time.
If you use Browserify or other bundling tools, you will have to make sure on your own that
pdf.worker.jsfile from
pdfjs-dist/buildis copied to your project's output folder.
If you don't need to debug
pdf.worker.js, you can use
pdf.worker.min.jsfile instead, which is roughly half the size. For this to work, however, you will need to specify
workerSrcmanually like so:
import { pdfjs } from 'react-pdf'; pdfjs.GlobalWorkerOptions.workerSrc = 'pdf.worker.min.js';
Alternatively, you could use the minified
pdf.worker.min.jsfrom an external CDN:
import { pdfjs } from 'react-pdf'; pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.min.js`;
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:
// using ES6 modules import 'react-pdf/dist/esm/Page/AnnotationLayer.css';// using CommonJS modules import 'react-pdf/dist/umd/Page/AnnotationLayer.css';
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.
First, you need to copy cMaps from
pdfjs-dist(React-PDF's dependency - it should be in your
node_modulesif you have React-PDF installed). cMaps are located in
pdfjs-dist/cmaps.
Add
copy-webpack-pluginto your project if you haven't already:
npm install copy-webpack-plugin --save-dev
Now, in your Webpack config, import the plugin:
import CopyWebpackPlugin from 'copy-webpack-plugin';
and in
pluginssection of your config, add the following:
new CopyWebpackPlugin([ { from: 'node_modules/pdfjs-dist/cmaps/', to: 'cmaps/' }, ]),
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.
Now that you have cMaps in your build, pass required options to Document component by using
optionsprop, like so:
Alternatively, you could use cMaps from external CDN:
import { pdfjs } from 'react-pdf';
Loads a document passed using
fileprop.
|Prop name|Description|Default value|Example values| |----|----|----|----| |className|Class name(s) that will be added to rendered element along with the default
react-pdf__Document.|n/a|
"custom-class-name-1 custom-class-name-2"
["custom-class-name-1", "custom-class-name-2"]
"Failed to load PDF file."|
"An error occurred!"
An error occurred!
this.renderError
targetattribute.
"_self"
"_blank"
"_parent"
"_top"
import ... from ...or from file input form element), or an object with parameters (
url- URL;
data- data, preferably Uint8Array;
range- PDFDataRangeTransport;
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).
===) is used to determine if
fileobject has changed, it must be memoized by setting it in component's state,
useMemoor other similar technique.|n/a|
"http://example.com/sample.pdf"
import sample from '../static/sample.pdf'and then
sample
{ url: 'http://example.com/sample.pdf', httpHeaders: { 'X-CustomHeader': '40359820958024350238508234' }, withCredentials: true }
"/public/images/"| |inputRef|A prop that behaves like ref, but it's passed to main
rendered by component.|n/a|| |loading|What the component should display while loading.|
- Function:
(ref) => { this.myDocument = ref; }- Ref created using
React.createRef:this.ref = React.createRef();
…inputRef={this.ref}- Ref created using
React.useRef:const ref = React.useRef();
…inputRef={ref}"Loading PDF…"|| |noData|What the component should display in case of no data.|
- String:
"Please wait!"- React element:
Please wait!- Function:
this.renderLoader"No PDF file specified."|| |onItemClick|Function 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|
- String:
"Please select a file."- React element:
Please select a file.- Function:
this.renderNoData({ pageNumber }) => alert('Clicked an item from page ' + pageNumber + '!')| |onLoadError|Function called in case of an error while loading a document.|n/a|(error) => alert('Error while loading document! ' + error.message)| |onLoadSuccess|Function called when the document is successfully loaded.|n/a|(pdf) => alert('Loaded a file with ' + pdf.numPages + ' pages!')| |onPassword|Function called when a password-protected PDF is loaded.|A function that prompts the user for password|(callback) => callback('s3cr3t_p4ssw0rd')| |onSourceError|Function called in case of an error while retrieving document source fromfileprop.|n/a|(error) => alert('Error while retrieving document source! ' + error.message)| |onSourceSuccess|Function called when document source is successfully retrieved fromfileprop.|n/a|() => alert('Document source retrieved!')| |options|An object in which additional parameters to be passed to PDF.js can be defined. For a full list of possible parameters, check PDF.js documentation on DocumentInitParameters.|n/a|{ cMapUrl: 'cmaps/', cMapPacked: true }| |renderMode|Rendering mode of the document. Can be"canvas","svg"or"none".|"canvas"|"svg"| |rotate|Rotation of the document in degrees. If provided, will change rotation globally, even for the pages which were givenrotateprop of their own.90= rotated to the right,180= upside down,270= rotated to the left.|n/a|90|Page
Displays a page. Should be placed inside
. Alternatively, it can haveonLoadSuccesscallback function, however some advanced functions like linking between pages inside a document may not be working correctly.Props
|Prop name|Description|Default value|Example values| |----|----|----|----| |canvasRef|A prop that behaves like ref, but it's passed to
rendered by component. If you setrenderModeto"svg"this prop will be ignored.|n/a|| |className|Class name(s) that will be added to rendered element along with the default
- Function:
(ref) => { this.myPage = ref; }- Ref created using
React.createRef:this.ref = React.createRef();
…inputRef={this.ref}- Ref created using
React.useRef:const ref = React.useRef();
…inputRef={ref}react-pdf__Page.|n/a|| |customTextRenderer|A function that customizes how a text layer is rendered. Passes itext item and index for item.|n/a|
- String:
"custom-class-name-1 custom-class-name-2"- Array of strings:
["custom-class-name-1", "custom-class-name-2"]({ str, itemIndex }) => { return ({str}) }| |error|What the component should display in case of an error.|"Failed to load the page."|| |height|Page height. If neither
- String:
"An error occurred!"- React element:
An error occurred!- Function:
this.renderErrorheightnorwidthare defined, page will be rendered at the size defined in PDF. If you definewidthandheightat the same time,heightwill be ignored. If you defineheightandscaleat the same time, the height will be multiplied by a given factor.|Page's default height|300| |imageResourcesPath|The path used to prefix the src attributes of annotation SVGs.|n/a (pdf.js will fallback to an empty string)|"/public/images/"| |inputRef|A prop that behaves like ref, but it's passed to mainrendered by component.|n/a|| |loading|What the component should display while loading.|
- Function:
(ref) => { this.myPage = ref; }- Ref created using
React.createRef:this.ref = React.createRef();
…inputRef={this.ref}- Ref created using
React.useRef:const ref = React.useRef();
…inputRef={ref}"Loading page…"|| |noData|What the component should display in case of no data.|
- String:
"Please wait!"- React element:
Please wait!- Function:
this.renderLoader"No page specified."|| |onLoadError|Function called in case of an error while loading the page.|n/a|
- String:
"Please select a page."- React element:
Please select a page.- Function:
this.renderNoData(error) => alert('Error while loading page! ' + error.message)| |onLoadProgress|Function called, potentially multiple times, as the loading progresses.|n/a|({ loaded, total }) => alert('Loading a document: ' + (loaded / total) * 100 + '%');| |onLoadSuccess|Function called when the page is successfully loaded.|n/a|(page) => alert('Now displaying a page number ' + page.pageNumber + '!')| |onRenderError|Function called in case of an error while rendering the page.|n/a|(error) => alert('Error while loading page! ' + error.message)| |onRenderSuccess|Function called when the page is successfully rendered on the screen.|n/a|() => alert('Rendered the page!')| |onGetAnnotationsSuccess|Function called when annotations are successfully loaded.|n/a|(annotations) => alert('Now displaying ' + annotations.length + ' annotations!')| |onGetAnnotationsError|Function called in case of an error while loading annotations.|n/a|(error) => alert('Error while loading annotations! ' + error.message)| |onGetTextSuccess|Function called when text layer items are successfully loaded.|n/a|(items) => alert('Now displaying ' + items.length + ' text layer items!')| |onGetTextError|Function called in case of an error while loading text layer items.|n/a|(error) => alert('Error while loading text layer items! ' + error.message)| |pageIndex|Which page from PDF file should be displayed, by page index.|0|1| |pageNumber|Which page from PDF file should be displayed, by page number. If provided,pageIndexprop will be ignored.|1|2| |renderAnnotationLayer|Whether annotations (e.g. links) should be rendered.|true|false| |renderInteractiveForms|Whether interactive forms should be rendered.renderAnnotationLayerprop must be set totrue.|false|true| |renderMode|Rendering mode of the document. Can be"canvas","svg"or"none".|"canvas"|"svg"| |renderTextLayer|Whether a text layer should be rendered.|true|false| |rotate|Rotation of the page in degrees.90= rotated to the right,180= upside down,270= rotated to the left.|Page's default setting, usually0|90| |scale|Page scale.|1.0|0.5| |width|Page width. If neitherheightnorwidthare defined, page will be rendered at the size defined in PDF. If you definewidthandheightat the same time,heightwill be ignored. If you definewidthandscaleat the same time, the width will be multiplied by a given factor.|Page's default width|300|Outline
Displays an outline (table of contents). Should be placed inside
. Alternatively, it can haveonLoadSuccesscallback function.Props
|Prop name|Description|Default value|Example values| |----|----|----|----| |className|Class name(s) that will be added to rendered element along with the default
react-pdf__Outline.|n/a|| |inputRef|A prop that behaves like ref, but it's passed to main
- String:
"custom-class-name-1 custom-class-name-2"- Array of strings:
["custom-class-name-1", "custom-class-name-2"]rendered by component.|n/a|| |onItemClick|Function 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|
- Function:
(ref) => { this.myOutline = ref; }- Ref created using
React.createRef:this.ref = React.createRef();
…inputRef={this.ref}- Ref created using
React.useRef:const ref = React.useRef();
…inputRef={ref}({ pageNumber }) => alert('Clicked an item from page ' + pageNumber + '!')| |onLoadError|Function called in case of an error while retrieving the outline.|n/a|(error) => alert('Error while retrieving the outline! ' + error.message)| |onLoadSuccess|Function called when the outline is successfully retrieved.|n/a|(outline) => alert('The outline has been successfully retrieved.')|Useful links
License
The MIT License.
Author
![]()
Wojciech Maj
[email protected]
https://wojtekmaj.plThank you
This project wouldn't be possible without awesome work of Niklas Närhinen [email protected] who created its initial 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!