wojtekmaj/react-pdf
Display PDFs in your React app as easily as if they were images.
README
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 `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:
- v5.x
- v4.x
- v3.x
- v2.x
- v1.x
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.
React | Newest |
---|---|
------------- | ----------------------------------- |
≥16.8 | latest |
≥16.3 | 5.x |
≥15.5 | 4.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:
- ``` js
- 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 (
- <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.
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:
- ``` js
- import { Document, Page } from 'react-pdf';
- ```
write:
- ``` js
- import { Document, Page } from 'react-pdf/dist/esm/entry.webpack5';
- ```
Bundler | Entry |
---|---|
--------- | ----------------------------------- |
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:
- ``` js
- import path from 'path';
- import fs from 'fs';
- const pdfjsDistPath = path.dirname(require.resolve('pdfjs-dist/package.json'));
- const pdfWorkerPath = path.join(pdfjsDistPath, 'build', 'pdf.worker.js');
- fs.copyFileSync(pdfWorkerPath, './dist/pdf.worker.js');
- ```
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:
- ``` js
- import { pdfjs } from 'react-pdf';
- pdfjs.GlobalWorkerOptions.workerSrc = 'pdf.worker.min.js';
- ```
Alternatively, you could use the minified pdf.worker.min.js from an external CDN:
- ``` js
- import { pdfjs } from 'react-pdf';
- pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.js`;
- ```
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:
- ``` js
- import 'react-pdf/dist/esm/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:
- ``` js
- import 'react-pdf/dist/esm/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.
Webpack
Add copy-webpack-plugin to your project if you haven't already:
- ```
- npm install copy-webpack-plugin --save-dev
- ```
Now, in your Webpack config, import the plugin:
- ``` js
- import path from 'path';
- import CopyWebpackPlugin from 'copy-webpack-plugin';
- ```
and in plugins section of your config, add the following:
- ``` js
- new CopyWebpackPlugin({
- patterns: [
- {
- from: path.join(path.dirname(require.resolve('pdfjs-dist/package.json')), 'cmaps'),
- to: 'cmaps/'
- },
- ],
- }),
- ```
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:
- ``` js
- import path from 'path';
- import fs from 'fs';
- const cMapsDir = path.join(path.dirname(require.resolve('pdfjs-dist/package.json')), 'cmaps');
- function copyDir(from, to) {
- // Ensure target directory exists
- fs.mkdirSync(to, { recursive: true });
- const files = fs.readdirSync(from);
- files.forEach((file) => {
- fs.copyFileSync(path.join(from, file), path.join(to, file));
- });
- }
- copyDir(cMapsDir, 'dist/cmaps/');
- ```
Setting up React-PDF
Now that you have cMaps in your build, pass required options to Document component by using options prop, like so:
- ``` js
- <Document
- options={{
- cMapUrl: 'cmaps/',
- cMapPacked: true,
- }}
- />
- ```
Alternatively, you could use cMaps from external CDN:
- ``` js
- import { pdfjs } from 'react-pdf';
- <Document
- options={{
- cMapUrl: `https://unpkg.com/pdfjs-dist@${pdfjs.version}/cmaps/`,
- cMapPacked: true,
- }}
- />;
- ```
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:
- ```
- npm install copy-webpack-plugin --save-dev
- ```
Now, in your Webpack config, import the plugin:
- ``` js
- import path from 'path';
- import CopyWebpackPlugin from 'copy-webpack-plugin';
- ```
and in plugins section of your config, add the following:
- ``` js
- new CopyWebpackPlugin({
- patterns: [
- {
- from: path.join(path.dirname(require.resolve('pdfjs-dist/package.json')), 'standard_fonts'),
- to: 'standard_fonts/'
- },
- ],
- }),
- ```
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:
- ``` js
- import path from 'path';
- import fs from 'fs';
- const standardFontsDir = path.join(
- path.dirname(require.resolve('pdfjs-dist/package.json')),
- 'standard_fonts',
- );
- function copyDir(from, to) {
- // Ensure target directory exists
- fs.mkdirSync(to, { recursive: true });
- const files = fs.readdirSync(from);
- files.forEach((file) => {
- fs.copyFileSync(path.join(from, file), path.join(to, file));
- });
- }
- copyDir(standardFontsDir, 'dist/standard_fonts/');
- ```
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:
- ``` js
- <Document
- options={{
- standardFontDataUrl: 'standard_fonts/',
- }}
- />
- ```
Alternatively, you could use standard fonts from external CDN:
- ``` js
- import { pdfjs } from 'react-pdf';
- <Document
- options={{
- standardFontDataUrl: `https://unpkg.com/pdfjs-dist@${pdfjs.version}/standard_fonts`,
- }}
- />;
- ```
User guide
Document
Loads a document passed using file prop.
Props
Prop | Description | Default | Example |
---|---|---|---|
--- | --- | --- | --- |
className | Class | n/a |
|
error | What | `"Failed |
|
externalLinkRel | Link | `"noopener | One |
externalLinkTarget | Link | unset, | One |
file | What | n/a |
|
imageResourcesPath | The | n/a | `"/public/images/"` |
inputRef | A | n/a |
|
loading | What | `"Loading |
|
noData | What | `"No |
|
onItemClick | Function | n/a | `({ |
onLoadError | Function | n/a | `(error) |
onLoadProgress | Function | n/a | `({ |
onLoadSuccess | Function | n/a | `(pdf) |
onPassword | Function | Function | `(callback) |
onSourceError | Function | n/a | `(error) |
onSourceSuccess | Function | n/a | `() |
options | An | n/a | `{ |
renderMode | Rendering | `"canvas"` | `"svg"` |
rotate | Rotation | n/a | `90` |
Page
Props
Prop | Description | Default | Example |
---|---|---|---|
------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
canvasBackground | Canvas | n/a | `"transparent"` |
canvasRef | A | n/a |
|
className | Class | n/a |
|
customTextRenderer | Function | n/a | `` |
devicePixelRatio | The | `window.devicePixelRatio` | `1` |
error | What | `"Failed |
|
height | Page | Page's | `300` |
imageResourcesPath | The | n/a | `"/public/images/"` |
inputRef | A | n/a |
|
loading | What | `"Loading |
|
noData | What | `"No |
|
onLoadError | Function | n/a | `(error) |
onLoadSuccess | Function | n/a | `(page) |
onRenderError | Function | n/a | `(error) |
onRenderSuccess | Function | n/a | `() |
onRenderTextLayerError | Function | n/a | `(error) |
onRenderTextLayerSuccess | Function | n/a | `() |
onGetAnnotationsSuccess | Function | n/a | `(annotations) |
onGetAnnotationsError | Function | n/a | `(error) |
onGetTextSuccess | Function | n/a | `({ |
onGetTextError | Function | n/a | `(error) |
pageIndex | Which | `0` | `1` |
pageNumber | Which | `1` | `2` |
renderAnnotationLayer | Whether | `true` | `false` |
renderForms | Whether | `false` | `true` |
renderMode | Rendering | `"canvas"` | `"svg"` |
renderTextLayer | Whether | `true` | `false` |
rotate | Rotation | Page's | `90` |
scale | Page | `1.0` | `0.5` |
width | Page | Page's | `300` |
Outline
Props
Prop | Description | Default | Example |
---|---|---|---|
------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
className | Class | n/a |
|
inputRef | A | n/a |
|
onItemClick | Function | n/a | `({ |
onLoadError | Function | n/a | `(error) |
onLoadSuccess | Function | n/a | `(outline) |
Useful links
License
The MIT License.
Author
Wojciech Maj kontakt@wojtekmaj.pl https://wojtekmaj.pl |
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!