### Install React-PDF Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Install React-PDF using npm or yarn. ```bash npm install react-pdf yarn add react-pdf ``` -------------------------------- ### Custom Text Rendering Example Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Customize how text is rendered by providing a function to `customTextRenderer`. This example highlights all occurrences of 'ipsum' with a `` tag. ```javascript ({ str, itemIndex }) => str.replace(/ipsum/g, value => `${value}`) ``` -------------------------------- ### Example: renderAnnotationLayer Prop Source: https://github.com/wojtekmaj/react-pdf/blob/main/packages/react-pdf/README.md Set the `renderAnnotationLayer` prop to `true` to render annotations such as links on the PDF page. Defaults to `true`. ```javascript false ``` -------------------------------- ### React-PDF onItemClick Callback Example Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Callback function executed when an outline item or thumbnail is clicked. Use this to navigate to the requested page. ```javascript ({ dest, pageIndex, pageNumber }) => alert('Clicked an item from page ' + pageNumber + '!') ``` -------------------------------- ### Example: pageIndex Prop Source: https://github.com/wojtekmaj/react-pdf/blob/main/packages/react-pdf/README.md Display a specific page from the PDF file using its index with the `pageIndex` prop. This prop is ignored if `pageNumber` is provided. The index is zero-based. ```javascript 1 ``` -------------------------------- ### Display All Pages in React PDF Source: https://github.com/wojtekmaj/react-pdf/wiki/Recipes Renders all pages of a PDF document. This approach uses state to keep track of the total number of pages and dynamically creates a Page component for each. Be aware of potential performance issues with very large documents. ```javascript import React, { useState } from 'react'; import { Document, Page } from 'react-pdf'; import samplePDF from './test.pdf'; export default function Test() { const [numPages, setNumPages] = useState(null); function onDocumentLoadSuccess({ numPages }) { setNumPages(numPages); } return ( {Array.from( new Array(numPages), (el, index) => ( ), )} ); } ``` -------------------------------- ### Display Single Page in React PDF Source: https://github.com/wojtekmaj/react-pdf/wiki/Recipes Renders a single page of a PDF document using the react-pdf library. It requires the Document and Page components and a PDF file as input. The output is a single rendered page of the PDF. ```javascript import React from 'react'; import { Document, Page } from 'react-pdf'; import samplePDF from './test.pdf'; export default function Test() { return ( ); } ``` -------------------------------- ### React-PDF onLoadSuccess Callback Example Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Callback function executed once the document has been successfully loaded. It receives the PDF document object. ```javascript (pdf) => alert('Loaded a file with ' + pdf.numPages + ' pages!') ``` -------------------------------- ### ReactPDF Component Replacement (React) Source: https://github.com/wojtekmaj/react-pdf/wiki/Upgrade-guide-from-version-1.x-to-2.x In v2.x, the single ReactPDF component has been replaced by two distinct components: Document and Page. This allows for rendering multiple pages efficiently by loading the file only once. The example shows the transition from the v1.x syntax to the v2.x syntax for rendering a single page. ```jsx ``` ```jsx ``` -------------------------------- ### Example: renderForms Prop Source: https://github.com/wojtekmaj/react-pdf/blob/main/packages/react-pdf/README.md Set the `renderForms` prop to `true` to render form fields within the PDF. This requires the `renderAnnotationLayer` prop to also be set to `true`. Defaults to `false`. ```javascript true ``` -------------------------------- ### Display Single Page with Navigation in React PDF Source: https://github.com/wojtekmaj/react-pdf/wiki/Recipes Enables navigation between pages of a PDF document. It displays a single page at a time and provides 'Previous' and 'Next' buttons to change the current page. The current page number and total number of pages are also displayed. ```javascript import React, { useState } from 'react'; import { Document, Page } from 'react-pdf'; import samplePDF from './test.pdf'; export default function Test() { const [numPages, setNumPages] = useState(null); const [pageNumber, setPageNumber] = useState(1); function onDocumentLoadSuccess({ numPages }) { setNumPages(numPages); setPageNumber(1); } function changePage(offset) { setPageNumber(prevPageNumber => prevPageNumber + offset); } function previousPage() { changePage(-1); } function nextPage() { changePage(1); } return ( <>

