);
};
// 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
);
```