You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

пре 3 година
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. [![npm](https://img.shields.io/npm/v/react-pdf.svg)](https://www.npmjs.com/package/react-pdf) ![downloads](https://img.shields.io/npm/dt/react-pdf.svg) ![build](https://travis-ci.com/wojtekmaj/react-pdf.svg?branch=master) ![dependencies](https://img.shields.io/david/wojtekmaj/react-pdf.svg) ![dev dependencies](https://img.shields.io/david/dev/wojtekmaj/react-pdf.svg) [![tested with jest](https://img.shields.io/badge/tested_with-jest-99424f.svg)](https://github.com/facebook/jest)
  2. # React-PDF
  3. Display PDFs in your React app as easily as if they were images.
  4. ## tl;dr
  5. * Install by executing `npm install react-pdf` or `yarn add react-pdf`.
  6. * Import by adding `import { Document } from 'react-pdf'`.
  7. * Use by adding `<Document file="..." />`. `file` can be a URL, base64 content, Uint8Array, and more.
  8. * Put `<Page />` components inside `<Document />` to render pages.
  9. ## Demo
  10. A minimal demo page can be found in `sample` directory.
  11. [Online demo](http://projects.wojtekmaj.pl/react-pdf/) is also available!
  12. ## Before you continue
  13. React-PDF is under constant development. This documentation is written for React-PDF 4.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:
  14. * [v3.x](https://github.com/wojtekmaj/react-pdf/blob/v3.x/README.md)
  15. * [v2.x](https://github.com/wojtekmaj/react-pdf/blob/v2.x/README.md)
  16. * [v1.x](https://github.com/wojtekmaj/react-pdf/blob/v1.8.3/README.md)
  17. ## Getting started
  18. ### Compatibility
  19. To use the latest version of React-PDF, your project needs to use React 16.3 or later.
  20. 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!
  21. | React version | Newest compatible React-PDF version |
  22. |-------|--------|
  23. | ≥16.3 | 4.x |
  24. | ≥15.5 | 3.x |
  25. | ≥0.13 | 0.0.10 |
  26. | ≥0.11 | 0.0.4 |
  27. ### Installation
  28. Add React-PDF to your project by executing `npm install react-pdf` or `yarn add react-pdf`.
  29. ### Usage
  30. Here's an example of basic usage:
  31. ```js
  32. import React, { useState } from 'react';
  33. import { Document, Page } from 'react-pdf';
  34. function MyApp() {
  35. const [numPages, setNumPages] = useState(null);
  36. const [pageNumber, setPageNumber] = useState(1);
  37. function onDocumentLoadSuccess({ numPages }) {
  38. setNumPages(numPages);
  39. }
  40. return (
  41. <div>
  42. <Document
  43. file="somefile.pdf"
  44. onLoadSuccess={onDocumentLoadSuccess}
  45. >
  46. <Page pageNumber={pageNumber} />
  47. </Document>
  48. <p>Page {pageNumber} of {numPages}</p>
  49. </div>
  50. );
  51. }
  52. ```
  53. Check the [sample directory](https://github.com/wojtekmaj/react-pdf/tree/master/sample) in this repository for a full working example. For more examples and more advanced use cases, check [Recipes](https://github.com/wojtekmaj/react-pdf/wiki/Recipes) in React-PDF Wiki.
  54. ### Enable PDF.js worker
  55. 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.
  56. #### Webpack
  57. Instead of directly importing/requiring `'react-pdf'`, import it like so:
  58. ```js
  59. import { Document } from 'react-pdf/dist/entry.webpack';
  60. ```
  61. #### Parcel
  62. Instead of directly importing/requiring `'react-pdf'`, import it like so:
  63. ```js
  64. import { Document } from 'react-pdf/dist/entry.parcel';
  65. ```
  66. #### Create React App
  67. Create React App uses Webpack under the hood, but instructions for Webpack will not work. [Standard instructions](#standard-browserify-and-others) apply.
  68. #### Standard (Browserify and others)
  69. 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.
  70. Alternatively, you could use `pdf.worker.js` from an external CDN:
  71. ```js
  72. import { pdfjs } from 'react-pdf';
  73. pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;
  74. ```
  75. ### Support for annotations
  76. 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:
  77. ```js
  78. import 'react-pdf/dist/Page/AnnotationLayer.css';
  79. ```
  80. ### Support for non-latin characters
  81. If you want to ensure that PDFs with non-latin characters will render perfectly, or you have encountered the following warning:
  82. ```
  83. Warning: The CMap "baseUrl" parameter must be specified, ensure that the "cMapUrl" and "cMapPacked" API parameters are provided.
  84. ```
  85. then you would also need to include cMaps in your build and tell React-PDF where they are.
  86. #### Copying cMaps
  87. 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`.
  88. ##### Webpack
  89. Add `copy-webpack-plugin` to your project if you haven't already:
  90. ```
  91. npm install copy-webpack-plugin --save-dev
  92. ```
  93. Now, in your Webpack config, import the plugin:
  94. ```js
  95. import CopyWebpackPlugin from 'copy-webpack-plugin';
  96. ```
  97. and in `plugins` section of your config, add the following:
  98. ```js
  99. new CopyWebpackPlugin([
  100. {
  101. from: 'node_modules/pdfjs-dist/cmaps/',
  102. to: 'cmaps/'
  103. },
  104. ]),
  105. ```
  106. ##### Parcel, Browserify and others
  107. 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.
  108. #### Setting up React-PDF
  109. Now that you have cMaps in your build, pass required options to Document component by using `options` prop, like so:
  110. ```js
  111. <Document
  112. options={{
  113. cMapUrl: 'cmaps/',
  114. cMapPacked: true,
  115. }}
  116. />
  117. ```
  118. Alternatively, you could use cMaps from external CDN:
  119. ```js
  120. import { pdfjs } from 'react-pdf';
  121. <Document
  122. options={{
  123. cMapUrl: `//cdn.jsdelivr.net/npm/pdfjs-dist@${pdfjs.version}/cmaps/`,
  124. cMapPacked: true,
  125. }}
  126. />
  127. ```
  128. ## User guide
  129. ### Document
  130. Loads a document passed using `file` prop.
  131. #### Props
  132. |Prop name|Description|Default value|Example values|
  133. |----|----|----|----|
  134. |className|Class name(s) that will be added to rendered element along with the default `react-pdf__Document`.|n/a|<ul><li>String:<br />`"custom-class-name-1 custom-class-name-2"`</li><li>Array of strings:<br />`["custom-class-name-1", "custom-class-name-2"]`</li></ul>|
  135. |error|What the component should display in case of an error.|`"Failed to load PDF file."`|<ul><li>String:<br />`"An error occurred!"`</li><li>React element:<br />`<div>An error occurred!</div>`</li><li>Function:<br />`this.renderError`</li></ul>|
  136. |externalLinkTarget|Link target for external links rendered in annotations.|unset, which means that default behavior will be used|One of valid [values for `target` attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#Attributes).<ul><li>`"_self"`</li><li>`"_blank"`</li><li>`"_parent"`</li><li>`"_top"`</li></ul>
  137. |file|What PDF should be displayed.<br />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`).<br />**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|<ul><li>URL:<br />`"http://example.com/sample.pdf"`</li><li>File:<br />`import sample from '../static/sample.pdf'` and then<br />`sample`</li><li>Parameter object:<br />`{ url: 'http://example.com/sample.pdf', httpHeaders: { 'X-CustomHeader': '40359820958024350238508234' }, withCredentials: true }`</ul>|
  138. |inputRef|A function that behaves like ref, but it's passed to main `<div>` rendered by `<Document>` component.|n/a|`(ref) => { this.myDocument = ref; }`|
  139. |loading|What the component should display while loading.|`"Loading PDF…"`|<ul><li>String:<br />`"Please wait!"`</li><li>React element:<br />`<div>Please wait!</div>`</li><li>Function:<br />`this.renderLoader`</li></ul>|
  140. |noData|What the component should display in case of no data.|`"No PDF file specified."`|<ul><li>String:<br />`"Please select a file."`</li><li>React element:<br />`<div>Please select a file.</div>`</li><li>Function:<br />`this.renderNoData`</li></ul>|
  141. |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|`({ pageNumber }) => alert('Clicked an item from page ' + pageNumber + '!')`|
  142. |onLoadError|Function called in case of an error while loading a document.|n/a|`(error) => alert('Error while loading document! ' + error.message)`|
  143. |onLoadSuccess|Function called when the document is successfully loaded.|n/a|`(pdf) => alert('Loaded a file with ' + pdf.numPages + ' pages!')`|
  144. |onPassword|Function called when a password-protected PDF is loaded.|A function that prompts the user for password|`(callback) => callback('s3cr3t_p4ssw0rd')`|
  145. |onSourceError|Function called in case of an error while retrieving document source from `file` prop.|n/a|`(error) => alert('Error while retrieving document source! ' + error.message)`|
  146. |onSourceSuccess|Function called when document source is successfully retrieved from `file` prop.|n/a|`() => alert('Document source retrieved!')`|
  147. |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](https://mozilla.github.io/pdf.js/api/draft/module-pdfjsLib.html#~DocumentInitParameters).|n/a|`{ cMapUrl: 'cmaps/', cMapPacked: true }`|
  148. |renderMode|Rendering mode of the document. Can be `"canvas"`, `"svg"` or `"none"`.|`"canvas"`|`"svg"`|
  149. |rotate|Rotation 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/a|`90`|
  150. ### Page
  151. 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.
  152. #### Props
  153. |Prop name|Description|Default value|Example values|
  154. |----|----|----|----|
  155. |className|Class name(s) that will be added to rendered element along with the default `react-pdf__Page`.|n/a|<ul><li>String:<br />`"custom-class-name-1 custom-class-name-2"`</li><li>Array of strings:<br />`["custom-class-name-1", "custom-class-name-2"]`</li></ul>|
  156. |customTextRenderer|A function that customizes how a text layer is rendered. Passes itext item and index for item.|n/a|`({ str, itemIndex }) => { return (<mark>{str}</mark>) }`|
  157. |error|What the component should display in case of an error.|`"Failed to load the page."`|<ul><li>String:<br />`"An error occurred!"`</li><li>React element:<br />`<div>An error occurred!</div>`</li><li>Function:<br />`this.renderError`</li></ul>|
  158. |height|Page 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 height|`300`|
  159. |inputRef|A function that behaves like ref, but it's passed to main `<div>` rendered by `<Page>` component.|n/a|`(ref) => { this.myPage = ref; }`|
  160. |loading|What the component should display while loading.|`"Loading page…"`|<ul><li>String:<br />`"Please wait!"`</li><li>React element:<br />`<div>Please wait!</div>`</li><li>Function:<br />`this.renderLoader`</li></ul>|
  161. |noData|What the component should display in case of no data.|`"No page specified."`|<ul><li>String:<br />`"Please select a page."`</li><li>React element:<br />`<div>Please select a page.</div>`</li><li>Function:<br />`this.renderNoData`</li></ul>|
  162. |onLoadError|Function called in case of an error while loading the page.|n/a|`(error) => alert('Error while loading page! ' + error.message)`|
  163. |onLoadProgress|Function called, potentially multiple times, as the loading progresses.|n/a|`({ loaded, total }) => alert('Loading a document: ' + (loaded / total) * 100 + '%');`|
  164. |onLoadSuccess|Function called when the page is successfully loaded.|n/a|`(page) => alert('Now displaying a page number ' + page.pageNumber + '!')`|
  165. |onRenderError|Function called in case of an error while rendering the page.|n/a|`(error) => alert('Error while loading page! ' + error.message)`|
  166. |onRenderSuccess|Function called when the page is successfully rendered on the screen.|n/a|`() => alert('Rendered the page!')`|
  167. |onGetAnnotationsSuccess|Function called when annotations are successfully loaded.|n/a|`(annotations) => alert('Now displaying ' + annotations.length + ' annotations!')`|
  168. |onGetAnnotationsError|Function called in case of an error while loading annotations.|n/a|`(error) => alert('Error while loading annotations! ' + error.message)`|
  169. |onGetTextSuccess|Function called when text layer items are successfully loaded.|n/a|`(items) => alert('Now displaying ' + items.length + ' text layer items!')`|
  170. |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)`|
  171. |pageIndex|Which page from PDF file should be displayed, by page index.|`0`|`1`|
  172. |pageNumber|Which page from PDF file should be displayed, by page number. If provided, `pageIndex` prop will be ignored.|`1`|`2`|
  173. |renderAnnotationLayer|Whether annotations (e.g. links) should be rendered.|`true`|`false`|
  174. |renderInteractiveForms|Whether interactive forms should be rendered. `renderAnnotationLayer` prop must be set to `true`.|`false`|`true`|
  175. |renderMode|Rendering mode of the document. Can be `"canvas"`, `"svg"` or `"none"`.|`"canvas"`|`"svg"`|
  176. |renderTextLayer|Whether a text layer should be rendered.|`true`|`false`|
  177. |rotate|Rotation of the page in degrees. `90` = rotated to the right, `180` = upside down, `270` = rotated to the left.|Page's default setting, usually `0`|`90`|
  178. |scale|Page scale.|`1.0`|`0.5`|
  179. |width|Page 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 width|`300`|
  180. ### Outline
  181. 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.
  182. #### Props
  183. |Prop name|Description|Default value|Example values|
  184. |----|----|----|----|
  185. |className|Class name(s) that will be added to rendered element along with the default `react-pdf__Outline`.|n/a|<ul><li>String:<br />`"custom-class-name-1 custom-class-name-2"`</li><li>Array of strings:<br />`["custom-class-name-1", "custom-class-name-2"]`</li></ul>|
  186. |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|`({ pageNumber }) => alert('Clicked an item from page ' + pageNumber + '!')`|
  187. |onLoadError|Function called in case of an error while retrieving the outline.|n/a|`(error) => alert('Error while retrieving the outline! ' + error.message)`|
  188. |onLoadSuccess|Function called when the outline is successfully retrieved.|n/a|`(outline) => alert('The outline has been successfully retrieved.')`|
  189. ## License
  190. The MIT License.
  191. ## Author
  192. <table>
  193. <tr>
  194. <td>
  195. <img src="https://github.com/wojtekmaj.png?s=100" width="100">
  196. </td>
  197. <td>
  198. Wojciech Maj<br />
  199. <a href="mailto:kontakt@wojtekmaj.pl">kontakt@wojtekmaj.pl</a><br />
  200. <a href="http://wojtekmaj.pl">http://wojtekmaj.pl</a>
  201. </td>
  202. </tr>
  203. </table>
  204. ## Thank you
  205. This project wouldn't be possible without awesome work of Niklas Närhinen <niklas@narhinen.net> who created its initial version and without Mozilla, author of [pdf.js](http://mozilla.github.io/pdf.js). Thank you!
  206. ### Sponsors
  207. Thank you to all our sponsors! [Become a sponsor](https://opencollective.com/react-pdf-wojtekmaj#sponsor) and get your image on our README on GitHub.
  208. <a href="https://opencollective.com/react-pdf-wojtekmaj#sponsors" target="_blank"><img src="https://opencollective.com/react-pdf-wojtekmaj/sponsors.svg?width=890"></a>
  209. ### Backers
  210. Thank you to all our backers! [Become a backer](https://opencollective.com/react-pdf-wojtekmaj#backer) and get your image on our README on GitHub.
  211. <a href="https://opencollective.com/react-pdf-wojtekmaj#backers" target="_blank"><img src="https://opencollective.com/react-pdf-wojtekmaj/backers.svg?width=890"></a>
  212. ### Top Contributors
  213. Thank you to all our contributors that helped on this project!
  214. ![Top Contributors](https://opencollective.com/react-pdf/contributors.svg?width=890&button=false)