Page {pageNumber || (numPages ? 1 : '--')} of {numPages || '--'}

); } ``` -------------------------------- ### React-PDF onLoadProgress Callback Example Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Callback function that is called, possibly multiple times, during the document loading process. It provides loaded and total byte counts. ```javascript ({ loaded, total }) => alert('Loading a document: ' + (loaded / total) * 100 + '%') ``` -------------------------------- ### Handle External Links in React PDF Source: https://github.com/wojtekmaj/react-pdf/wiki/Recipes Enables handling of external links within a PDF document. When an outline item that is an external link is clicked, the `onItemClick` prop on the `Document` component can be used to manage the navigation or action. This example shows how to use `onItemClick` directly on the `Document` component. ```javascript import React, { useState } from 'react'; import { Document, Outline, Page } from 'react-pdf'; import samplePDF from './test.pdf'; export default function Test() { const [pageNumber, setPageNumber] = useState(1); function onItemClick({ pageNumber: itemPageNumber }) { setPageNumber(itemPageNumber); } return ( ); } ``` -------------------------------- ### Configure PDF.js options in React-PDF Source: https://github.com/wojtekmaj/react-pdf/wiki/Upgrade-guide-from-version-3.x-to-4.x Demonstrates the migration from the deprecated setOptions function to the modern options prop on the Document component. This allows for instance-specific configuration of PDF.js settings like cMap URLs. ```javascript import { setOptions } from 'react-pdf'; setOptions({ cMapUrl: 'cmaps/', cMapPacked: true, }); ``` ```javascript const options = { cMapUrl: 'cmaps/', cMapPacked: true, }; ``` -------------------------------- ### Handle Input Reference with Function Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Pass a function to the inputRef prop to get a reference to the main div element. ```javascript (ref) => { this.myDocument = ref; } ``` -------------------------------- ### Example: pageNumber Prop Source: https://github.com/wojtekmaj/react-pdf/blob/main/packages/react-pdf/README.md Display a specific page from the PDF file using its page number with the `pageNumber` prop. If this prop is provided, the `pageIndex` prop will be ignored. Page numbers are typically one-based. ```javascript 2 ``` -------------------------------- ### Configure PDF.js Worker for Parcel 2 Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md For Parcel 2, use a modified workerSrc path starting with 'npm:'. ```diff 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 PDF.js Worker Script Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Use this script to copy the pdf.worker.mjs file to your project's output directory. Ensure the destination path is correct for your build setup. ```typescript 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 }); ``` -------------------------------- ### Display Interactive Table of Contents in React PDF Source: https://github.com/wojtekmaj/react-pdf/wiki/Recipes Renders an interactive Table of Contents (TOC) for a PDF document. Clicking on an item in the TOC navigates the user to the corresponding page in the document. This utilizes the `Outline` component for displaying the TOC. ```javascript import React, { useState } from 'react'; import { Document, Outline, Page } from 'react-pdf'; import samplePDF from './test.pdf'; export default function Test() { const [pageNumber, setPageNumber] = useState(1); function onItemClick({ pageNumber: itemPageNumber }) { setPageNumber(itemPageNumber); } return ( ); } ``` -------------------------------- ### Highlight Text on Page in React PDF Source: https://github.com/wojtekmaj/react-pdf/wiki/Recipes Highlights specific text within a PDF page based on user input. It uses a custom text renderer to wrap matching text with a `` tag. This allows for visual searching within the document content. ```javascript import React, { useCallback, useState } from 'react'; import { Document, Page } from 'react-pdf'; import samplePDF from './test.pdf'; function highlightPattern(text, pattern) { return text.replace(pattern, (value) => `${value}`); } export default function Test() { const [searchText, setSearchText] = useState(''); const textRenderer = useCallback( (textItem) => highlightPattern(textItem.str, searchText), [searchText] ); function onChange(event) { setSearchText(event.target.value); } return ( <>
); } ``` -------------------------------- ### Specify PDF File from Import Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Import a PDF file directly into your project and pass it as the file prop. ```javascript import importedPdf from '../static/sample.pdf' sample ``` -------------------------------- ### Basic Document Usage Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Use the Document component to display a PDF. The 'file' prop accepts various formats like URLs, base64, or Uint8Array. ```javascript ``` -------------------------------- ### Basic React-PDF Usage Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Demonstrates the basic integration of the Document and Page components in a React application. It includes state management for page numbers and a success handler for document loading. ```tsx import { useState } from 'react'; import { Document, Page } from 'react-pdf'; function MyApp() { const [numPages, setNumPages] = useState(); const [pageNumber, setPageNumber] = useState(1); function onDocumentLoadSuccess({ numPages }: { numPages: number }): void { setNumPages(numPages); } return (

Page {pageNumber} of {numPages}

); } ``` -------------------------------- ### canvasRef Source: https://github.com/wojtekmaj/react-pdf/blob/main/packages/react-pdf/README.md Allows you to get a reference to the rendered `` element, similar to how React refs work. ```APIDOC ## canvasRef ### Description Allows you to get a reference to the rendered `` element, similar to how React refs work. ### Prop `canvasRef` (function | React.RefObject) ### Default Value n/a ### Example Values ```javascript // Function callback (ref) => { this.myCanvas = ref; } // Ref created with createRef const myRef = createRef(); // Ref created with useRef const myRef = useRef(); ``` ``` -------------------------------- ### React-PDF onLoadError Callback Example Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Callback function invoked if an error occurs during document loading. It receives an error object. ```javascript (error) => alert('Error while loading document! ' + error.message) ``` -------------------------------- ### Set Loading State with Function Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Provide a function that returns the content to be displayed during the loading state. ```javascript this.renderLoader ``` -------------------------------- ### Next.js Configuration for SWC Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md If using Next.js prior to v15, disable SWC minification to avoid potential issues with React-PDF. ```diff module.exports = { + swcMinify: false, } ``` -------------------------------- ### Using canvasRef with a Function Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Pass a function to canvasRef to get a direct reference to the canvas element. This is useful for imperative DOM manipulations or integrations. ```javascript (ref) => { this.myCanvas = ref; } ``` -------------------------------- ### pageNumber Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Determines which page from the PDF file to display, identified by its page number (starting from 1). If this prop is provided, the `pageIndex` prop will be ignored. ```APIDOC ## pageNumber ### Description Which page from PDF file should be displayed, by page number. If provided, `pageIndex` prop will be ignored. ### Type `number` ### Default `1` ### Example ```javascript 2 ``` ``` -------------------------------- ### Configure React-PDF Document with Local Standard Fonts Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Pass the 'options' prop to the Document component with 'standardFontDataUrl' pointing to the local path where fonts were copied. Define the options object outside the component for performance. ```jsx // Outside of React component const options = { standardFontDataUrl: '/standard_fonts/', }; // Inside of React component ; ``` -------------------------------- ### Handle No Data in react-pdf Source: https://github.com/wojtekmaj/react-pdf/blob/main/packages/react-pdf/README.md Specify what to display when no PDF file is provided. This can be a string, a React element, or a function. ```javascript "No PDF file specified." ``` ```javascript "Please select a file." ``` ```javascript

