### Install React PDF Viewer core package
Source: https://react-pdf-viewer.dev/docs/getting-started
Command to install the main `@react-pdf-viewer/core` package using npm. This package provides the essential functionalities for the React PDF Viewer.
```bash
npm install @react-pdf-viewer/core@3.12.0
```
--------------------------------
### Verify pdfjs-dist dependency in package.json
Source: https://react-pdf-viewer.dev/docs/getting-started
An example of how the `pdfjs-dist` dependency appears in the `dependencies` section of your `package.json` file after successful installation.
```json
{
"dependencies": {
"pdfjs-dist": "^3.4.120"
}
}
```
--------------------------------
### Install pdfjs-dist via npm
Source: https://react-pdf-viewer.dev/docs/getting-started
Command to install the `pdfjs-dist` library, a required dependency for React PDF Viewer, using the npm package manager. This version is specified to ensure compatibility.
```bash
npm install pdfjs-dist@3.4.120
```
--------------------------------
### Install canvas dependencies on macOS (Apple M1 fix)
Source: https://react-pdf-viewer.dev/docs/getting-started
Commands to install necessary dependencies for the `canvas` package on macOS using Homebrew. This addresses common installation issues with `pdfjs-dist` on Apple M1 chips that might require `canvas`.
```bash
$ brew install pkg-config cairo pango
```
--------------------------------
### Control React PDF Viewer Component Size with CSS
Source: https://react-pdf-viewer.dev/docs/basic-usage
This example illustrates how to manage the visual dimensions of the `Viewer` component within a React application. By wrapping the `Viewer` in a `div` element and applying inline CSS styles, such as `height` and `border`, developers can explicitly control the space the PDF viewer occupies on the page, as the component defaults to taking the full size of its parent container.
```javascript
```
--------------------------------
### Integrate Plugins with React-PDF-Viewer
Source: https://react-pdf-viewer.dev/docs/options
Shows how to integrate external plugins with the React-PDF-Viewer component. This example demonstrates importing a plugin, creating an instance, and passing it to the 'plugins' array property of the Viewer component to extend its functionality.
```JavaScript
import { bookmarkPlugin } from '@react-pdf-viewer/bookmark';
// Create new plugin instance
const bookmarkPluginInstance = bookmarkPlugin();
// Render
;
```
--------------------------------
### Render React Application Root Component
Source: https://react-pdf-viewer.dev/docs/basic-usage
This standard React snippet demonstrates the typical entry point for a React application, where the main `App` component is rendered into a specific DOM element, commonly identified by 'root'. This is a foundational step in setting up any React project.
```JavaScript
render(, document.getElementById('root'));
```
--------------------------------
### Handle Theme Switching and Persist Theme with onSwitchTheme Callback
Source: https://react-pdf-viewer.dev/docs/options
Illustrates how to implement the `onSwitchTheme` callback to manage theme changes. The example shows storing the selected theme in `localStorage` and loading it back on subsequent visits, then applying it to the `Viewer` component.
```TypeScript
const handleSwitchTheme = (theme: string) => {
localStorage.setItem('theme', theme);
};
const theme = localStorage.getItem('theme') || 'light';
;
```
--------------------------------
### Set Initial Page for React-PDF-Viewer
Source: https://react-pdf-viewer.dev/docs/options
Demonstrates how to configure the React-PDF-Viewer component to display a specific page upon initial load. The 'initialPage' property accepts a zero-based index to determine the starting page.
```JSX
```
--------------------------------
### Configure React PDF Viewer Worker URL
Source: https://react-pdf-viewer.dev/docs/basic-usage
This snippet demonstrates how to initialize the React PDF Viewer by importing the `Worker` component and providing the `workerUrl` prop. The `workerUrl` specifies the path to the `pdf.worker.min.js` file, which is crucial for offloading PDF parsing and rendering tasks to a web worker.
```JavaScript
import { Worker } from '@react-pdf-viewer/core';
...
```
--------------------------------
### Example Usage of characterMap Prop
Source: https://react-pdf-viewer.dev/docs/options
Demonstrates how to configure and use the `characterMap` prop with the `Viewer` component to enable support for non-latin characters, specifying the character map URL and compression status.
```TypeScript
import { CharacterMap, Viewer } from '@react-pdf-viewer/core';
const characterMap: CharacterMap = {
isCompressed: true,
// The url has to end with "/"
url: 'https://unpkg.com/pdfjs-dist@2.6.347/cmaps/',
};
;
```
--------------------------------
### Import and Render React PDF Viewer Component
Source: https://react-pdf-viewer.dev/docs/basic-usage
This snippet demonstrates the fundamental steps to display a PDF document using the `@react-pdf-viewer/core` component. It shows how to import the `Viewer` component and its essential styles, then render it by providing the PDF's URL to the `fileUrl` prop. The `fileUrl` prop supports various input types, including URLs, base64 strings, and byte arrays.
```javascript
// Import the main component
import { Viewer } from '@react-pdf-viewer/core';
// Import the styles
import '@react-pdf-viewer/core/lib/styles/index.css';
// Your render function
;
```
--------------------------------
### Place React PDF Viewer Worker in App Component
Source: https://react-pdf-viewer.dev/docs/basic-usage
This example illustrates how to embed the `Worker` component directly within a higher-level React component, such as the main `App` component. Placing the `Worker` at a layout level is recommended when the PDF viewer is utilized across multiple pages or routes within the application, ensuring the worker is consistently available.
```JavaScript
const App = () => {
return ...;
};
```
--------------------------------
### Configure Worker Component with PDF.js Worker URL
Source: https://react-pdf-viewer.dev/docs/options
Example demonstrating how to use the `Worker` component from `@react-pdf-viewer/core` by providing a `workerUrl` to the PDF.js worker script, essential for the viewer's functionality.
```TypeScript
import { Worker } from '@react-pdf-viewer/core';
...;
```
--------------------------------
### React: Setting Text Direction with Dark Theme
Source: https://react-pdf-viewer.dev/docs/options
Provides an example of combining a specific theme (dark) with a right-to-left text direction within the `theme` object for the `Viewer` component.
```TypeScript
;
```
--------------------------------
### React PDF Viewer Worker Version Mismatch Error
Source: https://react-pdf-viewer.dev/docs/basic-usage
This code block illustrates a common error message that occurs when the API version of the `pdfjs` library used in the application does not match the version of the loaded web worker. Ensuring that both versions are identical is critical for the React PDF Viewer to function correctly and avoid runtime issues.
```Plain Text
The API version "3.4.120" does not match the Worker version "2.6.347"
```
--------------------------------
### React PDF Viewer Unknown Worker Action Error
Source: https://react-pdf-viewer.dev/docs/basic-usage
This snippet displays another error message indicating an 'Unknown action from worker', often a symptom of version discrepancies between `pdfjs` and its worker, or an improperly configured worker. This error points to an issue within the `pdf.js` library's internal message handling.
```Plain Text
Uncaught Error: Unknown action from worker: undefined
at Worker.MessageHandler._onComObjOnMessage (pdf.js:6846)
```
--------------------------------
### Customize Loader Renderer for React-PDF-Viewer
Source: https://react-pdf-viewer.dev/docs/options
Provides an example of customizing the loading indicator for the React-PDF-Viewer using the 'renderLoader' property. This function receives the loading 'percentages' and allows rendering a custom React element, such as a progress bar, to show document loading progress.
```JSX
import { ProgressBar } from '@react-pdf-viewer/core';
// Your render function
(
)}
/>;
```
--------------------------------
### Handle Document Password Prompt in React PDF Viewer
Source: https://react-pdf-viewer.dev/docs/options
This callback is invoked when a protected PDF document requires a password to be opened. Developers can implement custom logic within this handler to manage password submission, for example, by programmatically providing the password.
```TypeScript
import { DocumentAskPasswordEvent, Viewer } from '@react-pdf-viewer/core';
const handleAskPassword = (e: DocumentAskPasswordEvent) => {
// ...
};
;
```
--------------------------------
### Viewer Component Props API Reference
Source: https://react-pdf-viewer.dev/docs/options
Detailed API documentation for the `Viewer` component's properties. Each prop defines a specific configuration or behavior for the PDF viewer, including data sources, rendering options, and event handlers.
```APIDOC
Viewer component props:
characterMap: object - Support non-latin characters via cmap
defaultScale: number | SpecialZoomLevel - The default zoom level
fileUrl*: string | Uint8Array - The path to document
httpHeaders: object - The additional authentication headers to load the document
initialPage: number - The initial page
initialRotation: number - The initial rotation
localization: LocalizationMap - Define the localized texts
pageLayout: object - Modify the styles and size of each page
plugins: Plugin[] - Array of plugin instances
renderError: Function - The error renderer
renderLoader: Function - The loader renderer
renderPage: Function - Page renderer
renderProtectedView: Function - Customize the view of a protected document
scrollMode: ScrollMode - The initial scroll mode
theme: string | object - The theme options
transformGetDocumentParams: Function - Transform more options of pdf.js getDocument API
viewMode: ViewMode - The initial viewmode
withCredentials: boolean - Allow to load the document from protected resource
onDocumentAskPassword: Function - Invoked when a protected document requires a password to open
onDocumentLoad: Function - Invoked when document is loaded
onPageChange: Function - Invoked when users change page
onRotate: Function - Invoked when users rotate the document
onRotatePage: Function - Invoked when users rotate a single page
onSwitchTheme: Function - Invoked when users switch theme
onZoom: Function - Invoked when zooming document
```
--------------------------------
### Basic Usage of fileUrl Prop
Source: https://react-pdf-viewer.dev/docs/options
Illustrates the fundamental way to provide a document to the `Viewer` component using the `fileUrl` prop, specifying the path to the PDF file.
```TypeScript
import { Viewer } from '@react-pdf-viewer/core';
;
```
--------------------------------
### React: Setting Theme as String
Source: https://react-pdf-viewer.dev/docs/options
Shows how to apply a theme to the `Viewer` component by passing the theme name as a string directly to the `theme` prop.
```TypeScript
```
--------------------------------
### Importing the Viewer Component
Source: https://react-pdf-viewer.dev/docs/options
Imports the `Viewer` component from the `@react-pdf-viewer/core` package, which is the primary component for rendering PDF documents.
```TypeScript
import { Viewer } from '@react-pdf-viewer/core';
```
--------------------------------
### React: Setting Theme as Object
Source: https://react-pdf-viewer.dev/docs/options
Illustrates how to apply a theme to the `Viewer` component by passing an object to the `theme` prop, specifying the theme name within the object.
```TypeScript
```
--------------------------------
### Handle Document Zoom Event with onZoom Callback
Source: https://react-pdf-viewer.dev/docs/options
Shows how to use the `onZoom` callback in `@react-pdf-viewer/core` to react to document zoom events. It demonstrates importing `ZoomEvent` and `Viewer`, defining a handler that logs the new scale, and integrating it with the `Viewer` component.
```TypeScript
import { Viewer, ZoomEvent } from '@react-pdf-viewer/core';
const handleZoom = (e: ZoomEvent) => {
console.log(`Zoom to ${e.scale}`);
};
;
```
--------------------------------
### Configuring httpHeaders for Authenticated Documents
Source: https://react-pdf-viewer.dev/docs/options
Shows how to pass additional HTTP headers and credentials to the `Viewer` component when loading documents from protected resources, enabling authentication.
```TypeScript
```
--------------------------------
### Configure Initial View Mode for React PDF Viewer
Source: https://react-pdf-viewer.dev/docs/options
This section describes the available initial view modes for the React PDF Viewer component. It defines different display behaviors for PDF documents, such as single page, dual page, or dual page with a cover.
```APIDOC
ViewMode:
ViewMode.SinglePage:
Type: ViewMode
Description: The default viewmode. View single page continuously
ViewMode.DualPage:
Type: ViewMode
Description: View two pages each time
ViewMode.DualPageWithCover:
Type: ViewMode
Description: View two pages each time. The first page is displayed as a cover
```
--------------------------------
### Worker Component Props API Reference
Source: https://react-pdf-viewer.dev/docs/options
API documentation for the `Worker` component's properties, specifically `workerUrl`, detailing its type, description, and requirement status.
```APIDOC
Worker Component Props:
workerUrl*: string (The path to pdfjs' worker)
```
--------------------------------
### ZoomEvent Object API Reference
Source: https://react-pdf-viewer.dev/docs/options
API documentation for the `ZoomEvent` object, detailing its properties: `doc` and `scale`, along with their types and descriptions.
```APIDOC
ZoomEvent:
doc: PdfJs.PdfDocument (The PDF document)
scale: number (The current scale level)
```
--------------------------------
### API: theme Property Options
Source: https://react-pdf-viewer.dev/docs/options
Documents the `theme` property, allowing customization of the viewer's visual theme and text direction. It outlines available built-in themes (`auto`, `dark`, `light`) and text direction options (`LeftToRight`, `RightToLeft`).
```APIDOC
theme: string | { theme?: string; direction?: TextDirection; };
Built-in Themes:
auto (From 2.6.0): Switch to the dark or light mode automatically based on the system setting
dark (From 2.6.0): The dark theme
light (From 2.6.0): The light theme (default)
TextDirection Values:
TextDirection.LeftToToRight (From 2.8.0): Left to right (LTR) direction. It's the default value
TextDirection.RightToLeft (From 2.8.0): Right to left (RTL) direction
```
--------------------------------
### API: renderPage Function and RenderPageProps
Source: https://react-pdf-viewer.dev/docs/options
Documents the `renderPage` function, which customizes the page renderer, accepting `RenderPageProps`. It details the properties available in `RenderPageProps`, including layers, dimensions, page index, rotation, scale, and rendering status flags. It also highlights the importance of `markRendered` for sequential page rendering.
```APIDOC
renderPage: (props: RenderPageProps) => React.ReactElement;
RenderPageProps:
annotationLayer: Slot (From 1.5.0) - The annotation layer
canvasLayer: Slot (From 1.5.0) - The canvas layer
canvasLayerRendered: Boolean (From 3.1.0) - Indicate that the canvas layer is rendered completely or not
doc: PdfJs.PdfDocument (From 1.5.0) - The PDF document
height: number (From 1.5.0) - The height of page
pageIndex: number (From 1.5.0) - The page index
rotation: number (From 1.5.0) - The current number of rotation degrees
scale: number (From 1.5.0) - The current zoom level
svgLayer: Slot (From 1.5.0) - The SVG layer
textLayer: Slot (From 1.5.0) - The text layer
textLayerRendered: Boolean (From 3.1.0) - Indicate that the text layer is rendered completely or not
width: number (From 1.5.0) - The width of page
markRendered: Function (From 3.1.0) - Mark as the page rendered completely
```
--------------------------------
### API: RenderProtectedViewProps Interface
Source: https://react-pdf-viewer.dev/docs/options
Details the `RenderProtectedViewProps` interface, which provides properties for customizing the protected view. It includes `passwordStatus` to indicate the current password state and `verifyPassword` function for password validation.
```APIDOC
RenderProtectedViewProps:
passwordStatus: PasswordStatus (From 3.11.0) - The password status enum
verifyPassword: Function (From 3.11.0) - The function to verify the password
```
--------------------------------
### Handle Page Rotation Event with onRotatePage Callback
Source: https://react-pdf-viewer.dev/docs/options
Demonstrates how to use the `onRotatePage` callback in `@react-pdf-viewer/core` to respond when a user rotates a document page. It shows importing `RotatePageEvent` and `Viewer`, defining a handler, and passing it to the `Viewer` component.
```TypeScript
import { RotatePageEvent, Viewer } from '@react-pdf-viewer/core';
const handleRotatePage = (e: RotatePageEvent) => {
// ...
};
;
```
--------------------------------
### Import Worker Component for React PDF Viewer
Source: https://react-pdf-viewer.dev/docs/options
Basic import statement for the `Worker` component from `@react-pdf-viewer/core`, necessary for PDF rendering.
```TypeScript
import { Worker } from '@react-pdf-viewer/core';
```
--------------------------------
### Customize Page Layout Functions for React-PDF-Viewer
Source: https://react-pdf-viewer.dev/docs/options
Defines the TypeScript signatures for functions used to customize the styling and size of individual pages within the React-PDF-Viewer. These functions are part of the 'pageLayout' object, allowing for dynamic modification of page appearance.
```TypeScript
buildPageStyles?: ({ numPages: number; pageIndex: number }) => React.CSSProperties;
```
```TypeScript
tranformSize?: ({ numPages: number; pageIndex: number; size: Rect }) => Rect;
```
```APIDOC
Rect:
height: number
width: number
```
--------------------------------
### characterMap Prop Object Structure
Source: https://react-pdf-viewer.dev/docs/options
Defines the structure of the `characterMap` object, used to configure support for non-latin characters. It specifies the URL for character maps and whether they are compressed.
```APIDOC
characterMap object properties:
url*: string - Indicate the URL that we can load the character maps
isCompressed: boolean - Indicate the character maps are compressed or not
```
--------------------------------
### React: Customizing Protected View with renderProtectedView
Source: https://react-pdf-viewer.dev/docs/options
Demonstrates how to customize the protected view in `react-pdf-viewer` using the `renderProtectedView` prop. It shows a React functional component `ProtectedView` that accepts `RenderProtectedViewProps` and is passed to the `Viewer` component.
```TypeScript
import { RenderProtectedViewProps, Viewer } from '@react-pdf-viewer/core';
const ProtectedView: React.FC = ({ passwordStatus, verifyPassword }) => {
...
};
} />
```
--------------------------------
### Handle Document Load Event in React PDF Viewer
Source: https://react-pdf-viewer.dev/docs/options
This callback is triggered when the PDF document has been completely loaded. It provides access to document properties, such as the total number of pages, and information about the opened file, enabling post-load operations.
```TypeScript
import { DocumentLoadEvent, Viewer } from '@react-pdf-viewer/core';
const handleDocumentLoad = (e: DocumentLoadEvent) => {
console.log(`Number of pages: ${e.doc.numPages}`);
};
;
```
```APIDOC
DocumentLoadEvent:
doc:
Type: PdfJs.PdfDocument
Description: The PDF document
From: 1.7.0
file:
Type: OpenFile
Description: The current opened file
From: 2.7.2
OpenFile:
data:
Type: string or Uint8Array
Description: It is the file name or Uint8Array depending on the type of fileUrl
name:
Type: string
Description: The file name
```
--------------------------------
### Enable Cross-Site Credentials for React PDF Viewer
Source: https://react-pdf-viewer.dev/docs/options
This option indicates whether cross-site requests made by the PDF viewer should include credentials like cookies and authorization headers. The default value is `false`. For more advanced authentication, the `httpHeaders` option can be used.
```React JSX
```
--------------------------------
### RotatePageEvent Object API Reference
Source: https://react-pdf-viewer.dev/docs/options
API documentation for the `RotatePageEvent` object, detailing its properties: `direction`, `doc`, `pageIndex`, and `rotation`, along with their types and descriptions.
```APIDOC
RotatePageEvent:
direction: RotateDirection (The rotate direction)
doc: PdfJs.PdfDocument (The PDF document)
pageIndex: number (The zero-based page index)
rotation: number (The latest rotation value)
```
--------------------------------
### Handle Page Change Event in React PDF Viewer
Source: https://react-pdf-viewer.dev/docs/options
This callback is invoked whenever the user navigates to a different page within the PDF document. It provides the current page index and the PDF document object, allowing for custom actions based on page transitions.
```TypeScript
import { PageChangeEvent, Viewer } from '@react-pdf-viewer/core';
const handlePageChange = (e: PageChangeEvent) => {
// ...
};
;
```
```APIDOC
PageChangeEvent:
currentPage:
Type: number
Description: The current page (zero based) index
From: 1.7.0
doc:
Type: PdfJs.PdfDocument
Description: The PDF document
From: 1.7.0
```
--------------------------------
### Set Initial Rotation for React-PDF-Viewer
Source: https://react-pdf-viewer.dev/docs/options
Illustrates how to set the initial rotation of the PDF document displayed in the React-PDF-Viewer. The 'initialRotation' property takes a numerical value representing the rotation angle in degrees.
```JSX
```
--------------------------------
### React: Setting Text Direction
Source: https://react-pdf-viewer.dev/docs/options
Demonstrates how to set the text direction for the `Viewer` component using the `direction` property within the `theme` object, importing `TextDirection` from `@react-pdf-viewer/core`.
```TypeScript
import { TextDirection } from '@react-pdf-viewer/core';
;
```
--------------------------------
### Handle Document Rotation Event in React PDF Viewer
Source: https://react-pdf-viewer.dev/docs/options
This callback is triggered when the user rotates the document. It provides information about the rotation direction, the PDF document, and the new rotation value, enabling developers to respond to orientation changes.
```TypeScript
import { RotateEvent, Viewer } from '@react-pdf-viewer/core';
const handleRotate = (e: RotateEvent) => {
// ...
};
;
```
```APIDOC
RotateEvent:
direction:
Type: RotateDirection
Description: The rotate direction
From: 3.2.0
doc:
Type: PdfJs.PdfDocument
Description: The PDF document
From: 3.2.0
rotation:
Type: number
Description: The latest rotation value
From: 3.2.0
RotateDirection:
Backward: if users rotate counterclockwise
Forward: if users rotate clockwise
```
--------------------------------
### TypeScript: markRendered Function Signature
Source: https://react-pdf-viewer.dev/docs/options
Defines the type signature for the `markRendered` function, which is crucial for signaling the completion of page rendering in `react-pdf-viewer`. This function takes a `pageIndex` to identify the rendered page.
```TypeScript
markRendered: (pageIndex: number) => void;
```
--------------------------------
### Customize Error Renderer for React-PDF-Viewer
Source: https://react-pdf-viewer.dev/docs/options
Documents the 'LoadError' type, which is passed to the 'renderError' property for customizing how errors are displayed in the React-PDF-Viewer. It lists the properties of 'LoadError' and the possible values for the 'name' property, allowing developers to handle different error scenarios.
```APIDOC
LoadError:
message: string
name: string (one of: AbortException, FormatError, InvalidPDFException, MissingPDFException, PasswordException, UnexpectedResponseException, UnknownErrorException)
```
--------------------------------
### Transform PDF.js getDocument Parameters in React PDF Viewer
Source: https://react-pdf-viewer.dev/docs/options
This option is a function that allows transforming the parameters passed to the pdf.js `getDocument` API. It enables developers to customize document loading behavior, such as disabling range or stream requests, by merging custom options with the default ones.
```TypeScript
import { PdfJs } from '@react-pdf-viewer/core';
Object.assign({}, options, {
disableRange: false,
disableStream: false,
})
}
/>;
```
--------------------------------
### API: scrollMode Property and Enum
Source: https://react-pdf-viewer.dev/docs/options
Describes the `scrollMode` property, which sets the initial scrolling behavior for the PDF viewer. It lists the available `ScrollMode` enum values: `Vertical` (default), `Horizontal`, `Page`, and `Wrapped`, along with their descriptions.
```APIDOC
scrollMode: ScrollMode; // Initial scroll mode
ScrollMode:
ScrollMode.Vertical: The default scroll mode. Scroll the pages in the vertical direction
ScrollMode.Horizontal: Scroll the pages in the horizontal direction
ScrollMode.Page: Display a single page each time
ScrollMode.Wrapped: Scroll the pages in both vertical and horizontal directions
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.