必须配置 PDF.js worker,且 workerSrc 要写在渲染 Document/Page 的同一模块里,否则可能被默认值覆盖;使用注解或文本层需额外引入 AnnotationLayer.css 和 TextLayer.css;非拉丁字符需自行拷贝 pdfjs-dist/cmaps 并配置 cMapUrl,pnpm 用户可能还需 hoist pdfjs-dist。
npm install react-pdf
import { pdfjs } from 'react-pdf';
pdfjs.GlobalWorkerOptions.workerSrc = new URL('pdfjs-dist/build/pdf.worker.min.mjs', import.meta.url).toString();README 未说明硬件要求;运行环境要求 React 19 及以上、Node.js 22.13.0 及以上,浏览器最低 Chrome 125 与 Safari 18(iOS 18)。
在 React 应用里像显示图片一样显示 PDF,基于 PDF.js 封装 Document 和 Page 组件
在 React 应用里像插入图片一样简单显示 PDF,基于 PDF.js 封装成组件,省去自己处理渲染和分页的麻烦。
核心能力
- 用 Document 和 Page 组件声明式渲染 PDF 页面
- file 支持 URL、base64、Uint8Array 等多种来源
- 内置 Suspense 与 Error Boundary 处理加载和错误
- 可选注解层与文本层样式表,支持链接与文本选择
- 支持自定义 PDF.js worker 的引入、拷贝或 CDN 方式
容易踩的坑
- v11.0.0最新正式版2026-09-10 · 2026-09-10 16:44 UTC
See Upgrade guide from version 10.x to 11.x.
React-PDF 11 brings PDF loading into React's Suspense flow. Use the same loading fallbacks and Error Boundaries as the rest of your application, or keep your existing viewer behavior with
suspense={false}.This release also upgrades PDF.js to version 6, with improvements to rendering, accessibility, and performance, along with some important compatibility changes.
👀 Want to see exciting features more often? Consider sponsoring React-PDF.
❗️ = breaking change
What's new?
- ❗️ Added Suspense and Error Boundary support, enabled by default (#2144).
Document,Page,Thumbnail, andOutlinenow use your boundary fallbacks for loading and failures.- Set
suspense={false}onDocumentto keep the previous loading and error behavior. - Use
startTransitionto keep previously revealed content visible while loading another file or page.
- Updated PDF.js from 5.4.296 to 6.3.289 (#2142), bringing improvements to annotation rendering, image decoding, font conversion, text selection, accessibility, and performance.
What's changed?
- ❗️ React 19 is now required (#2143). Support for React 16.8, 17, and 18 has been dropped.
- ❗️ Dropped support for older browsers and Node.js versions. See the upgrade guide for details.
- ❗️ Several PDF.js APIs have changed. If you use
pdfjsdirectly, document/page proxies, or custom data factories, check the upgrade guide. onRenderAnnotationLayerSuccessnow runs after asynchronous annotation rendering finishes, and rendering failures are reported throughonRenderAnnotationLayerError.- In Suspense mode, plain
fileandoptionsobjects are compared by value.
- ❗️ Added Suspense and Error Boundary support, enabled by default (#2144).
- v10.5.02026-08-20 · 2026-08-20 19:48 UTC
查看更新说明
What's changed?
- Text layer styles are now in sync with PDF.js 5.4.296 (#2077).
If you were customizing text layer styles, note that
--highlight-bg-colorand--highlight-selected-bg-colormoved from:rootto.textLayer .highlightand are now semi-transparent, and that.textLayerz-indexchanged from2to0. - Documented legacy PDF.js worker, reported to work on iOS 16.4 and newer.
- Updated pnpm hoisting instructions for pnpm 11+ (#2114).
- Clarified that filtering of HTML returned by
customTextRendereris best-effort, and sanitizing it is up to you.
Bug fixes
- Fixed text layer being misaligned with page content (#2064).
- Fixed crash when
<Document />was hidden and revealed by<Activity>(#2128). - Disallowed
data:URLs in URL attributes returned bycustomTextRenderer.
- Text layer styles are now in sync with PDF.js 5.4.296 (#2077).
If you were customizing text layer styles, note that
- v10.4.12026-02-25 · 2026-02-25 14:28 UTC
查看更新说明
Bug fixes
- Sanitize HTML returned by
customTextRenderer(#2070).
- Sanitize HTML returned by
- v10.4.02026-02-21 · 2026-02-21 00:35 UTC
查看更新说明
What's new?
- Added support for
pageColorsprop in Page component (#2068). With this option, you can easily override colors used to render the PDF and implement accessibility enhancements. For example, this:
will result in the following:<Page /* … */ pageColors={{ background: 'black', foreground: '#FF0000' }} />
- Added support for
- v10.3.02025-12-30 · 2025-12-30 21:39 UTC
查看更新说明
What's new?
- Added support for
filterAnnotationsprop inPagecomponent (#1991). - Made the code more resilient to promise cancellations (#974).
What's changed?
- Tests are no longer shipped to npm. This helped reducing publish size from 416 kB to 303 kB.
- Updated Next.js samples.
Bug fixes
- Fixed incorrectly calculated dimensions of rotated pages in Page onLoadSuccess handler (#2027). Thanks, @wkirby!
- Added support for
用户点评
登录用户的真实使用记录,可按版本和硬件筛选还没有人点评。第一个说出真实体验的人最有价值。
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-pdforyarn add react-pdf. - Import by adding
import { Document } from 'react-pdf'. - Wrap the viewer in React
Suspenseand an Error Boundary, then add<Document file="..." />.filecan be a URL, base64 content, Uint8Array, and more. - Put
<Page />components inside<Document />to render pages. - Import stylesheets for annotations and text layer if applicable.
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 11.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
Browser support
React-PDF supports the latest versions of all major modern browsers.
Minimum browser requirements are Chrome 125 and Safari 18 (iOS 18). Versions below the latest releases, but meeting these minimums, may require additional polyfills, bundler transpilation, and the legacy PDF.js worker.
For example, Chrome 125 requires a polyfill for URL.parse(), which is used by PDF.js. Load the polyfill before initializing React-PDF:
if (typeof URL !== 'undefined' && typeof URL.parse !== 'function') {
URL.parse = function (url, base) {
try {
return new URL(url, base);
} catch {
return null;
}
};
}
Polyfilling this API alone does not establish compatibility with browsers below the minimum requirements.
For details, see the PDF.js browser compatibility documentation.
React
To use the latest version of React-PDF, your project needs to use React 19 or later.
Preact
React-PDF may be used with Preact. Use preact/compat (Preact's React adapter) with use support.
Node.js
React-PDF requires Node.js 22.13.0 or newer.
Installation
Add React-PDF to your project by executing npm install react-pdf or yarn add react-pdf.
Next.js
If you use Next.js prior to v15 (v15.0.0-canary.53, specifically), you may need to add the following to your next.config.js:
module.exports = {
+ swcMinify: false,
}
Configure PDF.js worker
For React-PDF to work, PDF.js worker needs to be provided. You have several options.
Import worker (recommended)
For most cases, the following example will work:
import { pdfjs } from 'react-pdf';
pdfjs.GlobalWorkerOptions.workerSrc = new URL(
'pdfjs-dist/build/pdf.worker.min.mjs',
import.meta.url,
).toString();
[!WARNING] The
workerSrcmust be set in the same module where you use React-PDF components (e.g.,<Document>,<Page>). Setting it in a separate file likemain.tsxand then importing React-PDF in another component may cause the default value to overwrite your custom setting due to module execution order. Always configure the worker in the file where you render the PDF components.
[!NOTE] In Next.js, make sure to skip SSR when importing the module you're using this code in. Here's how to do this in Pages Router and App Router.
[!NOTE] pnpm users may need to hoist
pdfjs-distfor this setup to work:pnpm < 11 — add this to
.npmrc:public-hoist-pattern[]=pdfjs-distpnpm 11+ — add this to
pnpm-workspace.yaml:publicHoistPattern: - pdfjs-dist
Parcel 2
For Parcel 2, you need to use a slightly different code:
pdfjs.GlobalWorkerOptions.workerSrc = new URL(
- 'pdfjs-dist/build/pdf.worker.min.mjs',
+ 'npm:pdfjs-dist/build/pdf.worker.min.mjs',
import.meta.url,
).toString();
Copy worker to public directory
You will have to make sure on your own that pdf.worker.mjs file from pdfjs-dist/build is copied to your project's output folder.
For example, you could use a custom script like:
import path from 'node:path';
import fs from 'node:fs';
const pdfjsDistPath = path.dirname(require.resolve('pdfjs-dist/package.json'));
const pdfWorkerPath = path.join(pdfjsDistPath, 'build', 'pdf.worker.mjs');
fs.cpSync(pdfWorkerPath, './dist/pdf.worker.mjs', { recursive: true });
Use external CDN
import { pdfjs } from 'react-pdf';
pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.mjs`;
[!WARNING] The
workerSrcmust be set in the same module where you use React-PDF components (e.g.,<Document>,<Page>). Setting it in a separate file likemain.tsxand then importing React-PDF in another component may cause the default value to overwrite your custom setting due to module execution order. Always configure the worker in the file where you render the PDF components.
Legacy PDF.js worker
If you need to support older browsers, you may use legacy PDF.js worker. This is not a complete backwards-compatibility solution: you may still need additional polyfills and bundler transpilation.
To do so, follow the instructions above, but replace /build/ with /legacy/build/ in PDF.js worker import path, for example:
pdfjs.GlobalWorkerOptions.workerSrc = new URL(
- 'pdfjs-dist/build/pdf.worker.min.mjs',
+ 'pdfjs-dist/legacy/build/pdf.worker.min.mjs',
import.meta.url,
).toString();
or:
-pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.mjs`;
+pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/legacy/build/pdf.worker.min.mjs`;
Usage
Here's an example of basic usage. It uses react-error-boundary (npm install react-error-boundary or yarn add react-error-boundary); you can also use your application's own Error Boundary:
import { Suspense, useState } from 'react';
import { ErrorBoundary } from 'react-error-boundary';
import { Document, Page } from 'react-pdf';
function MyApp() {
const [numPages, setNumPages] = useState<number>();
const [pageNumber, setPageNumber] = useState<number>(1);
function onDocumentLoadSuccess({ numPages }: { numPages: number }): void {
setNumPages(numPages);
}
return (
<div>
<ErrorBoundary fallback={<p>Failed to load PDF.</p>}>
<Suspense fallback={<p>Loading document…</p>}>
<Document file="somefile.pdf" onLoadSuccess={onDocumentLoadSuccess}>
<Suspense fallback={<p>Loading page…</p>}>
<Page pageNumber={pageNumber} />
</Suspense>
</Document>
</Suspense>
</ErrorBoundary>
<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.
Loading and errors
Document, Page, Thumbnail, and Outline use Suspense and Error Boundaries by default. Suspense waits for document, page, or outline data; canvas and other layers render progressively, with their errors also reaching the boundary. noData still handles empty input.
Set suspense={false} to use the existing loading and error props. Children inherit this setting and can override it:
<Document error="Could not load PDF." file={file} loading="Loading PDF…" suspense={false}>
<Page pageNumber={1} />
</Document>
Load callbacks remain available, with success callbacks running after commit. Keep password and progress UI outside the suspended viewer. Use startTransition when changing files or pages to keep previously revealed content visible while loading.
Suspense compares plain file/options objects by value. Keep binary inputs, workers, and range transports outside the suspended subtree. Concurrent initial loads may share password/progress handlers; superseded loads may still call them.
Wrap Document in the Error Boundary so resetting it retries the entire load. To reload a mounted document, change its React key. See the test page for an example.
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:
import 'react-pdf/dist/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:
import 'react-pdf/dist/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.
Vite
Add vite-plugin-static-copy by executing npm install vite-plugin-static-copy --save-dev or yarn add vite-plugin-static-copy --dev and add the following to your Vite config:
+import path from 'node:path';
+import { createRequire } from 'node:module';
-import { defineConfig } from 'vite';
+import { defineConfig, normalizePath } from 'vite';
+import { viteStaticCopy } from 'vite-plugin-static-copy';
+const require = createRequire(import.meta.url);
+
+const pdfjsDistPath = path.dirname(require.resolve('pdfjs-dist/package.json'));
+const cMapsDir = normalizePath(path.join(pdfjsDistPath, 'cmaps'));
export default defineConfig({
plugins: [
+ viteStaticCopy({
+ targets: [
+ {
+ src: cMapsDir,
+ dest: 'cmaps',
+ rename: { stripBase: true },
+ },
+ ],
+ }),
]
});
Webpack
Add copy-webpack-plugin by executing npm install copy-webpack-plugin --save-dev or yarn add copy-webpack-plugin --dev and add the following to your Webpack config:
+import path from 'node:path';
+import CopyWebpackPlugin from 'copy-webpack-plugin';
+const pdfjsDistPath = path.dirname(require.resolve('pdfjs-dist/package.json'));
+const cMapsDir = path.join(pdfjsDistPath, 'cmaps');
module.exports = {
plugins: [
+ new CopyWebpackPlugin({
+ patterns: [
+ {
+ from: cMapsDir,
+ to: 'cmaps/'
+ },
+ ],
+ }),
],
};
Other tools
If you use other bundlers, 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:
import path from 'node:path';
import fs from 'node:fs';
const pdfjsDistPath = path.dirname(require.resolve('pdfjs-dist/package.json'));
const cMapsDir = path.join(pdfjsDistPath, 'cmaps');
fs.cpSync(cMapsDir, 'dist/cmaps/', { recursive: true });
Setting up React-PDF
Now that you have cMaps in your build, pass required options to Document component by using options prop, like so:
// Outside of React component
const options = {
cMapUrl: '/cmaps/',
};
// Inside of React component
<Document options={options} />;
[!NOTE] Make sure to define
optionsobject outside of your React component or useuseMemoif you can't.
Alternatively, you could use cMaps from external CDN:
// Outside of React component
import { pdfjs } from 'react-pdf';
const options = {
cMapUrl: `https://unpkg.com/pdfjs-dist@${pdfjs.version}/cmaps/`,
};
// Inside of React component
<Document options={options} />;
Support for JPEG 2000 and JBIG2
If you want to ensure that JPEG 2000 and JBIG2 images in PDFs will render, or you have encountered one of the following warnings:
Warning: Unable to decode image "img_p0_1": "JpxError: OpenJPEG failed to initialize".
Warning: Unable to decode image "img_p0_1": "Jbig2Error: JBig2 failed to initialize".
then you would also need to include wasm directory in your build and tell React-PDF where it is.
Copying wasm directory
First, you need to copy wasm from pdfjs-dist (React-PDF's dependency - it should be in your node_modules if you have React-PDF installed). Wasm files are located in pdfjs-dist/wasm.
Vite
Add vite-plugin-static-copy by executing npm install vite-plugin-static-copy --save-dev or yarn add vite-plugin-static-copy --dev and add the following to your Vite config:
+import path from 'node:path';
+import { createRequire } from 'node:module';
-import { defineConfig } from 'vite';
+import { defineConfig, normalizePath } from 'vite';
+import { viteStaticCopy } from 'vite-plugin-static-copy';
+const require = createRequire(import.meta.url);
+
+const pdfjsDistPath = path.dirname(require.resolve('pdfjs-dist/package.json'));
+const wasmDir = normalizePath(path.join(pdfjsDistPath, 'wasm'));
export default defineConfig({
plugins: [
+ viteStaticCopy({
+ targets: [
+ {
+ src: wasmDir,
+ dest: 'wasm',
+ rename: { stripBase: true },
+ },
+ ],
+ }),
]
});
Webpack
Add copy-webpack-plugin by executing npm install copy-webpack-plugin --save-dev or yarn add copy-webpack-plugin --dev and add the following to your Webpack config:
+import path from 'node:path';
+import CopyWebpackPlugin from 'copy-webpack-plugin';
+const pdfjsDistPath = path.dirname(require.resolve('pdfjs-dist/package.json'));
+const wasmDir = path.join(pdfjsDistPath, 'wasm');
module.exports = {
plugins: [
+ new CopyWebpackPlugin({
+ patterns: [
+ {
+ from: wasmDir,
+ to: 'wasm/'
+ },
+ ],
+ }),
],
};
Other tools
If you use other bundlers, you will have to make sure on your own that wasm directory is copied to your project's output folder.
For example, you could use a custom script like:
import path from 'node:path';
import fs from 'node:fs';
const pdfjsDistPath = path.dirname(require.resolve('pdfjs-dist/package.json'));
const wasmDir = path.join(pdfjsDistPath, 'wasm');
fs.cpSync(wasmDir, 'dist/wasm/', { recursive: true });
Setting up React-PDF
Now that you have wasm directory in your build, pass required options to Document component by using options prop, like so:
// Outside of React component
const options = {
wasmUrl: '/wasm/',
};
// Inside of React component
<Document options={options} />;
[!NOTE] Make sure to define
optionsobject outside of your React component or useuseMemoif you can't.
Alternatively, you could use wasm directory from external CDN:
// Outside of React component
import { pdfjs } from 'react-pdf';
const options = {
wasmUrl: `https://unpkg.com/pdfjs-dist@${pdfjs.version}/wasm/`,
};
// Inside of React component
<Document options={options} />;
Support for standard fonts
If you want to support PDFs using standard fonts (deprecated in PDF 1.5, but still around), or you have encountered the following warning:
The standard font "baseUrl" parameter must be specified, ensure that the "standardFontDataUrl" API parameter is provided.
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.
Vite
Add vite-plugin-static-copy by executing npm install vite-plugin-static-copy --save-dev or yarn add vite-plugin-static-copy --dev and add the following to your Vite config:
+import path from 'node:path';
+import { createRequire } from 'node:module';
-import { defineConfig } from 'vite';
+import { defineConfig, normalizePath } from 'vite';
+import { viteStaticCopy } from 'vite-plugin-static-copy';
+const require = createRequire(import.meta.url);
+const standardFontsDir = normalizePath(
+ path.join(path.dirname(require.resolve('pdfjs-dist/package.json')), 'standard_fonts')
+);
export default defineConfig({
plugins: [
+ viteStaticCopy({
+ targets: [
+ {
+ src: standardFontsDir,
+ dest: 'standard_fonts',
+ rename: { stripBase: true },
+ },
+ ],
+ }),
]
});
Webpack
Add copy-webpack-plugin by executing npm install copy-webpack-plugin --save-dev or yarn add copy-webpack-plugin --dev and add the following to your Webpack config:
+import path from 'node:path';
+import CopyWebpackPlugin from 'copy-webpack-plugin';
+const standardFontsDir = path.join(path.dirname(require.resolve('pdfjs-dist/package.json')), 'standard_fonts');
module.exports = {
plugins: [
+ new CopyWebpackPlugin({
+ patterns: [
+ {
+ from: standardFontsDir,
+ to: 'standard_fonts/'
+ },
+ ],
+ }),
],
};
Other tools
If you use other bundlers, 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:
import path from 'node:path';
import fs from 'node:fs';
const pdfjsDistPath = path.dirname(require.resolve('pdfjs-dist/package.json'));
const standardFontsDir = path.join(pdfjsDistPath, 'standard_fonts');
fs.cpSync(standardFontsDir, 'dist/standard_fonts/', { recursive: true });
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:
// Outside of React component
const options = {
standardFontDataUrl: '/standard_fonts/',
};
// Inside of React component
<Document options={options} />;
[!NOTE] Make sure to define
optionsobject outside of your React component or useuseMemoif you can't.
Alternatively, you could use standard fonts from external CDN:
// Outside of React component
import { pdfjs } from 'react-pdf';
const options = {
standardFontDataUrl: `https://unpkg.com/pdfjs-dist@${pdfjs.version}/standard_fonts/`,
};
// Inside of React component
<Document options={options} />;
User guide
Document
Loads a document passed using file prop.
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__Document. | n/a | String:"custom-class-name-1 custom-class-name-2"Array of strings:["custom-class-name-1", "custom-class-name-2"] |
| error | What the component should display in case of an error when suspense={false}. | "Failed to load PDF file." | String:"An error occurred!"React element:<p>An error occurred!</p>Function:this.renderError |
| externalLinkRel | Link rel for links rendered in annotations. | "noopener noreferrer nofollow" | One of valid values for rel attribute."noopener""noreferrer""nofollow""noopener noreferrer" |
| 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."_self""_blank""_parent""_top" |
| file | 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.Suspense compares plain parameter objects by value. Keep binary inputs and range transports outside the suspended subtree. With suspense={false}, memoize object props to avoid unnecessary reloads. | n/a | URL:"https://example.com/sample.pdf"File:import importedPdf from '../static/sample.pdf' and thensampleParameter object:{ url: 'https://example.com/sample.pdf' } |
| 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 main <div> rendered by <Document> component. | n/a | Function:(ref) => { this.myDocument = ref; }Ref created using createRef:this.ref = createRef();…inputRef={this.ref}Ref created using useRef:const ref = useRef();…inputRef={ref} |
| loading | What the component should display while loading when suspense={false}. | "Loading PDF…" | String:"Please wait!"React element:<p>Please wait!</p>Function:this.renderLoader |
| noData | What the component should display in case of no data. | "No PDF file specified." | String:"Please select a file."React element:<p>Please select a file.</p>Function:this.renderNoData |
| onItemClick | Function called when an outline item or a thumbnail has been clicked. Usually, you would like to use this callback to move the user wherever they requested to. | n/a | ({ dest, pageIndex, 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) |
| 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 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. | Function that prompts the user for password. | (callback) => callback('s3cr3t_p4ssw0rd') |
| 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) |
| onSourceSuccess | Function called when document source is successfully retrieved from file prop. | n/a | () => alert('Document source retrieved!') |
| options | An object in which additional parameters to be passed to PDF.js can be defined. Most notably:cMapUrl;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)For a full list of possible parameters, check PDF.js documentation on DocumentInitParameters.Suspense compares plain options by value. Keep workers and other non-plain values outside the suspended subtree. With suspense={false}, memoize options to avoid unnecessary reloads. | n/a | { cMapUrl: '/cmaps/' } |
| renderMode | Rendering mode of the document. Can be "canvas", "custom" or "none". If set to "custom", customRenderer must also be provided. | "canvas" | "custom" |
| 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 |
| scale | Document scale. | 1 | 0.5 |
| suspense | Use React Suspense and Error Boundaries for loading and failures. Children inherit the document setting and can override it. | true | false |
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 rendering annotations and linking between pages inside a document may not be working correctly.
Props
| Prop name | Description | Default value | Example values |
|---|---|---|---|
| canvasBackground | Canvas background color. Any valid canvas.fillStyle can be used. | n/a | "transparent" |
| canvasRef | A prop that behaves like ref, but it's passed to <canvas> rendered by <Canvas> component. | n/a | Function:(ref) => { this.myCanvas = ref; }Ref created using createRef:this.ref = createRef();…inputRef={this.ref}Ref created using useRef:const ref = useRef();…inputRef={ref} |
| className | Class name(s) that will be added to rendered element along with the default react-pdf__Page. | n/a | String:"custom-class-name-1 custom-class-name-2"Array of strings:["custom-class-name-1", "custom-class-name-2"] |
| customRenderer | Function that customizes how a page is rendered. You must set renderMode to "custom" to use this prop. | n/a | MyCustomRenderer |
| customTextRenderer | Function that customizes how a text layer is rendered. React-PDF applies best-effort filtering to the returned HTML, but you are responsible for ensuring that it is safe and properly sanitized. | n/a | ({ str, itemIndex }) => str.replace(/ipsum/g, value => `<mark>${value}</mark>`) |
| devicePixelRatio | The ratio between physical pixels and device-independent pixels (DIPs) on the current device. | window.devicePixelRatio | 1 |
| error | What the component should display in case of an error when suspense={false}. | "Failed to load the page." | String:"An error occurred!"React element:<p>An error occurred!</p>Function:this.renderError |
| filterAnnotations | Function to filter annotations before they are rendered. | n/a | ({ annotations }) => annotations.filter(annotation => annotation.subtype === 'Text') |
| 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 |
| 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 main <div> rendered by <Page> component. | n/a | Function:(ref) => { this.myPage = ref; }Ref created using createRef:this.ref = createRef();…inputRef={this.ref}Ref created using useRef:const ref = useRef();…inputRef={ref} |
| loading | What the component should display while loading when suspense={false}. | "Loading page…" | String:"Please wait!"React element:<p>Please wait!</p>Function:this.renderLoader |
| noData | What the component should display in case of no data. | "No page specified." | String:"Please select a page."React element:<p>Please select a page.</p>Function:this.renderNoData |
| onGetAnnotationsError | Function called in case of an error while loading annotations. | n/a | (error) => alert('Error while loading annotations! ' + error.message) |
| onGetAnnotationsSuccess | Function called when annotations are successfully loaded. | n/a | (annotations) => alert('Now displaying ' + annotations.length + ' annotations!') |
| onGetStructTreeError | Function called in case of an error while loading structure tree. | n/a | (error) => alert('Error while loading structure tree! ' + error.message) |
| onGetStructTreeSuccess | Function called when structure tree is successfully loaded. | n/a | (structTree) => alert(JSON.stringify(structTree)) |
| 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) |
| onGetTextSuccess | Function called when text layer items are successfully loaded. | n/a | ({ items, styles }) => alert('Now displaying ' + items.length + ' text layer items!') |
| onLoadError | Function called in case of an error while loading the page. | n/a | (error) => alert('Error while loading page! ' + error.message) |
| onLoadSuccess | Function called when the page is successfully loaded. | n/a | (page) => alert('Now displaying a page number ' + page.pageNumber + '!') |
| onRenderAnnotationLayerError | Function called in case of an error while rendering the annotation layer. | n/a | (error) => alert('Error while loading annotation layer! ' + error.message) |
| onRenderAnnotationLayerSuccess | Function called when annotations are successfully rendered on the screen. | n/a | () => alert('Rendered the annotation layer!') |
| 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!') |
| onRenderTextLayerError | Func |