Please select a file.

``` ```javascript this.renderNoData ``` -------------------------------- ### Configure React-PDF Document with CDN Standard Fonts Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Use the 'options' prop with 'standardFontDataUrl' set to a CDN path for standard fonts, dynamically including the pdfjs.version. This is an alternative to local copying. ```jsx // 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 ; ``` -------------------------------- ### Referencing Page Div in React-PDF Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md The `inputRef` prop allows you to get a reference to the main `
` rendered by the `` component. It supports functions, `createRef`, and `useRef`. ```javascript (ref) => { this.myPage = ref; } ``` ```javascript this.ref = createRef(); ... inputRef={this.ref} ``` ```javascript const ref = useRef(); ... inputRef={ref} ``` -------------------------------- ### React-PDF Document Options with Local WASM Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Configure the Document component with the 'options' prop to specify the URL for the local WASM directory. Ensure the wasmUrl path matches your build output. ```typescript // Outside of React component const options = { wasmUrl: '/wasm/', }; // Inside of React component ; ``` -------------------------------- ### Manage Input Ref in react-pdf Source: https://github.com/wojtekmaj/react-pdf/blob/main/packages/react-pdf/README.md The `inputRef` prop allows you to get a reference to the main `
` element rendered by the `` component. It supports function refs, `createRef`, and `useRef`. ```javascript import React, { useRef } from 'react'; function MyComponent() { const pdfContainerRef = useRef(null); return ; } ``` -------------------------------- ### onLoadSuccess Prop Source: https://github.com/wojtekmaj/react-pdf/blob/main/packages/react-pdf/README.md A callback function that is executed once the document has been successfully loaded. It receives the PDF document object, which contains information like the total number of pages. ```APIDOC ## onLoadSuccess ### Description Function called when the document is successfully loaded. ### Parameters - **pdf** (object): The loaded PDF document object. It has a `numPages` property. ### Example Usage ```javascript alert('Loaded a file with ' + pdf.numPages + ' pages!')} /> ``` ``` -------------------------------- ### Configure Vite for Standard Fonts Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Integrate vite-plugin-static-copy into your Vite configuration to copy standard fonts from pdfjs-dist to your build output. Ensure the plugin is added to the plugins array. ```diff +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: '', + }, + ], + }), ] }); ``` -------------------------------- ### Patch for Node.js Canvas Rendering in PDF.js Source: https://github.com/wojtekmaj/react-pdf/wiki/Upgrade-guide-from-version-8.x-to-9.x A diff patch for pdf.mjs to resolve 'createCanvas' errors in Node.js environments by explicitly importing the canvas module. ```diff diff --git a/build/pdf.mjs b/build/pdf.mjs index 003035596c3797888692cafd43f9466f96607d55..e69bc909492626f188ccff66b24a8d586fd96a30 100644 --- a/build/pdf.mjs +++ b/build/pdf.mjs @@ -5303,8 +5303,9 @@ if (isNodeJS) { const fs = await import( /*webpackIgnore: true*/"fs"), http = await import( /*webpackIgnore: true*/"http"), https = await import( /*webpackIgnore: true*/"https"), - url = await import( /*webpackIgnore: true*/"url"); - let canvas, path2d; + url = await import( /*webpackIgnore: true*/"url"), + canvas = await import( /*webpackIgnore: true*/"canvas"); + let path2d; return new Map(Object.entries({ fs, http, ``` -------------------------------- ### Set Loading State as String Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Display a simple string message while the PDF is loading. ```javascript "Please wait!" ``` -------------------------------- ### onGetTextSuccess Prop Source: https://github.com/wojtekmaj/react-pdf/blob/main/packages/react-pdf/README.md A callback function that is invoked when text layer items are successfully loaded. ```APIDOC ## onGetTextSuccess ### Description Function called when text layer items are successfully loaded. ### Type Function ### Callback Signature `({ items, styles }) => void` ### Example `({ items, styles }) => alert('Now displaying ' + items.length + ' text layer items!')` ``` -------------------------------- ### Update React-PDF Import Paths Source: https://github.com/wojtekmaj/react-pdf/wiki/Upgrade-guide-from-version-9.x-to-10.x Updates import statements to reflect the removal of separate CJS and ESM build directories. The paths have been simplified to point directly to the /dist folder. ```diff - import 'react-pdf/dist/esm/Page/AnnotationLayer.css'; - import 'react-pdf/dist/esm/Page/TextLayer.css'; + import 'react-pdf/dist/Page/AnnotationLayer.css'; + import 'react-pdf/dist/Page/TextLayer.css'; ``` -------------------------------- ### Import TextLayer CSS in React-PDF Source: https://github.com/wojtekmaj/react-pdf/wiki/Upgrade-guide-from-version-5.x-to-6.x To ensure the text layer renders correctly in PDFs, you must manually import the required stylesheet into your application. This is a mandatory step for v6 functionality. ```javascript import 'react-pdf/dist/esm/Page/TextLayer.css'; ``` -------------------------------- ### onLoadSuccess Prop Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md A callback function that is executed once the document has been successfully loaded. ```APIDOC ## onLoadSuccess Prop ### Description Function called when the document is successfully loaded. ### Type Function ### Parameters - `pdf` (object): An object representing the loaded PDF document, containing properties like `numPages`. ### Example `(pdf) => alert('Loaded a file with ' + pdf.numPages + ' pages!')` ``` -------------------------------- ### Handle Input Reference with createRef Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Use createRef to manage the reference to the main div element. ```javascript this.ref = createRef(); ... inputRef={this.ref} ``` -------------------------------- ### Set Image Resources Path Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Define a path to prefix the src attributes of annotation SVGs. Defaults to an empty string if not provided. ```javascript "/public/images/" ``` -------------------------------- ### loading Prop Source: https://github.com/wojtekmaj/react-pdf/blob/main/packages/react-pdf/README.md Defines the content to be displayed while the PDF document is loading. Can be a string, a React element, or a function. ```APIDOC ## loading ### Description What the component should display while loading. ### Type `string | ReactElement | function` ### Default `"Loading PDF…"` ### Examples - String: `"Please wait!"` - React element: `

