react-pdf

wojtekmajMIT活跃维护

在 React 应用里像插入图片一样简单显示 PDF,基于 PDF.js 封装成组件,省去自己处理渲染和分页的麻烦。

Display PDFs in your React app as easily as if they were images.

v11.0.0发布于 2026-09-10 16:44 UTC11,197star1,004fork同步于 2026-11-10 11:28 UTC

怎么上手

由 README 提炼,执行前请确认
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 说明

README 未说明硬件要求;运行环境要求 React 19 及以上、Node.js 22.13.0 及以上,浏览器最低 Chrome 125 与 Safari 18(iOS 18)。

下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

在 React 应用里像显示图片一样显示 PDF,基于 PDF.js 封装 Document 和 Page 组件

在 React 应用里像插入图片一样简单显示 PDF,基于 PDF.js 封装成组件,省去自己处理渲染和分页的麻烦。

核心能力

  • 用 Document 和 Page 组件声明式渲染 PDF 页面
  • file 支持 URL、base64、Uint8Array 等多种来源
  • 内置 Suspense 与 Error Boundary 处理加载和错误
  • 可选注解层与文本层样式表,支持链接与文本选择
  • 支持自定义 PDF.js worker 的引入、拷贝或 CDN 方式

容易踩的坑

必须配置 PDF.js worker,且 workerSrc 要写在渲染 Document/Page 的同一模块里,否则可能被默认值覆盖;使用注解或文本层需额外引入 AnnotationLayer.css 和 TextLayer.css;非拉丁字符需自行拷贝 pdfjs-dist/cmaps 并配置 cMapUrl,pnpm 用户可能还需 hoist pdfjs-dist。

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

