百科.dev
全部条目AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
R

react-pdf

> 前端框架
开源

在 React 应用中显示 PDF 文件,就像显示图像一样简单。

11.1K stars0 点赞0 次浏览
访问官网GitHub

工具介绍

在 React 应用中显示 PDF 文件,就像显示图像一样简单。

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-pdf or yarn add react-pdf.
  • Import by adding import { Document } from 'react-pdf'.
  • Wrap the viewer in React Suspense and an Error Boundary, then add <Document file="..." />. file can 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:

  • v10.x
  • v9.x
  • v8.x
  • v7.x
  • v6.x
  • v5.x

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 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 workerSrc must be set in the same module where you use React-PDF components (e.g., <Document>, <Page>). Setting it in a separate file like main.tsx and 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-dist for this setup to work:

pnpm < 11 — add this to .npmrc:

public-hoist-pattern[]=pdfjs-dist

pnpm 11+ — add this to pnpm-workspace.yaml:

publicHoistPattern:
  - pdfjs-dist
See more examplesParcel 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 workerSrc must be set in the same module where you use React-PDF components (e.g., <Document>, <Page>). Setting it in a separate file like main.tsx and 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 (
    

  );
}

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:

…
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 options object outside of your React component or use useMemo if 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

If you want to ensure that JPEG 2000 images in PDFs will render, or you have encountered the following warning:

Warni

GitHub Issues· 0 开放

在 GitHub 查看全部

暂无开放 Issues,或尚未同步最近议题。

核心特点

  • •Install by executing npm install react-pdf or yarn add react-pdf.
  • •Import by adding import { Document } from 'react-pdf'.
  • •Wrap the viewer in React Suspense and an Error Boundary, then add <Document file="..." />. file can 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.
  • •swcMinify: false,
  • •'pdfjs-dist/build/pdf.worker.min.mjs',
  • •'npm:pdfjs-dist/build/pdf.worker.min.mjs',
  • •'pdfjs-dist/build/pdf.worker.min.mjs',
  • •'pdfjs-dist/legacy/build/pdf.worker.min.mjs',

> 标签

TypeScriptpdfpdf-viewerreact

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类前端框架
定价开源

> 相关工具

R
React
用于构建用户界面的 JavaScript 库
V
Vue.js
渐进式 JavaScript 框架
N
Next.js
基于 React 的全栈 Web 框架