Please wait!

` - Function: `this.renderLoader` ``` -------------------------------- ### Update onGetTextSuccess callback signature Source: https://github.com/wojtekmaj/react-pdf/wiki/Upgrade-guide-from-version-5.x-to-6.x The onGetTextSuccess callback signature has been updated to receive an object containing items and styles instead of just the items array. This change requires updating existing function definitions to use object destructuring. ```diff -function onGetTextSuccess(items) { +function onGetTextSuccess({ items }) { // … ``` -------------------------------- ### Set Loading State as React Element Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Render a custom React element to indicate the loading state. ```javascript

Please wait!

``` -------------------------------- ### onGetTextSuccess Prop Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md A function that is called when text layer items are successfully loaded. ```APIDOC ## onGetTextSuccess Prop ### Description Function called when text layer items are successfully loaded. ### Type Function ### Callback Signature `({ items, styles }) => void` ### Example `({ items, styles }) => alert('Now displaying ' + items.length + ' text layer items!')` ``` -------------------------------- ### Custom Script to Copy WASM Directory Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md A custom Node.js script using fs.cpSync to copy the WASM directory. This is a fallback for bundlers not explicitly covered. ```typescript 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 }); ``` -------------------------------- ### file Prop Source: https://github.com/wojtekmaj/react-pdf/blob/main/packages/react-pdf/README.md Specifies the PDF document to be displayed. Accepts a URL, a file object, or a configuration object. ```APIDOC ## file ### Description What PDF should be displayed. ### Type `string | File | object` ### Default `n/a` ### Details 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. **Warning**: Since equality check (`===`) is used to determine if `file` object has changed, it must be memoized by setting it in component's state, `useMemo` or other similar technique. ### Examples - URL: `"https://example.com/sample.pdf"` - File: `import importedPdf from '../static/sample.pdf'` and then `sample` - Parameter object: `{ url: 'https://example.com/sample.pdf' }` ``` -------------------------------- ### Specify PDF File URL Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Provide a URL string to load a PDF document. ```javascript "https://example.com/sample.pdf" ``` -------------------------------- ### Configure Legacy PDF.js Worker from CDN Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Use this configuration to load a legacy PDF.js worker from an unpkg CDN, which may be necessary for supporting older browsers. Ensure you also include necessary polyfills and transpilation. ```diff pdfjs.GlobalWorkerOptions.workerSrc = new URL( - 'pdfjs-dist/build/pdf.worker.min.mjs', + 'pdfjs-dist/legacy/build/pdf.worker.min.mjs', import.meta.url, ).toString(); ``` ```diff -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`; ``` -------------------------------- ### onSourceSuccess Prop Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md This function is called when the document source is successfully retrieved from the 'file' prop. ```APIDOC ## onSourceSuccess ### Description Function called when document source is successfully retrieved from `file` prop. ### Example ```javascript () => alert('Document source retrieved!') ``` ``` -------------------------------- ### onGetAnnotationsSuccess Prop Source: https://github.com/wojtekmaj/react-pdf/blob/main/packages/react-pdf/README.md A callback function that is invoked when annotations are successfully loaded. ```APIDOC ## onGetAnnotationsSuccess ### Description Function called when annotations are successfully loaded. ### Type Function ### Callback Signature `(annotations) => void` ### Example `(annotations) => alert('Now displaying ' + annotations.length + ' annotations!')` ``` -------------------------------- ### onRenderSuccess Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Function called when the page is successfully rendered on the screen. It takes no arguments. ```APIDOC ## onRenderSuccess ### Description Function called when the page is successfully rendered on the screen. ### Parameters This function takes no arguments. ### Example ```javascript () => alert('Rendered the page!') ``` ``` -------------------------------- ### Handle Successful Text Layer Item Loading in React-PDF Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Configure the `onGetTextSuccess` prop with a callback function to be executed when text layer items are loaded successfully. This function receives an object containing the loaded `items` and `styles`. ```javascript ({ items, styles }) => alert('Now displaying ' + items.length + ' text layer items!') ``` -------------------------------- ### onGetStructTreeSuccess Prop Source: https://github.com/wojtekmaj/react-pdf/blob/main/packages/react-pdf/README.md A callback function that is invoked when the structure tree is successfully loaded. ```APIDOC ## onGetStructTreeSuccess ### Description Function called when structure tree is successfully loaded. ### Type Function ### Callback Signature `(structTree) => void` ### Example `(structTree) => alert(JSON.stringify(structTree))` ``` -------------------------------- ### React-PDF Document Options with Local cMaps Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Configure the Document component with the 'options' prop to specify the URL for local cMaps. Ensure the cMapUrl path matches your build output. ```typescript // Outside of React component const options = { cMapUrl: '/cmaps/', }; // Inside of React component ; ``` -------------------------------- ### Specify PDF File via Parameter Object Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Use an object with a 'url' property to specify the PDF file location. ```javascript { url: 'https://example.com/sample.pdf' } ``` -------------------------------- ### Password Callback for Protected PDFs Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Use the `onPassword` prop to provide a callback function that supplies the password for protected PDFs. This function should accept a callback argument and invoke it with the password string. ```javascript (callback) => callback('s3cr3t_p4ssw0rd') ``` -------------------------------- ### Handling Outline Item Clicks in react-pdf Source: https://github.com/wojtekmaj/react-pdf/blob/main/packages/react-pdf/README.md Implement the `onItemClick` prop to define behavior when a user clicks on an outline item. This callback provides information about the clicked item, such as its destination, page index, and page number. ```javascript onItemClick={({ dest, pageIndex, pageNumber }) => alert('Clicked an item from page ' + pageNumber + '!')} ``` -------------------------------- ### Page Component Props Source: https://github.com/wojtekmaj/react-pdf/blob/main/packages/react-pdf/README.md Configuration options for the Page component, including how to handle device pixel ratio, errors, and page dimensions. ```javascript window.devicePixelRatio ``` ```javascript "Failed to load the page." ``` ```javascript ({ annotations }) => annotations.filter(annotation => annotation.subtype === 'Text') ``` ```javascript 300 ``` ```javascript "/public/images/" ``` ```javascript (ref) => { this.myPage = ref; } ``` ```javascript this.ref = createRef(); … inputRef={this.ref} ``` ```javascript const ref = useRef(); … inputRef={ref} ``` ```javascript "Loading page…" ``` -------------------------------- ### onGetStructTreeSuccess Prop Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md A function that is called when the structure tree is successfully loaded. ```APIDOC ## onGetStructTreeSuccess Prop ### Description Function called when structure tree is successfully loaded. ### Type Function ### Callback Signature `(structTree) => void` ### Example `(structTree) => alert(JSON.stringify(structTree))` ``` -------------------------------- ### Handle No Data Display with react-pdf Source: https://github.com/wojtekmaj/react-pdf/blob/main/packages/react-pdf/README.md Configure the 'noData' prop to specify what to display when no PDF data is available. This can be a string, a React element, or a function. ```javascript "No page specified." ``` ```javascript "Please select a page." ``` ```javascript

