npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2020 – Pkg Stats / Ryan Hefner

react-pdf

v5.0.0

Published

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

Downloads

872,826

Readme

npm downloads build dependencies dev dependencies tested with jest

React-PDF

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

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.

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 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:

Getting started

Compatibility

React

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 versionNewest compatible React-PDF version
≥16.35.x
≥15.53.x
≥0.130.0.10
≥0.110.0.4

Internet Explorer

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!

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:

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.

Enable PDF.js worker

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.

Webpack

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';

Parcel

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

Create React App uses Webpack under the hood, but instructions for Webpack will not work. Standard instructions apply.

Standard (Browserify and others)

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

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

import { pdfjs } from 'react-pdf';
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.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:

// using ES6 modules
import 'react-pdf/dist/esm/Page/AnnotationLayer.css';

// using CommonJS modules
import 'react-pdf/dist/umd/Page/AnnotationLayer.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:

import CopyWebpackPlugin from 'copy-webpack-plugin';

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

new CopyWebpackPlugin([
  {
    from: 'node_modules/pdfjs-dist/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.

Setting up React-PDF

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

<Document
  options={{
    cMapUrl: 'cmaps/',
    cMapPacked: true,
  }}
/>

Alternatively, you could use cMaps from external CDN:

import { pdfjs } from 'react-pdf';

<Document
  options={{
    cMapUrl: `//cdn.jsdelivr.net/npm/[email protected]${pdfjs.version}/cmaps/`,
    cMapPacked: true,
  }}
/>

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/aString:"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:<div>An error occurred!</div>Function:this.renderError
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; 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).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/aURL:"http://example.com/sample.pdf"File:import sample from '../static/sample.pdf' and thensampleParameter object:{ url: 'http://example.com/sample.pdf', httpHeaders: { 'X-CustomHeader': '40359820958024350238508234' }, withCredentials: true }
inputRefA function that behaves like ref, but it's passed to main <div> rendered by <Document> component.n/a(ref) => { this.myDocument = ref; }
loadingWhat the component should display while loading."Loading PDF…"String:"Please wait!"React element:<div>Please wait!</div>Function:this.renderLoader
noDataWhat the component should display in case of no data."No PDF file specified."String:"Please select a file."React element:<div>Please select a file.</div>Function:this.renderNoData
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({ 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)
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.A 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. For a full list of possible parameters, check PDF.js documentation on DocumentInitParameters.n/a{ cMapUrl: 'cmaps/', cMapPacked: true }
renderModeRendering mode of the document. Can be "canvas", "svg" or "none"."canvas""svg"
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

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 linking between pages inside a document may not be working correctly.

Props

Prop nameDescriptionDefault valueExample values
classNameClass name(s) that will be added to rendered element along with the default react-pdf__Page.n/aString:"custom-class-name-1 custom-class-name-2"Array of strings:["custom-class-name-1", "custom-class-name-2"]
customTextRendererA function that customizes how a text layer is rendered. Passes itext item and index for item.n/a({ str, itemIndex }) => { return (<mark>{str}</mark>) }
errorWhat the component should display in case of an error."Failed to load the page."String:"An error occurred!"React element:<div>An error occurred!</div>Function:this.renderError
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
inputRefA function that behaves like ref, but it's passed to main <div> rendered by <Page> component.n/a(ref) => { this.myPage = ref; }
loadingWhat the component should display while loading."Loading page…"String:"Please wait!"React element:<div>Please wait!</div>Function:this.renderLoader
noDataWhat the component should display in case of no data."No page specified."String:"Please select a page."React element:<div>Please select a page.</div>Function:this.renderNoData
onLoadErrorFunction called in case of an error while loading the page.n/a(error) => alert('Error while loading page! ' + 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 page is successfully loaded.n/a(page) => alert('Now displaying a page number ' + page.pageNumber + '!')
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!')
onGetAnnotationsSuccessFunction called when annotations are successfully loaded.n/a(annotations) => alert('Now displaying ' + annotations.length + ' annotations!')
onGetAnnotationsErrorFunction called in case of an error while loading annotations.n/a(error) => alert('Error while loading annotations! ' + error.message)
onGetTextSuccessFunction called when text layer items are successfully loaded.n/a(items) => alert('Now displaying ' + items.length + ' text layer items!')
onGetTextErrorFunction called in case of an error while loading text layer items.n/a(error) => alert('Error while loading text layer items! ' + error.message)
pageIndexWhich page from PDF file should be displayed, by page index.01
pageNumberWhich page from PDF file should be displayed, by page number. If provided, pageIndex prop will be ignored.12
renderAnnotationLayerWhether annotations (e.g. links) should be rendered.truefalse
renderInteractiveFormsWhether interactive forms should be rendered. renderAnnotationLayer prop must be set to true.falsetrue
renderModeRendering mode of the document. Can be "canvas", "svg" or "none"."canvas""svg"
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.1.00.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/aString:"custom-class-name-1 custom-class-name-2"Array of strings:["custom-class-name-1", "custom-class-name-2"]
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({ 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.')

Useful links

License

The MIT License.

Author

Thank 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!

Top Contributors