### Install React PDF Kit with Bun
Source: https://docs.react-pdf-kit.dev/introduction/getting-started
Installs the React PDF Kit viewer package using the Bun package manager. This command adds the necessary dependency to your project's bun.lockb file and node_modules directory.
```bash
bun add @react-pdf-kit/viewer
```
--------------------------------
### Install React PDF Kit with yarn
Source: https://docs.react-pdf-kit.dev/introduction/getting-started
Installs the React PDF Kit viewer package using the yarn package manager. This command adds the dependency to your project's package.json and installs it into node_modules.
```bash
yarn add @react-pdf-kit/viewer
```
--------------------------------
### Install Canvas Dependencies for Apple M Series
Source: https://docs.react-pdf-kit.dev/introduction/getting-started
Installs necessary system dependencies (pkg-config, cairo, pango) using Homebrew for the 'canvas' package, which is required by pdfjs-dist on Apple M series chipsets.
```bash
$ brew install pkg-config cairo pango
```
--------------------------------
### Install React PDF Kit with pnpm
Source: https://docs.react-pdf-kit.dev/introduction/getting-started
Installs the React PDF Kit viewer package using the pnpm package manager. This command adds the dependency to your project's package.json and installs it into the pnpm store and project node_modules.
```bash
pnpm add @react-pdf-kit/viewer
```
--------------------------------
### Install React PDF Kit with npm
Source: https://docs.react-pdf-kit.dev/introduction/getting-started
Installs the React PDF Kit viewer package using the npm package manager. This command adds the dependency to your project's package.json and installs it into node_modules.
```bash
npm install @react-pdf-kit/viewer
```
--------------------------------
### Basic React PDF Viewer Setup (React)
Source: https://docs.react-pdf-kit.dev/components/overview
Demonstrates the recommended basic setup for rendering a PDF document with the default toolbar layout using RPConfig, RPProvider, RPLayout, and RPPages. Requires licenseKey and src props.
```jsx
import { RPConfig, RPProvider, RPLayout, RPPages } from '@react-pdf-kit/viewer'
export default () => (
)
```
--------------------------------
### Install pdfjs-dist with bun
Source: https://docs.react-pdf-kit.dev/usage-guide/overriding-dependency
Installs the pdfjs-dist package using bun. This command adds the package to your project's dependencies.
```bash
bun add pdfjs-dist
```
--------------------------------
### Configure and Render React PDF Viewer
Source: https://docs.react-pdf-kit.dev/hooks/use-element-page-context
This snippet shows the setup for a React PDF viewer using `react-pdf-kit`. It configures the license key, provides the PDF source, and integrates custom elements and layout components for displaying the PDF.
```javascript
export const AppPdfViewer: FC = () => {
return (
)
}
```
--------------------------------
### Install copy-webpack-plugin with bun
Source: https://docs.react-pdf-kit.dev/usage-guide/overriding-dependency
Installs the 'copy-webpack-plugin' as a development dependency using bun. This plugin is required for Webpack configuration.
```bash
bun add copy-webpack-plugin --dev
```
--------------------------------
### React PDF Viewer App Setup with Custom Search (React)
Source: https://docs.react-pdf-kit.dev/examples/add-custom-search-bar-on-the-top-bar
The `AppPdfViewerSearch` component sets up the main PDF viewer application. It uses `useRef` to get a reference to a DOM element, `useState` to manage the target element for the custom search component, and `useEffect` to find and prepare a DOM node for the search UI. It configures the `RPLayout` with custom toolbar options and uses `createPortal` to render the `CustomSearch` component into the designated target.
```jsx
import React, { FC, useRef, useState, useEffect } from "react";
import { createPortal } from "react-dom";
import {
RPConfig,
RPProvider,
RPLayout,
RPHorizontalBar,
RPVerticalBar,
RPPages,
} from "react-pdf-kit";
import { CustomSearch } from "./CustomSearch";
export const AppPdfViewerSearch: FC = () => {
const ref = useRef(null);
const [target, setTarget] = useState(null);
useEffect(() => {
const elemTopBarLeft = ref.current?.querySelector('[data-rp="topBarLeft"]');
if (elemTopBarLeft) {
const wrapper = document.createElement("div");
ref.current = wrapper;
elemTopBarLeft.prepend(wrapper);
setTarget(wrapper);
}
}, []);
return (
<>
>
);
};
```
--------------------------------
### Install copy-webpack-plugin with pnpm
Source: https://docs.react-pdf-kit.dev/usage-guide/overriding-dependency
Installs the 'copy-webpack-plugin' as a development dependency using pnpm. This plugin is needed for Webpack setup.
```bash
pnpm install copy-webpack-plugin -D
```
--------------------------------
### Minimal React PDF Viewer Setup (React)
Source: https://docs.react-pdf-kit.dev/components/overview
Provides a minimal setup for basic PDF rendering without the toolbar and sidebar. It uses RPConfig, RPProvider, and RPPages, requiring a container with defined height and width for proper rendering. Requires licenseKey and src props.
```jsx
import { RPConfig, RPProvider, RPPages } from '@react-pdf-kit/viewer'
export default () => (
{/* Ensure the container has height and width for proper PDF rendering */}
)
```
--------------------------------
### Clear Bun Cache and Reinstall Dependencies
Source: https://docs.react-pdf-kit.dev/introduction/getting-started
Commands to clear the Bun cache and reinstall project dependencies. This is often used to resolve installation issues or when overriding package versions, particularly for pdfjs-dist.
```bash
bun pm cache rm
rm bun.lockb
rm -R node_modules
bun i
```
--------------------------------
### React PDF Viewer Setup with RPProvider
Source: https://docs.react-pdf-kit.dev/examples/jump-to-next-bbox-highlight-area-programmatically
Initializes the React PDF Kit viewer with a PDF source and defines the layout, including a top toolbar and a left sidebar. The `RPProvider` component wraps the entire viewer, making its context available to child components.
```jsx
const AppPdfViewer = () => {
return (
<>
} }}
leftSidebar={{ component: }}
>
>
);
};
export default AppPdfViewer;
```
--------------------------------
### Install copy-webpack-plugin with yarn
Source: https://docs.react-pdf-kit.dev/usage-guide/overriding-dependency
Installs the 'copy-webpack-plugin' as a development dependency using yarn. This is necessary for Webpack configuration.
```bash
yarn add copy-webpack-plugin -D
```
--------------------------------
### Install pdfjs-dist with pnpm
Source: https://docs.react-pdf-kit.dev/usage-guide/overriding-dependency
Installs the pdfjs-dist package using pnpm. This command adds the package to your project's dependencies.
```bash
pnpm add pdfjs-dist
```
--------------------------------
### React PDF Viewer Setup and Text Selection Handling
Source: https://docs.react-pdf-kit.dev/examples/add-custom-action-text-selection
This snippet sets up the main App component, initializes the PDF viewer using RPProvider, and implements text selection logic. It captures mouse up events on the viewer to detect selected text, calculates the position for a dropdown menu relative to the viewer, and manages the visibility of this menu. Dependencies include React hooks and the @react-pdf-kit/viewer library.
```javascript
import { Chat } from "./Chat";
import { useCallback, useEffect, useState } from "react";
import { SelectDropDown } from "./SelectDropDown";
import {
RPConfig,
RPProvider,
RPLayout,
RPPages,
} from "@react-pdf-kit/viewer";
const App = () => {
const [pdfViewer, setPdfViewer] = useState();
const [selectedText, setSelectedText] = useState();
const [menuPosition, setMenuPosition] = useState<{ x: number; y: number }>({
x: 0,
y: 0,
});
const [showDropdown, setShowDropdown] = useState(false);
const [context, setContext] = useState();
const handleMouseUp = useCallback(() => {
const selection = window.getSelection(); // Get current selection
// If there is no selection or no range, hide the dropdown and exit
if (!selection || selection.rangeCount === 0) {
setShowDropdown(false);
return;
}
const selectedString = selection?.toString(); // Convert to string
const selectedRange = selection?.getRangeAt(0); // Get the range object
// Set selected text so we can use it later
setSelectedText(selectedString);
// If the selection is empty or only whitespace, hide dropdown
if (!selectedString || selectedString.trim().length === 0) {
setShowDropdown(false);
return;
}
// A selection can span multiple lines.
// getClientRects() returns a DOMRect for each visual line of the selection.
const rects = selectedRange.getClientRects();
if (rects.length === 0) return;
// Use the LAST rectangle so the dropdown appears
// at the end of the selected text (not the beginning)
const lastRect = rects[rects.length - 1];
// Get the bounding rectangle of the PDF viewer container.
// This allows us to convert from viewport coordinates
// to container-relative coordinates.
const containerRect = pdfViewer?.getBoundingClientRect();
if (containerRect) {
// Position the dropdown relative to the PDF container
// right edge + bottom edge of the selected text
setMenuPosition({
x: lastRect.right - containerRect.left,
y: lastRect.bottom - containerRect.top,
});
setShowDropdown(true);
} else {
setShowDropdown(false);
}
}, []);
const handleAsk = useCallback(() => {
setContext(selectedText);
setShowDropdown(false);
}, [selectedText]);
const handleCopy = useCallback(() => {
if (selectedText) {
window.navigator.clipboard.writeText(selectedText);
}
setShowDropdown(false);
}, [selectedText]);
useEffect(() => {
pdfViewer?.addEventListener("mouseup", handleMouseUp);
return () => {
pdfViewer?.removeEventListener("mouseup", handleMouseUp);
};
}, [handleMouseUp, pdfViewer]);
return (
<>
setContext(undefined)}
/>
>
);
};
export default App;
```
--------------------------------
### Basic PDF Viewer Setup with React PDF Kit - React
Source: https://docs.react-pdf-kit.dev/examples/jump-to-next-bbox-highlight-area-programmatically
Sets up a basic PDF viewer using React PDF Kit's `RPProvider` and `RPLayout`. It configures a horizontal toolbar and a custom left sidebar component (`MyLeftSidebar`) to display the PDF content.
```jsx
const AppPdfViewer: FC = () => {
return (
<>
},
leftSidebar: { component: },
}}
>
>
);
};
export default AppPdfViewer;
```
--------------------------------
### Install pdfjs-dist with npm
Source: https://docs.react-pdf-kit.dev/usage-guide/overriding-dependency
Installs the pdfjs-dist package using npm. This is the first step in overriding the default version required by React PDF Kit.
```bash
npm install pdfjs-dist --save
```
--------------------------------
### Install pdfjs-dist with yarn
Source: https://docs.react-pdf-kit.dev/usage-guide/overriding-dependency
Installs the pdfjs-dist package using yarn. This command is used to add the package to your project dependencies.
```bash
yarn add pdfjs-dist
```
--------------------------------
### Full React PDF Viewer with Top Bar Button (JSX)
Source: https://docs.react-pdf-kit.dev/usage-guide/viewer-element-usage
This complete JSX example integrates the creation of a button element, its prepending to the top bar's right section, and its cleanup using React hooks (`useRef`, `useCallback`, `useMemo`). It sets up the `RPLayout` with a ref and event handlers for `onLoaded` and `cleanupOnLoaded`.
--------------------------------
### Basic RPButton with Icon (React)
Source: https://docs.react-pdf-kit.dev/components/rp-button
Demonstrates the basic usage of the RPButton component with an SVG icon. This example shows how to import and render a simple icon button.
```javascript
import { RPButton } from '@react-pdf-kit/viewer'
export const MyComponent = () => {
return (
console.log('Button clicked')}>
)
}
```
--------------------------------
### Setup Hyperlink Detection with useEffect (JSX/TSX)
Source: https://docs.react-pdf-kit.dev/usage-guide/viewer-element-usage
This snippet demonstrates how to use the `useEffect` hook in React to set up and tear down an event listener for detecting clicks on hyperlinks within the PDF viewer. It calls a `setupHyperlinkDetection` function and ensures proper cleanup by returning its result from the effect.
```jsx
useEffect(() => {
const cleanup = setupHyperlinkDetection()
return typeof cleanup === 'function' ? cleanup : undefined
}, [setupHyperlinkDetection])
```
```tsx
useEffect(() => {
return setupHyperlinkDetection()
}, [setupHyperlinkDetection])
```
--------------------------------
### Install copy-webpack-plugin with npm
Source: https://docs.react-pdf-kit.dev/usage-guide/overriding-dependency
Installs the 'copy-webpack-plugin' as a development dependency using npm. This plugin is required for configuring Webpack to handle the PDF worker file.
```bash
npm install copy-webpack-plugin --save-dev
```
--------------------------------
### Basic Usage of React PDF Kit Hooks
Source: https://docs.react-pdf-kit.dev/hooks/overview
Demonstrates how to use common React PDF Kit hooks such as usePaginationContext and useFullScreenContext within a custom React component. This example requires the component to be a child of RPProvider and assumes the necessary imports from '@react-pdf-kit/viewer'. It showcases accessing pagination details, controlling page navigation, and toggling fullscreen mode.
```jsx
import type { FC } from 'react'
import {
RPConfig,
RPProvider,
RPPages,
usePaginationContext,
useFullScreenContext,
RPLayout
} from '@react-pdf-kit/viewer'
const CustomPdfViewer: FC = () => {
const { focusedPage, totalPages, nextPage, prevPage } = usePaginationContext()
const { isFullScreen, toggleFullScreen } = useFullScreenContext()
return (
<>
Page {focusedPage} of {totalPages}
>
)
}
const AppPdfViewer = () => {
return (
)
}
export default AppPdfViewer
```
--------------------------------
### Full React PDF Viewer with Top Bar Button (TSX)
Source: https://docs.react-pdf-kit.dev/usage-guide/viewer-element-usage
This complete TSX example integrates the creation of a button element, its prepending to the top bar's right section, and its cleanup using React hooks (`useRef`, `useCallback`, `useMemo`). It sets up the `RPLayout` with a ref and event handlers for `onLoaded` and `cleanupOnLoaded`, including type annotations for the ref.
--------------------------------
### Example Usage of LazyAppPdfViewer in Next.js Page
Source: https://docs.react-pdf-kit.dev/introduction/basic-usage
Demonstrates how to import and use the `LazyAppPdfViewer` component within a Next.js page. It shows how to pass a PDF source URL to the component.
```jsx
import LazyAppPdfViewer from './components/LazyAppPdfViewer'
export default function Page() {
const pdfSrc = 'https://cdn.codetoweb.com/image/upload/v1721763853/guides/web-roadmap.pdf';
return
}
```
--------------------------------
### Vite Configuration for PDF Worker
Source: https://docs.react-pdf-kit.dev/usage-guide/overriding-dependency
Configures Vite's 'optimizeDeps.include' to ensure 'pdfjs-dist' is pre-bundled. This is a necessary step for using 'pdfjs-dist' with Vite.
```javascript
import { defineConfig } from 'vite'
export default defineConfig({
// ...config
optimizeDeps: {
include: ['pdfjs-dist']
// ...
}
})
```
--------------------------------
### Implement Single Page Rotation with React PDF Kit (TSX)
Source: https://docs.react-pdf-kit.dev/hooks/use-page-rotate-context
This TypeScript example demonstrates page rotation using React PDF Kit's context hooks. It's functionally equivalent to the JSX version but uses TypeScript syntax. Ensure RPProvider is used to provide the necessary context for hooks like usePageRotateContext.
```tsx
import { useCallback, useEffect, FC } from 'react'
import {
RPConfig,
RPProvider,
RPLayout,
RPPages,
usePageRotateContext,
usePaginationContext,
useElementPageContext
} from '@react-pdf-kit/viewer'
const CounterClockwiseIcon = () => {
return (
)
}
const SinglePageRotate: FC = () => {
const { rotate } = usePageRotateContext()
const { totalPages } = usePaginationContext()
const { updateElement, clearElements } = useElementPageContext()
const handleRotate = useCallback(
(page: number, direction: 'clockwise' | 'counterclockwise') => {
switch (direction) {
case 'clockwise':
rotate(page, (prev) => (prev + 90) % 360)
break
case 'counterclockwise':
rotate(page, (prev) => (prev - 90 + 360) % 360)
break
}
},
[rotate]
)
useEffect(() => {
Array.from({ length: totalPages }).forEach((_, index) => {
updateElement(index + 1, () => {
return [
handleRotate(index + 1, 'clockwise')}
>
handleRotate(index + 1, 'counterclockwise')}
>
]
})
})
return () => {
Array.from({ length: totalPages }).forEach((_, index) => {
clearElements(index + 1)
})
}
}, [clearElements, updateElement, handleRotate, totalPages])
return null
}
export const AppPdfViewer: FC = () => {
return (
)
}
```
--------------------------------
### Custom Theme React PDF Viewer Setup (React)
Source: https://docs.react-pdf-kit.dev/components/overview
Shows how to customize the appearance of the React PDF viewer while maintaining the default layout. It utilizes RPTheme with customVariables to override CSS properties like toolbar background and text color. Requires licenseKey and src props.
```jsx
import { RPConfig, RPTheme, RPProvider, RPLayout, RPPages } from '@react-pdf-kit/viewer'
export default () => (
)
```
--------------------------------
### Initialize State for Dropdown and Link in JSX
Source: https://docs.react-pdf-kit.dev/usage-guide/viewer-element-usage
Initializes state variables to manage the visibility and position of a custom dropdown menu and to store the hyperlink's href. This is a basic setup for managing UI state in a React component.
```jsx
const [dropdown, setDropdown] = useState(null)
```
--------------------------------
### Toggle RPButton with Active State (React)
Source: https://docs.react-pdf-kit.dev/components/rp-button
Shows how to implement a toggle button using the `active` prop of RPButton. This example uses React's `useState` hook to manage the active state and visually indicate it.
```javascript
import { useState } from 'react'
import { RPButton } from '@react-pdf-kit/viewer'
export const ToggleButton = () => {
const [isActive, setIsActive] = useState(false)
return (
setIsActive(!isActive)}>
)
}
```
--------------------------------
### Implement Single Page Rotation with React PDF Kit (JSX)
Source: https://docs.react-pdf-kit.dev/hooks/use-page-rotate-context
This example shows how to create a SinglePageRotate component using the usePageRotateContext hook to handle page rotation. It requires RPProvider as a parent component and utilizes hooks like usePaginationContext and useElementPageContext for managing page elements and total pages. The component adds rotation controls to each page.
```jsx
import { useCallback, useEffect } from 'react'
import {
RPConfig,
RPProvider,
RPLayout,
RPPages,
usePageRotateContext,
usePaginationContext,
useElementPageContext
} from '@react-pdf-kit/viewer'
const CounterClockwiseIcon = () => {
return (
)
}
const SinglePageRotate = () => {
const { rotate } = usePageRotateContext()
const { totalPages } = usePaginationContext()
const { updateElement, clearElements } = useElementPageContext()
const handleRotate = useCallback(
(page, direction) => {
switch (direction) {
case 'clockwise':
rotate(page, (prev) => (prev + 90) % 360)
break
case 'counterclockwise':
rotate(page, (prev) => (prev - 90 + 360) % 360)
break
}
},
[rotate]
)
useEffect(() => {
Array.from({ length: totalPages }).forEach((_, index) => {
updateElement(index + 1, () => {
return [
handleRotate(index + 1, 'clockwise')}
>
handleRotate(index + 1, 'counterclockwise')}
>
]
})
})
return () => {
Array.from({ length: totalPages }).forEach((_, index) => {
clearElements(index + 1)
})
}
}, [clearElements, updateElement, handleRotate, totalPages])
return null
}
export const AppPdfViewer = () => {
return (
)
}
```
--------------------------------
### Customize Download Tool in RPHorizontalBar with Custom Component
Source: https://docs.react-pdf-kit.dev/components/rp-horizontal-bar
Illustrates how to replace the default file download button in RPHorizontalBar with a custom React component. This example adds a confirmation dialog before initiating the download, providing a more controlled user experience.
```jsx
(
{
// Show a confirm alert before downloading
if (confirm('confirm download')) {
download()
}
}}
>
Download File
)
}}
/>
)
}}
}}
>
```
--------------------------------
### Configure Custom Horizontal Toolbar in React PDF Viewer (JSX)
Source: https://docs.react-pdf-kit.dev/examples/customize-a-search-popover
This example demonstrates how to configure the custom horizontal toolbar component within the React PDF Viewer using JSX. It utilizes `RPConfig`, `RPProvider`, and `RPLayout` components. The `CustomHorizontalBar` is passed as the `component` for the `topbar` within the `toolbar` configuration.
```jsx
import {
RPLayout,
RPPages,
RPProvider,
RPVerticalBar,
RPConfig,
} from "@react-pdf-kit/viewer";
import { CustomHorizontalBar } from "./CustomHorizontalBar";
const App = () => {
return (
},
leftSidebar: { component: },
}}
>
);
};
export default App
```
--------------------------------
### Set Initial Search Keyword in React PDF Viewer (TSX)
Source: https://docs.react-pdf-kit.dev/examples/set-an-initial-keyword-search
This TypeScript example demonstrates setting the `initialSearch` prop on the RPProvider component to automatically find and highlight a keyword ('TraceMonkey') upon PDF loading. It utilizes the `@react-pdf-kit/viewer` library and necessitates a license key for operation.
```tsx
import {
RPConfig,
RPProvider,
RPLayout,
RPPages,
} from "@react-pdf-kit/viewer";
import React, { type FC } from "react";
export const AppPdfViewer : FC = () => {
return (
<>
Initial search
>
);
};
```
--------------------------------
### Custom Download Tool in React PDF Viewer
Source: https://docs.react-pdf-kit.dev/components/rp-default-layout
To use a custom file download component in React PDF, define `downloadTool` as a function component in the `slots`. This example adds a confirmation flow before initiating the download process, providing a more controlled user experience.
```javascript
import { RPProvider, RPDefaultLayout, RPPages, RPConfig } from '@react-pdf-kit/viewer'
export const AppPdfViewer = () => {
return (
(
{
// Show a confirm alert before downloading
if (confirm('confirm download')) {
download()
}
}}
>
Download File
)
}}
>
)
}
```
--------------------------------
### React: PDF Viewer with Hyperlink Detection
Source: https://docs.react-pdf-kit.dev/usage-guide/viewer-element-usage
A React component that integrates with React-PDF-Kit to display a PDF document and enables custom handling of hyperlink clicks. It uses `useRef` to get a reference to the viewer container and `useState` to manage the state of a custom dropdown menu. `useEffect` is used to set up and clean up the event listener for hyperlink detection.
```typescript
import React, { useRef, useState, useCallback, useEffect } from "react";
import { Provider as RPProvider, Layout as RPLayout, Pages as RPPages } from "react-pdf-kit";
import HyperlinkDropdown from "./HyperlinkDropdown"; // Assuming HyperlinkDropdown is in the same directory
interface DropdownPosition {
href: string;
x: number;
y: number;
}
const AppPdfViewer: React.FC = () => {
// Reference to the viewer container
const containerRef = useRef(null);
// State for the hyperlink dropdown
const [dropdown, setDropdown] = useState(null);
const closeDropdown = useCallback(() => setDropdown(null), []);
const setupHyperlinkDetection = useCallback((): (() => void) | undefined => {
const root = containerRef.current;
if (!root) return;
const onRootClick = (e: MouseEvent) => {
const target = e.target as HTMLElement | null;
if (!target) return;
// Check if the clicked element is a hyperlink inside PDF layers
const anchor = target.closest("a[href]");
if (!anchor || !root.contains(anchor)) return;
const layer = anchor.closest(
'[data-rp*="textLayer"], [data-rp*="annotationLayer"]'
);
if (!layer) return;
// Exclusion: skip when href is empty
const hrefAttr = anchor.getAttribute("href") || "";
if (hrefAttr === "") {
return;
}
// Prevent default link behavior and show custom dropdown
e.preventDefault();
e.stopPropagation();
const rect = anchor.getBoundingClientRect();
setDropdown({
href: anchor.href,
x: rect.left + window.scrollX,
y: rect.bottom + window.scrollY + 5,
});
};
// Capture clicks inside the viewer
root.addEventListener("click", onRootClick, true);
return () => {
root.removeEventListener("click", onRootClick, true);
};
}, []);
useEffect(() => {
return setupHyperlinkDetection();
}, [setupHyperlinkDetection]);
return (
{/* PDF Viewer */}
{/* Custom dropdown menu when clicking a hyperlink */}
{dropdown && (
)}
);
};
export default AppPdfViewer;
```
--------------------------------
### Configure RPLayout Dimensions and Toolbar - React
Source: https://docs.react-pdf-kit.dev/components/rp-layout
This React code snippet demonstrates how to configure the dimensions (height and width) and enable the default toolbar for the RPLayout component. It utilizes RPConfig, RPProvider, RPLayout, and RPPages from '@react-pdf-kit/viewer'. The example overrides default dimensions and ensures the toolbar is visible.
```javascript
import {
RPConfig,
RPProvider,
RPLayout,
RPPages,
} from "@react-pdf-kit/viewer";
// Example of a parent component
const ParentComponent = ({ children }) => {
return
{children}
;
};
const AppPdfViewer = () => {
return (
);
};
export default AppPdfViewer;
```
--------------------------------
### Override pdfjs-dist version in package.json (npm/bun/pnpm)
Source: https://docs.react-pdf-kit.dev/usage-guide/overriding-dependency
Specifies an override for the 'pdfjs-dist' version in your package.json file. This ensures that the specific installed version is used by your project.
```json
{
"overrides": {
"pdfjs-dist": "the installed version"
}
}
```
--------------------------------
### Configure Webpack for PDF.js in Next.js (v14)
Source: https://docs.react-pdf-kit.dev/usage-guide/overriding-dependency
This configuration is for Next.js v14 using Webpack. It modifies the webpack configuration to correctly resolve the pdfjs-dist module. This is a workaround for compatibility issues with `@react-pdf-kit/viewer@^2.0.0` and Next.js v14. Ensure Step 1 of pdfjs-dist installation is completed.
```javascript
const path = require('path')
/** @type {import('next').NextConfig} */
const nextConfig = {
// Config options here
webpack: (config, { webpack }) => {
config.plugins.push(
new webpack.NormalModuleReplacementPlugin(/^pdfjs-dist$/, (resource) => {
resource.request = path.join(__dirname, './node_modules/pdfjs-dist/webpack')
})
)
return config
}
}
module.exports = nextConfig;
```
```typescript
import { NextConfig } from "next";
import path from 'path';
const nextConfig: NextConfig = {
/* config options here */
webpack: (config, { webpack }) => {
config.plugins.push(
new webpack.NormalModuleReplacementPlugin(/^pdfjs-dist$/, (resource: any) => {
resource.request = path.join(__dirname, './node_modules/pdfjs-dist/webpack')
})
)
return config
}
};
export default nextConfig;
```
--------------------------------
### Configure PDF Worker URL in Next.js (v15+) with Turbopack
Source: https://docs.react-pdf-kit.dev/usage-guide/overriding-dependency
This snippet shows how to configure the PDF worker URL for React PDF Kit in Next.js v15 and later using Turbopack. It involves adding the worker URL to the RPConfig component's workerUrl prop. Ensure Step 1 of pdfjs-dist installation is completed prior to this.
```jsx
import { RPConfig } from '@react-pdf-kit/viewer'
import React from 'react'
const workerSrc = new URL(
"pdfjs-dist/build/pdf.worker.min.mjs",
import.meta.url,
).toString();
function AppProviders({ children, ...props }) {
return (
{children}
)
}
export default AppProviders
```
```tsx
import { RPConfig, RPConfigProps } from '@react-pdf-kit/viewer'
import React from 'react'
import { type PropsWithChildren } from 'react'
const workerSrc = new URL(
"pdfjs-dist/build/pdf.worker.min.mjs",
import.meta.url,
).toString();
function AppProviders({ children, ...props }: PropsWithChildren>) {
return (
{children}
)
}
export default AppProviders
```
--------------------------------
### Configure and Render PDF Viewer with Highlights (React/TypeScript)
Source: https://docs.react-pdf-kit.dev/examples/highlight-with-bbox-coordinates-programmatically
The `AppPdfViewer` component sets up the React PDF Kit environment, including configuration, provider, and layout. It integrates the `BboxHighlightLayer` to display highlights on the PDF document. This component requires a license key and a source URL for the PDF file.
```typescript
import React, { FC } from "react";
import { RPConfig, RPProvider, RPLayout, RPPages } from "@react-pdf-kit/core";
import BboxHighlightLayer from "./BboxHighlightLayer"; // Assuming BboxHighlightLayer is in the same directory
export const AppPdfViewer: FC = () => {
return (
<>
>
);
};
export default AppPdfViewer;
```