Please select a page.

``` ```javascript this.renderNoData ``` -------------------------------- ### onGetAnnotationsSuccess Prop Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md A function that is called when annotations are successfully loaded. ```APIDOC ## onGetAnnotationsSuccess Prop ### Description Function called when annotations are successfully loaded. ### Type Function ### Callback Signature `(annotations) => void` ### Example `(annotations) => alert('Now displaying ' + annotations.length + ' annotations!')` ``` -------------------------------- ### Thumbnail Component Source: https://github.com/wojtekmaj/react-pdf/blob/main/packages/react-pdf/README.md Displays a thumbnail of a page. It does not render annotation or text layers and does not act as a link target. Clicking it attempts to navigate to the clicked page. Should be placed inside `` or receive a `pdf` prop. ```APIDOC ## Thumbnail Component Displays a thumbnail of a page. Does not render the annotation layer or the text layer. Does not register itself as a link target, so the user will not be scrolled to a Thumbnail component when clicked on an internal link (e.g. in Table of Contents). When clicked, attempts to navigate to the page clicked (similarly to a link in Outline). Should be placed inside ``. Alternatively, it can have `pdf` prop passed, which can be obtained from ``'s `onLoadSuccess` callback function. ``` -------------------------------- ### Import Stylesheet for Annotations Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Import this CSS file to enable the display of annotations, such as links, within rendered PDFs. This should be done in the same module where React-PDF components are used. ```typescript import 'react-pdf/dist/Page/AnnotationLayer.css'; ``` -------------------------------- ### options Prop Source: https://github.com/wojtekmaj/react-pdf/blob/main/packages/react-pdf/README.md Allows passing additional parameters to PDF.js, such as cMapUrl and httpHeaders for custom requests. ```APIDOC ## options ### Description 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](https://mozilla.github.io/pdf.js/api/draft/module-pdfjsLib.html#~DocumentInitParameters). **Note**: Make sure to define options object outside of your React component or use `useMemo` if you can't. ### Example ```javascript { cMapUrl: '/cmaps/' } ``` ``` -------------------------------- ### Success Notification for Document Source Retrieval Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Utilize the `onSourceSuccess` prop to define a callback function that executes upon successful retrieval of the document source. This is useful for displaying success messages or triggering subsequent actions. ```javascript () => alert('Document source retrieved!') ``` -------------------------------- ### Page Loading Event Handlers Source: https://github.com/wojtekmaj/react-pdf/blob/main/packages/react-pdf/README.md Callbacks triggered when a page is being loaded or has finished loading. ```APIDOC ## onLoadError ### Description Function called in case of an error while loading the page. ### Parameters - **error** (Error) - Description of the error object. ### Example ```javascript (error) => alert('Error while loading page! ' + error.message) ``` ## onLoadSuccess ### Description Function called when the page is successfully loaded. ### Parameters - **page** (object) - An object containing information about the loaded page, including `pageNumber`. ### Example ```javascript (page) => alert('Now displaying a page number ' + page.pageNumber + '!') ``` ``` -------------------------------- ### onLoadProgress Prop Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md A callback function that is called, potentially multiple times, to report the progress of the document loading. ```APIDOC ## onLoadProgress Prop ### Description Function called, potentially multiple times, as the loading progresses. ### Type Function ### Parameters - `loaded` (number): The amount of data loaded so far. - `total` (number): The total amount of data to be loaded. ### Example `({ loaded, total }) => alert('Loading a document: ' + (loaded / total) * 100 + '%')` ``` -------------------------------- ### onLoadProgress Prop Source: https://github.com/wojtekmaj/react-pdf/blob/main/packages/react-pdf/README.md A callback function that is called, potentially multiple times, to report the progress of the document loading. It provides the current loaded amount and the total expected size. ```APIDOC ## onLoadProgress ### Description Function called, potentially multiple times, as the loading progresses. ### Parameters - **loaded** (number): The amount of data loaded so far. - **total** (number): The total expected size of the document. ### Example Usage ```javascript alert('Loading a document: ' + (loaded / total) * 100 + '%')} /> ``` ``` -------------------------------- ### Handle Successful PDF Page Render in React-PDF Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Employ the onRenderSuccess prop to run a function once a PDF page has been successfully rendered on the screen. This callback takes no arguments. ```javascript () => alert('Rendered the page!') ``` -------------------------------- ### Configure PDF.js Worker (Recommended) Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Configure the PDF.js worker source URL. This must be set in the same module where React-PDF components are used. Ensure the worker path is correctly resolved. ```typescript import { pdfjs } from 'react-pdf'; pdfjs.GlobalWorkerOptions.workerSrc = new URL( 'pdfjs-dist/build/pdf.worker.min.mjs', import.meta.url, ).toString(); ``` -------------------------------- ### onItemClick Prop Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md A callback function that is invoked when an outline item or a thumbnail is clicked. This is typically used to navigate the user to the selected part of the document. ```APIDOC ## onItemClick Prop ### Description 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. ### Type Function ### Parameters - `dest` (object): Destination object for navigation. - `pageIndex` (number): The index of the page that was clicked. - `pageNumber` (number): The page number that was clicked. ### Example `({ dest, pageIndex, pageNumber }) => alert('Clicked an item from page ' + pageNumber + '!')` ``` -------------------------------- ### Configure React-PDF Worker Source (JavaScript) Source: https://github.com/wojtekmaj/react-pdf/wiki/Known-issues This code snippet demonstrates how to configure the worker source for React-PDF to load from an external CDN. This is a workaround for 'SyntaxError: expected expression, got <' and 'ReferenceError: window is not defined' errors, especially when not ejecting from Create React App. It requires the 'react-pdf' package. ```javascript import { pdfjs } from 'react-pdf'; pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`; ``` -------------------------------- ### Configure Webpack for Standard Fonts Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Use copy-webpack-plugin in your Webpack configuration to copy standard fonts from pdfjs-dist to your build. The plugin should be added to the plugins array in your Webpack configuration. ```diff +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/' + }, + ], + }), ], }; ``` -------------------------------- ### Import Document Component Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Import the Document component for use in your React application. ```javascript import { Document } from 'react-pdf' ``` -------------------------------- ### Custom Script to Copy cMaps Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md A custom Node.js script using fs.cpSync to copy the cMaps directory. This is useful for bundlers not explicitly covered. ```typescript 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 }); ``` -------------------------------- ### Outline Component Source: https://github.com/wojtekmaj/react-pdf/blob/main/packages/react-pdf/README.md Displays an outline (table of contents) for the PDF document. It should be placed inside the `` component or receive a `pdf` prop. ```APIDOC ## Outline Component Displays an outline (table of contents). Should be placed inside ``. Alternatively, it can have `pdf` prop passed, which can be obtained from ``'s `onLoadSuccess` callback function. ### Props | Prop name | Description | | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | | className | Class name(s) that will be added to rendered element along with the default `react-pdf__Outline`. | | inputRef | A prop that behaves like [ref](https://reactjs.org/docs/refs-and-the-dom.html), but it's passed to main `
` rendered by `` component. | | onItemClick | Function called when an outline item has been clicked. Usually, you would like to use this callback to move the user wherever they requested to. | | onLoadError | Function called in case of an error while retrieving the outline. | | onLoadSuccess | Function called when the outline is successfully retrieved. | ``` -------------------------------- ### Import Stylesheet for Text Layer Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Import this CSS file to enable the display of the text layer in rendered PDFs, allowing for text selection and searching. This should be done in the same module where React-PDF components are used. ```typescript import 'react-pdf/dist/Page/TextLayer.css'; ``` -------------------------------- ### Handle Successful Structure Tree Loading in React-PDF Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Use the `onGetStructTreeSuccess` prop to specify a callback function that is executed when the structure tree is loaded successfully. The structure tree data is passed as an argument to this function. ```javascript (structTree) => alert(JSON.stringify(structTree)) ``` -------------------------------- ### options Prop Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md An object for defining additional parameters to be passed to PDF.js. This can include cMapUrl and httpHeaders. ```APIDOC ## options ### Description 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](https://mozilla.github.io/pdf.js/api/draft/module-pdfjsLib.html#~DocumentInitParameters). **Note**: Make sure to define options object outside of your React component or use `useMemo` if you can't. ### Example ```javascript { cMapUrl: '/cmaps/' } ``` ``` -------------------------------- ### onLoadSuccess Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Function called when the page is successfully loaded. It receives a page object with page details as an argument. ```APIDOC ## onLoadSuccess ### Description Function called when the page is successfully loaded. ### Parameters #### Arguments - **page** (object) - An object containing page details, including `pageNumber`. ### Example ```javascript (page) => alert('Now displaying a page number ' + page.pageNumber + '!') ``` ``` -------------------------------- ### Page Rendering Event Handlers Source: https://github.com/wojtekmaj/react-pdf/blob/main/packages/react-pdf/README.md Callbacks triggered when a page is being rendered or has finished rendering on the screen. ```APIDOC ## onRenderError ### Description Function called in case of an error while rendering the page. ### Parameters - **error** (Error) - Description of the error object. ### Example ```javascript (error) => alert('Error while loading page! ' + error.message) ``` ## onRenderSuccess ### Description Function called when the page is successfully rendered on the screen. ### Example ```javascript () => alert('Rendered the page!') ``` ``` -------------------------------- ### Customize Loading State in react-pdf Source: https://github.com/wojtekmaj/react-pdf/blob/main/packages/react-pdf/README.md The `loading` prop allows customization of the content displayed while the PDF is loading. It can be a string, a React element, or a function returning renderable content. ```javascript Please wait!
} /> ``` -------------------------------- ### Configure Vite for Copying cMaps Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md This Vite configuration uses `vite-plugin-static-copy` to copy cMaps from `pdfjs-dist` to your build output. This is necessary for proper rendering of PDFs with non-Latin characters. ```diff import path from 'node:path'; import { createRequire } from 'node:module'; 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: '', }, ], }), ] }); ``` -------------------------------- ### width Prop Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Sets the width of the rendered page. If height is also provided, height will be ignored. If scale is provided, width will be multiplied by the scale factor. ```APIDOC ## width Prop ### Description Page width. 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 `width` and `scale` at the same time, the width will be multiplied by a given factor. ### Type Number ### Default Value Page's default width ### Example `300` (sets the page width to 300 pixels). ``` -------------------------------- ### inputRef Prop Source: https://github.com/wojtekmaj/react-pdf/blob/main/packages/react-pdf/README.md A ref passed to the main `
` rendered by the `` component, allowing direct access to the DOM element. ```APIDOC ## inputRef ### Description A prop that behaves like [ref](https://reactjs.org/docs/refs-and-the-dom.html), but it's passed to main `
` rendered by `` component. ### Type `function | object` ### Default `n/a` ### Examples - Function: `(ref) => { this.myDocument = ref; }` - Ref created using `createRef`: `this.ref = createRef();` ... `inputRef={this.ref}` - Ref created using `useRef`: `const ref = useRef();` ... `inputRef={ref}` ``` -------------------------------- ### Configuring PDF.js Options Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md The `options` prop allows you to pass additional parameters to PDF.js, such as `cMapUrl` for character map URLs or `httpHeaders` for custom request headers. Define this object outside your component or use `useMemo` to prevent unnecessary re-renders. ```javascript { cMapUrl: '/cmaps/' } ``` -------------------------------- ### renderTextLayer Prop Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Determines whether a text layer should be rendered on top of the document for text selection and searching. ```APIDOC ## renderTextLayer Prop ### Description Whether a text layer should be rendered. ### Type Boolean ### Default Value `true` ### Possible Values - `true`: Enables the text layer. - `false`: Disables the text layer. ``` -------------------------------- ### Specify PDF File in react-pdf Source: https://github.com/wojtekmaj/react-pdf/blob/main/packages/react-pdf/README.md The `file` prop accepts a URL, a file import, or an object with `url` or `data` properties. Ensure the `file` object is memoized if it's an object to prevent unnecessary re-renders. ```javascript import importedPdf from '../static/sample.pdf'; // Usage examples: ``` -------------------------------- ### Configure Vite to Copy WASM Files Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Use vite-plugin-static-copy to copy the WASM directory from pdfjs-dist to your Vite project's output. This is required for JPEG 2000 support. ```diff +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: '', + }, + ], + }), ] }); ``` -------------------------------- ### Configure Webpack to Copy WASM Files Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Use copy-webpack-plugin to copy the WASM directory from pdfjs-dist to your Webpack project's output. This is necessary for JPEG 2000 image rendering. ```diff +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/' + }, + ], + }), ], }; ``` -------------------------------- ### pdf Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md The PDF object that is obtained from the `onLoadSuccess` callback function of the parent `` component. This prop is essential for the PDF component to render the document content. ```APIDOC ## pdf ### Description pdf object obtained from ``'s `onLoadSuccess` callback function. ### Type `object` ### Default `(automatically obtained from parent )` ### Example ```javascript pdf ``` ``` -------------------------------- ### Render PDF Pages Source: https://github.com/wojtekmaj/react-pdf/blob/main/README.md Nest Page components within the Document component to render individual PDF pages. ```javascript ```