5 个版本v11.0.0
  1. 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, and Outline now use your boundary fallbacks for loading and failures.
      • Set suspense={false} on Document to keep the previous loading and error behavior.
      • Use startTransition to 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 pdfjs directly, document/page proxies, or custom data factories, check the upgrade guide.
    • onRenderAnnotationLayerSuccess now runs after asynchronous annotation rendering finishes, and rendering failures are reported through onRenderAnnotationLayerError.
    • In Suspense mode, plain file and options objects are compared by value.
  2. 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-color and --highlight-selected-bg-color moved from :root to .textLayer .highlight and are now semi-transparent, and that .textLayer z-index changed from 2 to 0.
    • 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 customTextRenderer is 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 by customTextRenderer.
  3. v10.4.12026-02-25 · 2026-02-25 14:28 UTC
    查看更新说明

    Bug fixes

    • Sanitize HTML returned by customTextRenderer (#2070).
  4. v10.4.02026-02-21 · 2026-02-21 00:35 UTC
    查看更新说明

    What's new?

    • Added support for pageColors prop in Page component (#2068). With this option, you can easily override colors used to render the PDF and implement accessibility enhancements. For example, this:
      <Page /* … */ pageColors={{ background: 'black', foreground: '#FF0000' }} />
      
      will result in the following:
  5. v10.3.02025-12-30 · 2025-12-30 21:39 UTC
    查看更新说明

    What's new?

    • Added support for filterAnnotations prop in Page component (#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!

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    npm downloads CI

    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:

    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 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
    
    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 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 (
        <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 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 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 options object outside of your React component or use useMemo if 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 options object outside of your React component or use useMemo if 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 nameDescriptionDefault valueExample values
    classNameClass name(s) that will be added to rendered element along with the default react-pdf__Document.n/aString:"custom-class-name-1 custom-class-name-2"Array of strings:["custom-class-name-1", "custom-class-name-2"]
    errorWhat 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
    externalLinkRelLink rel for links rendered in annotations."noopener noreferrer nofollow"One of valid values for rel attribute."noopener""noreferrer""nofollow""noopener noreferrer"
    externalLinkTargetLink target for external links rendered in annotations.unset, which means that default behavior will be usedOne of valid values for target attribute."_self""_blank""_parent""_top"
    fileWhat 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/aURL:"https://example.com/sample.pdf"File:import importedPdf from '../static/sample.pdf' and thensampleParameter object:{ url: 'https://example.com/sample.pdf' }
    imageResourcesPathThe path used to prefix the src attributes of annotation SVGs.n/a (pdf.js will fallback to an empty string)"/public/images/"
    inputRefA prop that behaves like ref, but it's passed to main <div> rendered by <Document> component.n/aFunction:(ref) => { this.myDocument = ref; }Ref created using createRef:this.ref = createRef();…inputRef={this.ref}Ref created using useRef:const ref = useRef();…inputRef={ref}
    loadingWhat the component should display while loading when suspense={false}."Loading PDF…"String:"Please wait!"React element:<p>Please wait!</p>Function:this.renderLoader
    noDataWhat 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
    onItemClickFunction 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 + '!')
    onLoadErrorFunction called in case of an error while loading a document.n/a(error) => alert('Error while loading document! ' + error.message)
    onLoadProgressFunction called, potentially multiple times, as the loading progresses.n/a({ loaded, total }) => alert('Loading a document: ' + (loaded / total) * 100 + '%')
    onLoadSuccessFunction called when the document is successfully loaded.n/a(pdf) => alert('Loaded a file with ' + pdf.numPages + ' pages!')
    onPasswordFunction called when a password-protected PDF is loaded.Function that prompts the user for password.(callback) => callback('s3cr3t_p4ssw0rd')
    onSourceErrorFunction called in case of an error while retrieving document source from file prop.n/a(error) => alert('Error while retrieving document source! ' + error.message)
    onSourceSuccessFunction called when document source is successfully retrieved from file prop.n/a() => alert('Document source retrieved!')
    optionsAn 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/' }
    renderModeRendering mode of the document. Can be "canvas", "custom" or "none". If set to "custom", customRenderer must also be provided."canvas""custom"
    rotateRotation 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/a90
    scaleDocument scale.10.5
    suspenseUse React Suspense and Error Boundaries for loading and failures. Children inherit the document setting and can override it.truefalse

    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 nameDescriptionDefault valueExample values
    canvasBackgroundCanvas background color. Any valid canvas.fillStyle can be used.n/a"transparent"
    canvasRefA prop that behaves like ref, but it's passed to <canvas> rendered by <Canvas> component.n/aFunction:(ref) => { this.myCanvas = ref; }Ref created using createRef:this.ref = createRef();…inputRef={this.ref}Ref created using useRef:const ref = useRef();…inputRef={ref}
    classNameClass name(s) that will be added to rendered element along with the default react-pdf__Page.n/aString:"custom-class-name-1 custom-class-name-2"Array of strings:["custom-class-name-1", "custom-class-name-2"]
    customRendererFunction that customizes how a page is rendered. You must set renderMode to "custom" to use this prop.n/aMyCustomRenderer
    customTextRendererFunction 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>`)
    devicePixelRatioThe ratio between physical pixels and device-independent pixels (DIPs) on the current device.window.devicePixelRatio1
    errorWhat 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
    filterAnnotationsFunction to filter annotations before they are rendered.n/a({ annotations }) => annotations.filter(annotation => annotation.subtype === 'Text')
    heightPage 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 height300
    imageResourcesPathThe path used to prefix the src attributes of annotation SVGs.n/a (pdf.js will fallback to an empty string)"/public/images/"
    inputRefA prop that behaves like ref, but it's passed to main <div> rendered by <Page> component.n/aFunction:(ref) => { this.myPage = ref; }Ref created using createRef:this.ref = createRef();…inputRef={this.ref}Ref created using useRef:const ref = useRef();…inputRef={ref}
    loadingWhat the component should display while loading when suspense={false}."Loading page…"String:"Please wait!"React element:<p>Please wait!</p>Function:this.renderLoader
    noDataWhat 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
    onGetAnnotationsErrorFunction called in case of an error while loading annotations.n/a(error) => alert('Error while loading annotations! ' + error.message)
    onGetAnnotationsSuccessFunction called when annotations are successfully loaded.n/a(annotations) => alert('Now displaying ' + annotations.length + ' annotations!')
    onGetStructTreeErrorFunction called in case of an error while loading structure tree.n/a(error) => alert('Error while loading structure tree! ' + error.message)
    onGetStructTreeSuccessFunction called when structure tree is successfully loaded.n/a(structTree) => alert(JSON.stringify(structTree))
    onGetTextErrorFunction called in case of an error while loading text layer items.n/a(error) => alert('Error while loading text layer items! ' + error.message)
    onGetTextSuccessFunction called when text layer items are successfully loaded.n/a({ items, styles }) => alert('Now displaying ' + items.length + ' text layer items!')
    onLoadErrorFunction called in case of an error while loading the page.n/a(error) => alert('Error while loading page! ' + error.message)
    onLoadSuccessFunction called when the page is successfully loaded.n/a(page) => alert('Now displaying a page number ' + page.pageNumber + '!')
    onRenderAnnotationLayerErrorFunction called in case of an error while rendering the annotation layer.n/a(error) => alert('Error while loading annotation layer! ' + error.message)
    onRenderAnnotationLayerSuccessFunction called when annotations are successfully rendered on the screen.n/a() => alert('Rendered the annotation layer!')
    onRenderErrorFunction called in case of an error while rendering the page.n/a(error) => alert('Error while loading page! ' + error.message)
    onRenderSuccessFunction called when the page is successfully rendered on the screen.n/a() => alert('Rendered the page!')
    onRenderTextLayerErrorFunc