在 React 应用中显示 PDF 文件,就像显示图像一样简单。
Display PDFs in your React app as easily as if they were images.
This package is used to display existing PDFs. If you wish to create PDFs using React, you may be looking for @react-pdf/renderer.
npm install react-pdf or yarn add react-pdf.import { Document } from 'react-pdf'.Suspense and an Error Boundary, then add <Document file="..." />. file can be a URL, base64 content, Uint8Array, and more.<Page /> components inside <Document /> to render pages.A minimal demo page can be found in sample directory.
Online demo is also available!
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:
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 details, see the PDF.js browser compatibility documentation.
To use the latest version of React-PDF, your project needs to use React 19 or later.
React-PDF may be used with Preact. Use preact/compat (Preact's React adapter) with use support.
React-PDF requires Node.js 22.13.0 or newer.
Add React-PDF to your project by executing npm install react-pdf or yarn add react-pdf.
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,
}
For React-PDF to work, PDF.js worker needs to be provided. You have several options.
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.
See more examplesParcel 2[!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
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();
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 });
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.
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`;
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 (
);
}
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.
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.
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';
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';
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.
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.
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:
…
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 });
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} />;
If you want to ensure that JPEG 2000 images in PDFs will render, or you have encountered the following warning:
Warni
暂无开放 Issues,或尚未同步最近议题。