### Run Example App Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/CLAUDE.md Starts the example application locally using Vite. Ensure you are in the example/ directory. ```bash npm run dev # or npm start ``` -------------------------------- ### Install react-pdf-highlighter-plus Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/README.md Install the library using npm. ```bash npm install react-pdf-highlighter-plus ``` -------------------------------- ### Basic PDF Highlighter Setup Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/README.md Set up a basic PDF highlighter component with document loading and highlight display. This example demonstrates how to load a PDF and render highlights, enabling area selection with the Alt key. ```tsx import { PdfLoader, PdfHighlighter, TextHighlight, AreaHighlight, useHighlightContainerContext, } from "react-pdf-highlighter-plus"; import "react-pdf-highlighter-plus/style/style.css"; function App() { const [highlights, setHighlights] = useState([]); return ( {(pdfDocument) => ( e.altKey} > )} ); } function HighlightContainer() { const { highlight, isScrolledTo } = useHighlightContainerContext(); return highlight.type === "text" ? ( ) : ( ); } ``` -------------------------------- ### Complete Example with Image and Signature Highlighting Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/docs/image-signature-highlights.md This example demonstrates a full React component setup for react-pdf-highlighter-plus, including functionality to add custom images and signatures as highlights. It manages state for highlights, image mode, and signature pad visibility. The component utilizes PdfLoader, PdfHighlighter, and custom components like HighlightContainer to render different highlight types. ```tsx import React, { useState, useRef } from "react"; import { PdfHighlighter, PdfHighlighterUtils, PdfLoader, ImageHighlight, SignaturePad, TextHighlight, AreaHighlight, useHighlightContainerContext, usePdfHighlighterContext, ScaledPosition, Highlight, } from "react-pdf-highlighter-plus"; const App = () => { const [highlights, setHighlights] = useState([]); const [imageMode, setImageMode] = useState(false); const [isSignaturePadOpen, setIsSignaturePadOpen] = useState(false); const [pendingImageData, setPendingImageData] = useState(null); const fileInputRef = useRef(null); const highlighterUtilsRef = useRef(); const handleImageClick = (position: ScaledPosition) => { if (pendingImageData) { const newHighlight: Highlight = { id: String(Math.random()).slice(2), type: "image", position, content: { image: pendingImageData }, }; setHighlights([newHighlight, ...highlights]); setPendingImageData(null); setImageMode(false); } }; const handleAddImage = () => { fileInputRef.current?.click(); }; const handleFileSelect = (event: React.ChangeEvent) => { const file = event.target.files?.[0]; if (file) { const reader = new FileReader(); reader.onload = (e) => { setPendingImageData(e.target?.result as string); setImageMode(true); }; reader.readAsDataURL(file); } event.target.value = ""; }; const handleAddSignature = () => { setIsSignaturePadOpen(true); }; const handleSignatureComplete = (dataUrl: string) => { setPendingImageData(dataUrl); setIsSignaturePadOpen(false); setImageMode(true); }; const editHighlight = (id: string, edit: Partial) => { setHighlights( highlights.map((h) => (h.id === id ? { ...h, ...edit } : h)) ); }; return (
{(pdfDocument) => ( (highlighterUtilsRef.current = utils)} enableImageCreation={() => imageMode} onImageClick={handleImageClick} > )} setIsSignaturePadOpen(false)} />
); }; // Highlight Container Component const HighlightContainer = ({ editHighlight, }: { editHighlight: (id: string, edit: Partial) => void; }) => { const { highlight, viewportToScaled, isScrolledTo, highlightBindings, } = useHighlightContainerContext(); const { toggleEditInProgress } = usePdfHighlighterContext(); if (highlight.type === "image") { return ( { editHighlight(highlight.id, { position: { boundingRect: viewportToScaled(boundingRect), rects: [], }, }); }} onEditStart={() => toggleEditInProgress(true)} onEditEnd={() => toggleEditInProgress(false)} /> ); } if (highlight.type === "text") { return ; } // Area highlight (default) return ( ); }; export default App; ``` -------------------------------- ### Build Library Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/CLAUDE.md Executes the full build pipeline for the library, including cleaning, dependency installation, TypeScript compilation, style copying, example app build, and documentation generation. ```bash npm run build ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/README.md Clone the project repository using Git, navigate into the project directory, and install all necessary npm dependencies to prepare for local development. ```bash git clone https://github.com/QuocVietHa08/react-pdf-highlighter-plus.git cd react-pdf-highlighter-plus npm install ``` -------------------------------- ### Individual Build Steps Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/CLAUDE.md Provides commands for executing specific steps of the build process, such as TypeScript compilation, style copying, example app building, documentation generation, or cleaning build artifacts. ```bash npm run build:esm # TypeScript compilation only npm run build:copy-styles # Copy CSS files to dist npm run build:example # Build example app with Vite npm run build:docs # Generate TypeDoc documentation npm run clean # Remove all build artifacts ``` -------------------------------- ### Run Development Server Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/README.md Start the development server for the react-pdf-highlighter-plus project using the `npm run dev` command. This command is typically used for local development and testing. ```bash npm run dev ``` -------------------------------- ### Complete React PDF Highlighter Example with Style Panel Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/docs/freetext-highlights.md This comprehensive example integrates PdfHighlighter, PdfLoader, and custom highlight components. It allows for adding freetext notes with customizable styles and editing existing highlights. Ensure you have the necessary components imported and a PDF document available at the specified URL. ```tsx import React, { useState, useRef } from "react"; import { PdfHighlighter, PdfHighlighterUtils, PdfLoader, FreetextHighlight, TextHighlight, AreaHighlight, useHighlightContainerContext, usePdfHighlighterContext, ScaledPosition, Highlight, } from "react-pdf-highlighter-plus"; // Style configuration interface FreetextStyle { color: string; backgroundColor: string; fontFamily: string; fontSize: string; } interface MyHighlight extends Highlight { comment?: string; freetextStyle?: FreetextStyle; } const App = () => { const [highlights, setHighlights] = useState([]); const [freetextMode, setFreetextMode] = useState(false); const [freetextStyle, setFreetextStyle] = useState({ color: "#333333", backgroundColor: "#ffffc8", fontFamily: "inherit", fontSize: "14px", }); const highlighterUtilsRef = useRef(); const handleFreetextClick = (position: ScaledPosition) => { const newHighlight: MyHighlight = { id: String(Math.random()).slice(2), type: "freetext", position, content: { text: "New note" }, freetextStyle: { ...freetextStyle }, }; setHighlights([newHighlight, ...highlights]); }; const editHighlight = (id: string, edit: Partial) => { setHighlights( highlights.map((h) => (h.id === id ? { ...h, ...edit } : h)) ); }; return (
{(pdfDocument) => ( (highlighterUtilsRef.current = utils)} enableFreetextCreation={() => freetextMode} onFreetextClick={handleFreetextClick} > )}
); }; // Highlight Container Component const HighlightContainer = ({ editHighlight, freetextStyle, }: { editHighlight: (id: string, edit: Partial) => void; freetextStyle: FreetextStyle; }) => { const { highlight, viewportToScaled, screenshot, isScrolledTo, highlightBindings, } = useHighlightContainerContext(); const { toggleEditInProgress } = usePdfHighlighterContext(); if (highlight.type === "freetext") { return ( { editHighlight(highlight.id, { position: { boundingRect: viewportToScaled(boundingRect), rects: [], }, }); toggleEditInProgress(false); }} onTextChange={(newText) => { editHighlight(highlight.id, { content: { text: newText }, }); }} onEditStart={() => toggleEditInProgress(true)} onEditEnd={() => toggleEditInProgress(false)} color={highlight.freetextStyle?.color ?? freetextStyle.color} backgroundColor={highlight.freetextStyle?.backgroundColor ?? freetextStyle.backgroundColor} fontFamily={highlight.freetextStyle?.fontFamily ?? freetextStyle.fontFamily} fontSize={highlight.freetextStyle?.fontSize ?? freetextStyle.fontSize} /> ); } if (highlight.type === "text") { return ; } // Area highlight return ( { editHighlight(highlight.id, { position: { boundingRect: viewportToScaled(boundingRect), rects: [], }, content: { image: screenshot(boundingRect) }, }); toggleEditInProgress(false); }} bounds={highlightBindings.textLayer} onEditStart={() => toggleEditInProgress(true)} /> ); }; export default App; ``` -------------------------------- ### Dynamic Theme Toggle Example Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/docs/api-reference.md Illustrates how to dynamically toggle between light and dark themes based on component state. ```tsx // Dynamic theme toggle const [darkMode, setDarkMode] = useState(false); ``` -------------------------------- ### FreetextHighlight Usage Example Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/docs/api-reference.md Example of how to use the FreetextHighlight component, including handling position, text, and style changes. Ensure highlight data and update functions are correctly passed. ```tsx updatePosition(highlight.id, rect)} onTextChange={(text) => updateText(highlight.id, text)} onStyleChange={(style) => updateStyle(highlight.id, style)} color={highlight.color} backgroundColor={highlight.backgroundColor} fontSize={highlight.fontSize} /> ``` -------------------------------- ### Quick Start: Export PDF and Download Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/docs/pdf-export.md Initiates the PDF export process and handles the download of the generated annotated PDF file. Ensure you have the `exportPdf` function imported. ```tsx import { exportPdf } from "react-pdf-highlighter-plus"; const handleExport = async () => { const pdfBytes = await exportPdf(pdfUrl, highlights); // Download the file const blob = new Blob([pdfBytes], { type: "application/pdf" }); const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = "annotated.pdf"; a.click(); URL.revokeObjectURL(url); }; ``` -------------------------------- ### Complete Theming Implementation Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/docs/theming.md Demonstrates a full React component setup for toggling dark mode using local storage and applying a custom theme to PdfHighlighter. Use this as a base for integrating theming into your application. ```tsx import { useState, useEffect } from "react"; import { PdfLoader, PdfHighlighter } from "react-pdf-highlighter-plus"; function App() { const [darkMode, setDarkMode] = useState(() => { // Load preference from localStorage return localStorage.getItem("pdfDarkMode") === "true"; }); useEffect(() => { localStorage.setItem("pdfDarkMode", String(darkMode)); }, [darkMode]); return (
{(pdfDocument) => ( )}
); } ``` -------------------------------- ### Complete PDF Annotation and Export Example Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/docs/pdf-export.md This snippet shows a full React component that loads a PDF, allows for highlighting, and exports the annotated PDF with customizable options and progress feedback. It utilizes PdfLoader, PdfHighlighter, and exportPdf from the library. ```tsx import React, { useState, useRef } from "react"; import { PdfHighlighter, PdfLoader, exportPdf, Highlight, } from "react-pdf-highlighter-plus"; const App = () => { const [highlights, setHighlights] = useState([]); const [isExporting, setIsExporting] = useState(false); const [exportProgress, setExportProgress] = useState({ current: 0, total: 0 }); const pdfUrl = "https://example.com/document.pdf"; const handleExport = async () => { setIsExporting(true); try { const pdfBytes = await exportPdf(pdfUrl, highlights, { textHighlightColor: "rgba(255, 226, 143, 0.5)", areaHighlightColor: "rgba(255, 226, 143, 0.5)", defaultFreetextColor: "#333333", defaultFreetextBgColor: "#ffffc8", defaultFreetextFontSize: 14, onProgress: (current, total) => { setExportProgress({ current, total }); }, }); // Download the file const blob = new Blob([pdfBytes], { type: "application/pdf" }); const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = "annotated-document.pdf"; a.click(); URL.revokeObjectURL(url); } catch (error) { console.error("Export failed:", error); } finally { setIsExporting(false); } }; return (
{(pdfDocument) => ( {/* Your highlight container */} )}
); }; export default App; ``` -------------------------------- ### Complete Drawing Example with React PDF Highlighter Plus Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/docs/drawing-highlights.md This snippet shows a full React component that integrates PdfHighlighter to allow users to draw on a PDF. It includes toolbar controls for enabling drawing mode, selecting stroke color, and adjusting stroke width. The drawing completion is handled by adding new drawing highlights to the state. ```tsx import React, { useState, useRef } from "react"; import { PdfHighlighter, PdfHighlighterUtils, PdfLoader, DrawingHighlight, TextHighlight, AreaHighlight, useHighlightContainerContext, usePdfHighlighterContext, ScaledPosition, Highlight, } from "react-pdf-highlighter-plus"; const App = () => { const [highlights, setHighlights] = useState([]); const [drawingMode, setDrawingMode] = useState(false); const [strokeColor, setStrokeColor] = useState("#ff0000"); const [strokeWidth, setStrokeWidth] = useState(2); const highlighterUtilsRef = useRef(); const handleDrawingComplete = ( dataUrl: string, position: ScaledPosition, strokes: DrawingStroke[], ) => { const newHighlight: Highlight = { id: String(Math.random()).slice(2), type: "drawing", position, content: { image: dataUrl, strokes }, }; setHighlights([newHighlight, ...highlights]); setDrawingMode(false); }; const editHighlight = (id: string, edit: Partial) => { setHighlights( highlights.map((h) => (h.id === id ? { ...h, ...edit } : h)) ); }; return (
{/* Toolbar */}
{drawingMode && ( <> )}
{(pdfDocument) => ( (highlighterUtilsRef.current = utils)} enableDrawingMode={drawingMode} onDrawingComplete={handleDrawingComplete} drawingStrokeColor={strokeColor} drawingStrokeWidth={strokeWidth} > )}
); }; // Highlight Container Component const HighlightContainer = ({ editHighlight, }: { editHighlight: (id: string, edit: Partial) => void; }) => { const { highlight, viewportToScaled, isScrolledTo, highlightBindings, } = useHighlightContainerContext(); const { toggleEditInProgress } = usePdfHighlighterContext(); if (highlight.type === "drawing") { return ( { editHighlight(highlight.id, { position: { boundingRect: viewportToScaled(boundingRect), rects: [], }, }); }} onEditStart={() => toggleEditInProgress(true)} onEditEnd={() => toggleEditInProgress(false)} /> ); } if (highlight.type === "text") { return ; } // Area highlight (default) return ( ); }; export default App; ``` -------------------------------- ### Custom Highlight Styling via Props Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/README.md Apply custom styles to `TextHighlight` components by passing a `style` prop. This example demonstrates dynamically setting the background color based on a highlight's category. ```tsx // Via props ``` -------------------------------- ### Import Styles Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/README.md Import the default styles for the highlighter. ```tsx import "react-pdf-highlighter-plus/style/style.css"; ``` -------------------------------- ### Integrate Signature Pad Component Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/docs/image-signature-highlights.md Shows how to integrate the `SignaturePad` component to allow users to draw signatures. It manages the signature pad's visibility and handles the completion of a signature by setting pending image data and enabling image mode. ```tsx import { SignaturePad } from "react-pdf-highlighter-plus"; const [isSignaturePadOpen, setIsSignaturePadOpen] = useState(false); const handleAddSignature = () => { setIsSignaturePadOpen(true); }; const handleSignatureComplete = (dataUrl: string) => { setPendingImageData(dataUrl); setIsSignaturePadOpen(false); setImageMode(true); }; // In JSX: setIsSignaturePadOpen(false)} /> ``` -------------------------------- ### Get Precise Text Position Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/docs/api-reference.md Locates a specific piece of text within a PDF document and returns its precise position, including bounding rectangles per line. It supports exact and fuzzy matching, ignoring whitespace and line-wraps. ```tsx import { getTextPosition } from "react-pdf-highlighter-plus"; const match = await getTextPosition(pdfDocument, "the quote to locate"); // match: { position: ScaledPosition; pageNumber: number; // matchedText: string; confidence: "exact" | "fuzzy" } | null if (match) { const highlight = { id: "cite-1", type: "text", content: { text: match.matchedText }, position: match.position, }; setHighlights((prev) => [highlight, ...prev]); utils.scrollToHighlight(highlight); // smooth scroll + flash } ``` -------------------------------- ### Image and Signature Highlight Components Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/README.md Integrate ImageHighlight and SignaturePad components for uploading images or drawing signatures. The ImageHighlight can be managed for editing, and the SignaturePad provides a modal for drawing. ```tsx import { ImageHighlight, SignaturePad } from "react-pdf-highlighter-plus"; // Signature pad modal setPendingImage(dataUrl)} onClose={() => setIsOpen(false)} /> // In your highlight container: toggleEditInProgress(true)} onEditEnd={() => toggleEditInProgress(false)} /> ``` -------------------------------- ### Locate Text Position with getTextPosition Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/README.md Use `getTextPosition` to find a specific text string within a PDF document and get its precise position for highlighting. Matching ignores whitespace and line breaks, falling back to fuzzy matching. ```tsx import { getTextPosition } from "react-pdf-highlighter-plus"; const match = await getTextPosition(pdfDocument, "the exact or near-exact quote"); if (match) { const citation = { id: "cite-1", type: "text", content: { text: match.matchedText }, position: match.position, // precise rects, page-independent }; setHighlights((prev) => [citation, ...prev]); utils.scrollToHighlight(citation); // smooth scroll + flash } // match: { position, pageNumber, matchedText, confidence: "exact" | "fuzzy" } ``` -------------------------------- ### Display Highlight Tips and Popups Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/README.md Use `MonitoredHighlightContainer` to manage highlight tips and popups. The `highlightTip` prop accepts an object with `position` and `content`, where `content` can be a React component to render the popup. ```tsx import { MonitoredHighlightContainer } from "react-pdf-highlighter-plus"; , }}> ``` -------------------------------- ### Render ImageHighlight Component Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/docs/image-signature-highlights.md Demonstrates how to render an `ImageHighlight` component within a custom highlight container. It handles the display of image highlights and updates their position when they are resized or repositioned. ```tsx import { ImageHighlight, useHighlightContainerContext } from "react-pdf-highlighter-plus"; const HighlightContainer = ({ editHighlight }) => { const { highlight, viewportToScaled, isScrolledTo, highlightBindings } = useHighlightContainerContext(); const { toggleEditInProgress } = usePdfHighlighterContext(); if (highlight.type === "image") { return ( { editHighlight(highlight.id, { position: { boundingRect: viewportToScaled(boundingRect), rects: [], }, }); }} onEditStart={() => toggleEditInProgress(true)} onEditEnd={() => toggleEditInProgress(false)} /> ); } // ... handle other highlight types }; ``` -------------------------------- ### Render FreetextHighlight in Compact Mode Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/docs/freetext-highlights.md Use the `compact` prop to render freetext notes as small markers until they are opened. The `compactSize` prop controls the size of these markers. ```tsx ``` -------------------------------- ### Handle Image Placement Logic Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/docs/image-signature-highlights.md Manages the placement of a new image highlight after an image has been selected and the user clicks on the PDF. It creates a new highlight object with the image data and resets the pending image state. ```tsx const [imageMode, setImageMode] = useState(false); const [pendingImageData, setPendingImageData] = useState(null); const handleImageClick = (position: ScaledPosition) => { if (pendingImageData) { const newHighlight: Highlight = { id: generateId(), type: "image", position, content: { image: pendingImageData }, }; setHighlights([newHighlight, ...highlights]); setPendingImageData(null); setImageMode(false); } }; ``` -------------------------------- ### SignaturePad Props Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/docs/image-signature-highlights.md Props for the SignaturePad component, used for capturing user signatures. ```APIDOC ## SignaturePad Props ### Description Props for the SignaturePad component, used for capturing user signatures. ### Props - **isOpen** (boolean) - Required - Whether the signature pad modal is visible - **onComplete** ((dataUrl: string) => void) - Required - Called with PNG data URL when user clicks "Done" - **onClose** (() => void) - Required - Called when user cancels or closes the modal - **width** (number) - Optional - Canvas width in pixels (default: 400) - **height** (number) - Optional - Canvas height in pixels (default: 200) ``` -------------------------------- ### Store Per-Highlight Styling Preferences Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/docs/freetext-highlights.md Store style preferences for each highlight by defining a custom interface that extends Highlight and includes style properties. These can then be passed as props. ```typescript interface MyHighlight extends Highlight { freetextStyle?: { color?: string; backgroundColor?: string; fontFamily?: string; fontSize?: string; }; } ``` ```tsx // In your container: ``` -------------------------------- ### Import TextHighlight Component Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/docs/api-reference.md Import the TextHighlight component from the library. This component is used to render selected PDF text as highlight rectangles. ```tsx import { TextHighlight } from "react-pdf-highlighter-plus"; ``` -------------------------------- ### Import FreetextHighlight Component Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/docs/api-reference.md Import the FreetextHighlight component from the library. This component provides a draggable, editable text annotation. ```tsx import { FreetextHighlight } from "react-pdf-highlighter-plus"; ``` -------------------------------- ### Configure PdfLoader Props Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/README.md Understand the props for PdfLoader, including disableAutoFetch for on-demand page fetching and httpHeaders for authentication. ```tsx {(pdfDocument) => } ``` -------------------------------- ### Enable Image Mode in PdfHighlighter Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/docs/image-signature-highlights.md Configure PdfHighlighter to enable image creation mode and handle image clicks for placement. The `enableImageCreation` prop should return true when image mode is active. ```tsx imageMode} // Return true when image mode is active onImageClick={handleImageClick} // Handle click to place image highlights={highlights} > ``` -------------------------------- ### Freehand Drawing Highlight Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/README.md Enable freehand drawing mode and display DrawingHighlight components. Drawings are stored as PNGs and can be customized with stroke color and width. ```tsx import { DrawingHighlight } from "react-pdf-highlighter-plus"; { addHighlight({ type: "drawing", position, content: { image: dataUrl } }); }} drawingStrokeColor="#ff0000" drawingStrokeWidth={2} > // In your highlight container: ``` -------------------------------- ### Define Custom Highlight Interface Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/README.md Extend the base `Highlight` interface to include custom properties like `category`, `comment`, and `author`. Use the generic type parameter of `useHighlightContainerContext` to specify your custom interface. ```tsx interface MyHighlight extends Highlight { category: string; comment?: string; author?: string; } // Use the generic type const { highlight } = useHighlightContainerContext(); ``` -------------------------------- ### Default Light Theme Configuration Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/docs/api-reference.md Provides the default theme configuration for the light mode of the PdfHighlighter component. ```typescript { mode: "light", containerBackgroundColor: "#e5e5e5", scrollbarThumbColor: "#9f9f9f", scrollbarTrackColor: "#d1d1d1", } ``` -------------------------------- ### DrawingHighlight Component Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/docs/api-reference.md A component for rendering and interacting with freehand drawing highlights. It allows for dragging, resizing, and custom event handling. ```APIDOC ## DrawingHighlight Component ### Description A draggable, resizable freehand drawing component. ### Props - `highlight` (ViewportHighlight) - Required - The highlight data (must have `content.image`) - `onChange` ((rect: LTWHP) => void) - Called when position/size changes - `isScrolledTo` (boolean) - Optional - Whether highlight was auto-scrolled to. Defaults to `false`. - `bounds` (string | Element) - Optional - Bounds for dragging - `onContextMenu` ((event: MouseEvent) => void) - Optional - Right-click handler - `onEditStart` (() => void) - Optional - Called when drag/resize begins - `onEditEnd` (() => void) - Optional - Called when drag/resize ends - `style` (CSSProperties) - Optional - Custom container styling - `dragIcon` (ReactNode) - Optional - Custom drag handle icon. Defaults to a 6-dot grid. ### Example ```jsx updatePosition(highlight.id, rect)} onEditStart={() => toggleEditInProgress(true)} onEditEnd={() => toggleEditInProgress(false)} /> ``` ``` -------------------------------- ### ExportableHighlight Interface Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/docs/api-reference.md Defines the structure for highlights that can be exported. It includes color and font properties for styling. ```typescript interface ExportableHighlight { id: string; type?: HighlightType; content?: { text?: string; image?: string; }; position: ScaledPosition; highlightColor?: string; // For text/area color?: string; // For freetext backgroundColor?: string; // For freetext fontSize?: string; // For freetext fontFamily?: string; // For freetext } ``` -------------------------------- ### ImageHighlight Component Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/docs/api-reference.md A component for rendering and interacting with image-based highlights. It supports dragging, resizing, and custom event handlers for editing and deletion. ```APIDOC ## ImageHighlight Component ### Description A draggable, resizable image annotation component. ### Props - `highlight` (ViewportHighlight) - Required - The highlight data (must have `content.image`) - `onChange` ((rect: LTWHP) => void) - Called when position/size changes - `isScrolledTo` (boolean) - Optional - Whether highlight was auto-scrolled to. Defaults to `false`. - `bounds` (string | Element) - Optional - Bounds for dragging - `onContextMenu` ((event: MouseEvent) => void) - Optional - Right-click handler - `onEditStart` (() => void) - Optional - Called when drag/resize begins - `onEditEnd` (() => void) - Optional - Called when drag/resize ends - `style` (CSSProperties) - Optional - Custom container styling - `dragIcon` (ReactNode) - Optional - Custom drag handle icon. Defaults to a 6-dot grid. - `onStyleChange` ((image: string, strokes: DrawingStroke[]) => void) - Optional - Called after editing drawing color/width - `onDelete` (() => void) - Optional - Called when delete is clicked ### Example ```jsx updatePosition(highlight.id, rect)} onEditStart={() => toggleEditInProgress(true)} onEditEnd={() => toggleEditInProgress(false)} /> ``` ``` -------------------------------- ### Basic Dark Mode Configuration Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/docs/theming.md Configure dark mode by providing background and foreground colors for the recolor ramp. This preserves hue and chroma for colored text and accents. ```tsx ``` -------------------------------- ### SignaturePad Component Usage Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/docs/api-reference.md Implement SignaturePad to allow users to draw signatures within a modal. It requires callbacks for completion and closing, and allows customization of canvas dimensions. ```tsx import { SignaturePad } from "react-pdf-highlighter-plus"; // ... { setPendingImage(dataUrl); setImageMode(true); setIsOpen(false); }} onClose={() => setIsOpen(false)} width={400} height={200} /> ``` -------------------------------- ### Enable Drawing Mode Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/docs/drawing-highlights.md Set the `enableDrawingMode` prop to true to activate drawing functionality. Configure stroke color and width using `drawingStrokeColor` and `drawingStrokeWidth`. Pass your existing highlights to the `highlights` prop. ```tsx ``` -------------------------------- ### Freehand Drawing Configuration Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/docs/pdf-export.md Embed freehand drawings as highlights by providing their base64 encoded PNG image content. These drawings have transparent backgrounds. ```tsx const highlight = { type: "drawing", content: { image: "data:image/png;base64,..." }, position: { ... }, }; ``` -------------------------------- ### Basic Dark Mode Usage Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/docs/api-reference.md Demonstrates how to apply a simple dark mode theme to the PdfHighlighter component. ```tsx ``` -------------------------------- ### Toggle Between Themes Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/docs/theming.md You can dynamically toggle between light and dark themes by managing a state variable. This allows users to switch themes based on their preference. A button can be used to trigger the state change. ```tsx const [darkMode, setDarkMode] = useState(false); ``` -------------------------------- ### Freetext Note Configuration Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/docs/pdf-export.md Configure freetext highlights with custom content, color, background color, and font size. Supports text wrapping and proportional scaling. ```tsx const highlight = { type: "freetext", content: { text: "This is a note with long text that will wrap automatically to fit within the box boundaries." }, color: "#333333", backgroundColor: "#ffffc8", fontSize: "14px", position: { ... }, }; ``` -------------------------------- ### sentenceToHighlight Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/docs/api-reference.md Converts a positioned sentence into a standard text highlight object, which can be used for rendering highlights or further processing in AI workflows. ```APIDOC ## sentenceToHighlight ### Description Converts a positioned sentence into a standard text highlight. ### Usage ```tsx import { extractSentences, sentenceToHighlight, } from "react-pdf-highlighter-plus"; const sentences = await extractSentences(pdfDocument); const highlights = sentences .filter((sentence) => sentence.position) .map((sentence) => sentenceToHighlight(sentence)); ``` ### AI Workflow Example For AI workflows, keep model calls in your app layer: ```tsx const sentences = await extractSentences(pdfDocument); const aiInput = sentences.map(({ id, text }) => ({ id, text })); const aiResults = await analyzeSentences(aiInput); // Assume analyzeSentences is your AI model call const highlights = sentences .filter((sentence) => aiResults[sentence.id]?.important) .map((sentence) => sentenceToHighlight(sentence)); ``` ``` -------------------------------- ### Enable Freetext Creation in PdfHighlighter Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/docs/freetext-highlights.md Configure `PdfHighlighter` to enable freetext annotation creation. The `enableFreetextCreation` prop should return a boolean indicating if freetext mode is active, and `onFreetextClick` handles the creation of new annotations. ```tsx freetextMode} // Return true when freetext mode is active onFreetextClick={handleFreetextClick} // Handle click to create annotation highlights={highlights} > ``` -------------------------------- ### SignaturePad Component Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/docs/api-reference.md A modal component that allows users to draw their signature. It provides callbacks for completion and closing the modal. ```APIDOC ## SignaturePad Component ### Description A modal component for drawing signatures. ### Props - `isOpen` (boolean) - Required - Whether the modal is visible - `onComplete` ((dataUrl: string) => void) - Required - Called with PNG data URL when done - `onClose` (() => void) - Required - Called when modal is closed - `width` (number) - Optional - Canvas width in pixels. Defaults to `400`. - `height` (number) - Optional - Canvas height in pixels. Defaults to `200`. ### Example ```jsx { setPendingImage(dataUrl); setImageMode(true); setIsOpen(false); }} onClose={() => setIsOpen(false)} width={400} height={200} /> ``` ``` -------------------------------- ### Export PDF with Drawings Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/docs/drawing-highlights.md Demonstrates how to export a PDF with highlights, including drawings, using the exportPdf function. Drawings are automatically included in the exported PDF. ```tsx import { exportPdf } from "react-pdf-highlighter-plus"; const pdfBytes = await exportPdf(pdfUrl, highlights); // Drawings are automatically included ``` -------------------------------- ### Create Shape Annotations Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/README.md Use the PdfHighlighter component to enable shape creation. The onShapeComplete callback receives the position and shape type, allowing you to add the shape as a highlight. Configure stroke color and width directly on the component. ```tsx { addHighlight({ type: "shape", position, content: { shape } }); }} shapeStrokeColor="#000000" shapeStrokeWidth={2} > ``` -------------------------------- ### Freetext Highlight Creation and Display Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/README.md Enable freetext note creation and display freetext highlights with customizable properties. The highlight container can manage changes to position, text, and style. ```tsx import { FreetextHighlight } from "react-pdf-highlighter-plus"; freetextMode} onFreetextClick={(position) => { addHighlight({ type: "freetext", position, content: { text: "Note" } }); }} > // In your highlight container: ``` -------------------------------- ### PdfHighlighter Props: Freetext Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/docs/api-reference.md Enables and handles user interaction for creating free text annotations within the PDF viewer. ```APIDOC ### Freetext-related | Prop | Type | Description | |------|------|-------------| | `enableFreetextCreation` | `(event: MouseEvent) => boolean` | Returns true when freetext mode is active | | `onFreetextClick` | `(position: ScaledPosition) => void` | Called when user clicks to create freetext | ``` -------------------------------- ### Custom Dark Palette Configuration Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/docs/api-reference.md Shows how to customize the dark mode color palette, including background, foreground, and container background colors. ```tsx ``` -------------------------------- ### Customize Color Presets Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/docs/freetext-highlights.md Customize the background and text color preset buttons using the backgroundColorPresets and textColorPresets props. These accept arrays of color strings. ```tsx editHighlight(highlight.id, style)} /> ``` -------------------------------- ### Enable Area Selection Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/README.md Configure the PdfHighlighter to enable area selection when the Alt key is pressed. ```tsx event.altKey} // ... > ``` -------------------------------- ### Export PDF from URL Source: https://github.com/quocvietha08/react-pdf-highlighter-plus/blob/main/docs/pdf-export.md Use this snippet to export a PDF with highlights directly from a URL. Ensure the URL points to a valid PDF document. ```tsx const pdfBytes = await exportPdf( "https://example.com/document.pdf", highlights ); ```