@activelylearn/react-pdf 中文文档教程
![dependencies](https://img.shields.io/david/wojtekmaj/react-pdf.svg )![开发依赖](https://img.shields.io/david/dev/wojtekmaj/react-pdf.svg )
React-PDF
在您的 React 应用程序中轻松显示 PDF 文件。
tl;dr
- Install by executing
npm install react-pdf
oryarn add react-pdf
. - Import by addding
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
最小演示页面包含在示例目录中。
在线演示也可用!
Getting started
Compatibility
您的项目需要使用 React 15.5 或更高版本。 如果您使用旧版本的 React,请参考下表找到合适的 React-PDF 版本。
React version | Newest supported React-PDF |
---|---|
>15.5 | latest |
>15.0 | 1.6.1 |
>0.14 | 0.0.10 |
>0.13 | 0.0.10 |
>0.11 | 0.0.4 |
Installation
通过执行 npm install react-pdf
或 yarn add react-pdf
将 React-PDF 添加到您的项目中。
Usage
下面是一个基本用法的示例:
import React, { Component } from 'react';
import { Document, Page } from 'react-pdf';
class MyApp extends Component {
state = {
numPages: null,
pageNumber: 1,
}
onDocumentLoad = ({ numPages }) => {
this.setState({ numPages });
}
render() {
const { pageNumber, numPages } = this.state;
return (
<div>
<Document
file="somefile.pdf"
onLoadSuccess={this.onDocumentLoad}
>
<Page pageNumber={pageNumber} />
</Document>
<p>Page {pageNumber} of {numPages}</p>
</div>
);
}
}
检查此存储库的示例目录以获得完整的工作示例。
Enable PDF.js worker
尽可能使用 PDF.js worker 对性能至关重要。 这可确保您的 PDF 文件将在单独的线程中呈现,而不会影响页面性能。 为了让事情变得更简单,我们准备了几个您可以使用的入口点。
Webpack
如果您使用 Webpack,那么您很幸运。 不是直接导入/要求 'react-pdf'
,而是像这样导入它:
import { Document } from 'react-pdf/build/entry.webpack';
......你已经准备好了!
Browserify and others
如果您使用 Browserify 或其他捆绑工具,您必须自行确保将 pdfjs-dist/build
中的 pdf.worker.js
文件复制到您的项目的导出目录。
I give up
如果绝对必要,您可以在禁用 worker 的情况下导入 React PDF。 你可以通过像这样导入 React-PDF 来做到这一点:
import { Document } from 'react-pdf/build/entry.noworker';
Support for non-latin characters
如果你想确保具有非拉丁字符的 PDF 将完美呈现,或者你遇到了以下警告:
Warning: CMap baseUrl must be specified, see "PDFJS.cMapUrl" (and also "PDFJS.cMapPacked").
那么你还需要在你的构建中包含 cMaps 并告诉 React -PDF 他们在哪里。
Copying cMaps
首先,您需要从 pdfjs-dist
复制 cMaps(React-PDF 的依赖项 - 如果您安装了 React-PDF,它应该在您的 node_modules
中)。 cMap 位于 pdfjs-dist/cmaps
中。
Webpack
如果您还没有将 copy-webpack-plugin
添加到您的项目中:
npm install copy-webpack-plugin --save-dev
现在,在您的 Webpack 配置中,导入插件:
import CopyWebpackPlugin from 'copy-webpack-plugin';
并在配置的插件部分中,添加以下内容:
new CopyWebpackPlugin([
{
from: 'node_modules/pdfjs-dist/cmaps/',
to: 'cmaps/'
},
]),
Browserify and others
如果您使用 Browserify或其他捆绑工具,您必须自己确保将 cMap 复制到项目的输出文件夹中。
Setting up React-PDF
现在你的构建中有了 cMaps,像这样导入 setOptions
:
import { setOptions } from 'react-pdf';
注意: 如果你使用不同的入口点,例如 react-pdf/build /entry.webpack'
,你可以使用相同的入口点导入 setOptions
。 您还可以将 setOptions
添加到用于导入 Document
、Page
和/或其他组件。
setOptions({
cMapUrl: 'cmaps/',
cMapPacked: true,
});
User guide
Document
加载使用 file
属性传递的文档。
Props
Prop name | Description | Example values |
---|---|---|
className | Defines custom class name(s), that will be added to rendered element along with the default ReactPDF__Document . |
|
error | Defines what the component should display in case of an error. Defaults to "Failed to load PDF file.". |
|
file | Defines what 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 ). |
|
inputRef | A function that behaves like ref, but it's passed to main <div> rendered by <Document> component. | (ref) => { this.myDocument = ref; } |
loading | Defines what the component should display while loading. Defaults to "Loading PDF…". |
|
noData | Defines what the component should display in case of no data. Defaults to "No PDF file specified.". |
|
onItemClick | Function called when an item has been clicked. Usually, you would like to use this callback to move the user wherever they requested to. | ({ pageNumber }) => alert('Clicked an item from page ' + pageNumber + '!') |
onLoadError | Function called in case of an error while loading a document. | (error) => alert('Error while loading document! ' + error.message) |
onLoadSuccess | Function called when the document is successfully loaded. | (pdf) => alert('Loaded a file with ' + pdf.numPages + ' pages!') |
onSourceError | Function called in case of an error while retrieving document source from file prop. | (error) => alert('Error while retreiving document source! ' + error.message) |
onSourceSuccess | Function called when document source is successfully retreived from file prop. | () => alert('Document source retreived!') |
rotate | Defines the 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. | 90 |
Page
显示一个页面。 必须放在
中或者传递pdf
属性,可以从
中获取onLoadSuccess
回调函数。
注意
必须是
组件的直接子组件。
仅将必要的道具传递给它的直接子级。 如果你想在
和
之间放置一个组件,你必须确保将所有属性传递给
组件自行编写。
Props
Prop name | Description | Example values |
---|---|---|
className | Defines custom class name(s), that will be added to rendered element along with the default ReactPDF__Page . |
|
inputRef | A function that behaves like ref, but it's passed to main <div> rendered by <Page> component. | (ref) => { this.myPage = ref; } |
onLoadError | Function called in case of an error while loading the page. | (error) => alert('Error while loading page! ' + error.message) |
onLoadSuccess | Function called when the page is successfully loaded. | (page) => alert('Now displaying a page number ' + page.pageNumber + '!') |
onRenderError | Function called in case of an error while rendering the page. | (error) => alert('Error while loading page! ' + error.message) |
onRenderSuccess | Function called when the page is successfully rendered on the screen. | () => alert('Rendered the page!') |
pageIndex | Defines which page from PDF file should be displayed. Defaults to 0. | 0 |
pageNumber | Defines which page from PDF file should be displayed. If provided, pageIndex prop will be ignored. Defaults to 1. | 1 |
renderAnnotations | Defined whether annotations (e.g. links) should be rendered. Defaults to true. | false |
renderTextLayer | Defines whether a text layer should be rendered. Defaults to true. | false |
rotate | Defines the rotation of the page in degrees. 90 = rotated to the right, 180 = upside down, 270 = rotated to the left. Defaults to page's default setting, usually 0. | 90 |
scale | Defines the scale in which PDF file should be rendered. Defaults to 1.0. | 0.5 |
width | Defines the width of the page. If not defined, canvas will be rendered at the width defined in PDF. If you define width and scale at the same time, the width will be multiplied by a given factor. | 300 |
Outline
显示大纲(目录)。 必须放在
中或者传递pdf
属性,可以从
中获取onLoadSuccess
回调函数。
Props
Prop name | Description | Example values |
---|---|---|
className | Defines custom class name(s), that will be added to rendered element along with the default ReactPDF__Outline . |
|
onItemClick | Function called when an item has been clicked. Usually, you would like to use this callback to move the user wherever they requested to. | ({ pageNumber }) => alert('Clicked an item from page ' + pageNumber + '!') |
onLoadError | Function called in case of an error while retreiving the outline. | (error) => alert('Error while retreiving the outline! ' + error.message) |
onLoadSuccess | Function called when the outline is successfully retreived. | () => alert('The outline has been successfully retreived.') |
onParseError | Function called in case of an error while parsing the outline. | (error) => alert('Error while parsing the outline! ' + error.message) |
onParseSuccess | Function called when the outline is successfully parsed. | ({ outline }) => alert('There are ' + outline.length + ' top level items in the table of contents.') |
setOptions
允许设置 PDF.js 渲染器的自定义选项。 当前支持的属性有:
- cMapUrl
- cMapPacked
- disableWorker
- workerSrc
用法示例:
setOptions({
workerSrc: 'my-path-to-worker.js'
});
License
MIT 许可证。
Author
Wojciech Maj kontakt@wojtekmaj.pl http://wojtekmaj.pl |
Thank you
如果没有创建初始版本的 Niklas Närhinen niklas@narhinen.net 的出色工作,并且没有 pdf.js。 谢谢你!
![dependencies](https://img.shields.io/david/wojtekmaj/react-pdf.svg ) ![dev dependencies](https://img.shields.io/david/dev/wojtekmaj/react-pdf.svg )
React-PDF
Easily display PDF files in your React application.
tl;dr
- Install by executing
npm install react-pdf
oryarn add react-pdf
. - Import by addding
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
Minimal demo page is included in sample directory.
Online demo is also available!
Getting started
Compatibility
Your project needs to use React 15.5 or later. If you use older version of React, please refer to the table below to find suitable React-PDF version.
React version | Newest supported React-PDF |
---|---|
>15.5 | latest |
>15.0 | 1.6.1 |
>0.14 | 0.0.10 |
>0.13 | 0.0.10 |
>0.11 | 0.0.4 |
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, { Component } from 'react';
import { Document, Page } from 'react-pdf';
class MyApp extends Component {
state = {
numPages: null,
pageNumber: 1,
}
onDocumentLoad = ({ numPages }) => {
this.setState({ numPages });
}
render() {
const { pageNumber, numPages } = this.state;
return (
<div>
<Document
file="somefile.pdf"
onLoadSuccess={this.onDocumentLoad}
>
<Page pageNumber={pageNumber} />
</Document>
<p>Page {pageNumber} of {numPages}</p>
</div>
);
}
}
Check the sample directory of this repository for a full working example.
Enable PDF.js worker
It is crucial for performance to use PDF.js worker whenever possible. This ensures that your PDF file 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
If you use Webpack, you're in luck. Instead of directly importing/requiring 'react-pdf'
, import it like so:
import { Document } from 'react-pdf/build/entry.webpack';
…and you're all set!
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.
I give up
If you absolutely have to, you can import React PDF with worker disabled. You can do so by importing React-PDF like so:
import { Document } from 'react-pdf/build/entry.noworker';
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: CMap baseUrl must be specified, see "PDFJS.cMapUrl" (and also "PDFJS.cMapPacked").
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/'
},
]),
Browserify and others
If you use 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, import setOptions
like so:
import { setOptions } from 'react-pdf';
Note: If you're using a different entry point, for example react-pdf/build/entry.webpack'
, you can should use the same entry point to import setOptions
. You can also add setOptions
to the same import
you're using to import Document
, Page
, and/or other components.
setOptions({
cMapUrl: 'cmaps/',
cMapPacked: true,
});
User guide
Document
Loads a document passed using file
prop.
Props
Prop name | Description | Example values |
---|---|---|
className | Defines custom class name(s), that will be added to rendered element along with the default ReactPDF__Document . |
|
error | Defines what the component should display in case of an error. Defaults to "Failed to load PDF file.". |
|
file | Defines what 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 ). |
|
inputRef | A function that behaves like ref, but it's passed to main <div> rendered by <Document> component. | (ref) => { this.myDocument = ref; } |
loading | Defines what the component should display while loading. Defaults to "Loading PDF…". |
|
noData | Defines what the component should display in case of no data. Defaults to "No PDF file specified.". |
|
onItemClick | Function called when an item has been clicked. Usually, you would like to use this callback to move the user wherever they requested to. | ({ pageNumber }) => alert('Clicked an item from page ' + pageNumber + '!') |
onLoadError | Function called in case of an error while loading a document. | (error) => alert('Error while loading document! ' + error.message) |
onLoadSuccess | Function called when the document is successfully loaded. | (pdf) => alert('Loaded a file with ' + pdf.numPages + ' pages!') |
onSourceError | Function called in case of an error while retrieving document source from file prop. | (error) => alert('Error while retreiving document source! ' + error.message) |
onSourceSuccess | Function called when document source is successfully retreived from file prop. | () => alert('Document source retreived!') |
rotate | Defines the 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. | 90 |
Page
Displays a page. Must be placed inside <Document />
or have pdf
prop passed, which can be obtained from <Document />
's onLoadSuccess
callback function.
Note: <Page/>
must be a direct child of <Document />
component. <Document />
passes necessary props only to its direct children. If you wish to put a component in between of <Document />
and <Page/>
, you must ensure to pass all the props to <Page/>
component by yourself.
Props
Prop name | Description | Example values |
---|---|---|
className | Defines custom class name(s), that will be added to rendered element along with the default ReactPDF__Page . |
|
inputRef | A function that behaves like ref, but it's passed to main <div> rendered by <Page> component. | (ref) => { this.myPage = ref; } |
onLoadError | Function called in case of an error while loading the page. | (error) => alert('Error while loading page! ' + error.message) |
onLoadSuccess | Function called when the page is successfully loaded. | (page) => alert('Now displaying a page number ' + page.pageNumber + '!') |
onRenderError | Function called in case of an error while rendering the page. | (error) => alert('Error while loading page! ' + error.message) |
onRenderSuccess | Function called when the page is successfully rendered on the screen. | () => alert('Rendered the page!') |
pageIndex | Defines which page from PDF file should be displayed. Defaults to 0. | 0 |
pageNumber | Defines which page from PDF file should be displayed. If provided, pageIndex prop will be ignored. Defaults to 1. | 1 |
renderAnnotations | Defined whether annotations (e.g. links) should be rendered. Defaults to true. | false |
renderTextLayer | Defines whether a text layer should be rendered. Defaults to true. | false |
rotate | Defines the rotation of the page in degrees. 90 = rotated to the right, 180 = upside down, 270 = rotated to the left. Defaults to page's default setting, usually 0. | 90 |
scale | Defines the scale in which PDF file should be rendered. Defaults to 1.0. | 0.5 |
width | Defines the width of the page. If not defined, canvas will be rendered at the width defined in PDF. If you define width and scale at the same time, the width will be multiplied by a given factor. | 300 |
Outline
Displays an outline (table of contents). Must be placed inside <Document />
or have pdf
prop passed, which can be obtained from <Document />
's onLoadSuccess
callback function.
Props
Prop name | Description | Example values |
---|---|---|
className | Defines custom class name(s), that will be added to rendered element along with the default ReactPDF__Outline . |
|
onItemClick | Function called when an item has been clicked. Usually, you would like to use this callback to move the user wherever they requested to. | ({ pageNumber }) => alert('Clicked an item from page ' + pageNumber + '!') |
onLoadError | Function called in case of an error while retreiving the outline. | (error) => alert('Error while retreiving the outline! ' + error.message) |
onLoadSuccess | Function called when the outline is successfully retreived. | () => alert('The outline has been successfully retreived.') |
onParseError | Function called in case of an error while parsing the outline. | (error) => alert('Error while parsing the outline! ' + error.message) |
onParseSuccess | Function called when the outline is successfully parsed. | ({ outline }) => alert('There are ' + outline.length + ' top level items in the table of contents.') |
setOptions
Allows to set custom options of PDF.js renderer. Currently supported properties are:
- cMapUrl
- cMapPacked
- disableWorker
- workerSrc
Example usage:
setOptions({
workerSrc: 'my-path-to-worker.js'
});
License
The MIT License.
Author
Wojciech Maj kontakt@wojtekmaj.pl http://wojtekmaj.pl |
Thank you
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. Thank you!