
Syncfusion React Pdf Viewer
- 1 installs
- 1 repo stars
- Updated July 6, 2026
- syncfusion/pdf-viewer-sdk-skills
Generates React TSX and HTML code to embed and configure the Syncfusion PdfViewerComponent for loading and interacting with PDF documents.
About
Generates React code that embeds the Syncfusion PdfViewerComponent from @syncfusion/ej2-react-pdfviewer to render PDFs. A developer uses it when adding a configured PDF viewer to a React application.
- Targets the @syncfusion/ej2-react-pdfviewer package
- Generates copy-pasteable TSX and HTML from reference files
Syncfusion React Pdf Viewer by the numbers
- 1 all-time installs (skills.sh)
- Ranked #1,914 of 2,245 Frontend Development skills by installs in the Skillselion catalog
- Data as of Jul 8, 2026 (Skillselion catalog sync)
npx skills add https://github.com/syncfusion/pdf-viewer-sdk-skills --skill syncfusion-react-pdf-viewerAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 1 |
|---|---|
| repo stars | ★ 1 |
| Last updated | July 6, 2026 |
| Repository | syncfusion/pdf-viewer-sdk-skills ↗ |
What it does
Generates React TSX and HTML code to embed and configure the Syncfusion PdfViewerComponent for loading and interacting with PDF documents.
Files
Syncfusion React Pdfviewer – UI Sample Generator
Target package: @syncfusion/ej2-react-pdfviewer
Generate Code for the User's Project (default)
Trigger keywords: "how to", "add pdfviewer", "code sample", "show me", "example", "snippet", "integrate", "component", "create sample", "react sample".
Purpose: Generate minimal, copy-pasteable TS and HTML code that the user can integrate directly into their React project.
Workflow: ⚠️ CRITICAL — Feature Support Policy (STRICT MODE):
FUNDAMENTAL RULE: Only generate code using APIs and properties that are EXPLICITLY listed in the reference files. ANY deviation is a VIOLATION.
- MANDATORY CHECKS BEFORE GENERATING ANY CODE:
1. Search the reference files for the exact API/property name 2. Verify it appears in the Method Reference, Properties, or Events tables 3. If NOT found in ANY reference file, STOP immediately 4. Do NOT generate or suggest undocumented APIs under any circumstances
- STRICT ENFORCEMENT - ZERO TOLERANCE:
- NO custom properties - Only use properties from reference file tables
- NO invented methods - Only use methods from reference file tables
- NO workarounds with undefined APIs - Forbidden
- NO assumptions about undocumented behavior - Forbidden
- NO alternative implementations using guess-work - Forbidden
- NO pretending support exists - Forbidden
- MANDATORY RESPONSE FOR UNSUPPORTED FEATURES:
- If a requested scenario/feature/API is NOT listed in any reference file, you MUST respond with:
"This feature is not supported in the current Syncfusion React PDF Viewer implementation."- Then list what IS supported from the appropriate reference file
- Never suggest alternatives unless explicitly documented in reference files
- REFERENCE FILE HIERARCHY:
- Each reference file contains complete, authoritative documentation for its domain
- The tables (Method Reference, Properties, Events) are the SOURCE OF TRUTH
- Content outside these tables in reference files is explanatory only
- Do NOT extend beyond what appears in the reference file tables
- AUDIT YOUR GENERATION:
- Before providing any code, verify EVERY API used appears in a reference file table
- Document which reference file each API comes from
- If you cannot cite a reference file table entry, DELETE that code
- This is a CRITICAL REQUIREMENT. Violations compromise the skill's integrity and reliability.
Step 1 — Detect the Application Type (REQUIRED - DO NOT SKIP)
- Use file_search and read_file tools to inspect workspace project files:
package.json(project configuration and dependencies)tsconfig.json(TypeScript configuration)App.tsxorApp.jsx(root component)vite.config.tsorwebpack.config.js(build configuration)- Any existing
.tsxor.jsxfiles in src/ folder - Output: Confirm the detected application type is a React TypeScript or JavaScript project before proceeding.
Step 2 — Generate Code from Reference Files Only (REQUIRED)
- Before generating: Confirm that Steps 1 are complete
- Read the relevant
references/*.mdfile(s) for the requested feature - Cross-reference EVERY API, property, and method against these tables
- COMPONENT-BASED APPROACH (MANDATORY - REACT PATTERNS ONLY):
- Use JSX/TSX syntax for React component composition
- Configure all PDF Viewer properties directly as component props
- Use React hooks (useState, useRef, useEffect) when programmatic access is needed
- MANDATORY: Before generating ANY code, verify that reference files exist and are accessible
- Read the appropriate reference file(s) for the requested feature:
- Use
read_filetool on relevantreferences/*.mdfiles - Confirm file contains Methods/Properties/Events tables
- Verify tables are complete and readable
- If reference file is missing or cannot be read:
- STOP code generation
- Respond: "Reference file for this feature is not available. Please ensure all reference files are present in the
references/directory." - List the missing reference file name
- This is a BLOCKER step: Cannot proceed without reference file validation
- If an API/property does NOT appear in the reference file table, DO NOT USE IT
- Do NOT invent, guess, or suggest any API, method, property, class, or namespace not explicitly present in the reference files
---
Reference File Routing Guide
All templates and operation snippets live in references/*.md. Each file is a focused snippet or template the agent will combine when generating samples.
Flow: Always start with getting-started.md, then merge matched features into its anchors (PROPS, EVENTS, UI_BUTTONS, HANDLERS). If no keyword matches, return only the basic sample.
Checklist Before Generating Code
- [ ] Count the settings properties: 1-3? → Use inline | 4+? → Use constant
- [ ] Are enums involved? Yes → Must use typed constant with imports | No → Can use inline
- [ ] Is it reused elsewhere? Yes → Use constant | No → Prefer inline
- [ ] Do I need type safety? Yes → Import
type { SettingsModel }| No → Skip type import - [ ] Do I need enums? Yes → Import required enums | No → Skip enum imports
- [ ] Is the component prop simple enough? Yes → Keep inline | No → Extract to constant
🎯 Core Setup & Configuration
| File | Purpose | Route When User Asks About |
|---|---|---|
| getting-started.md | Minimal PDFViewer with documentPath, height, and width. Base template for all samples. | "basic setup", "minimal example", "getting started", "how to load PDF" |
| general-properties.md | Configure core viewer properties (server URL, document path, locale, resource base path). | "configuration", "server settings", "locale", "document path setup" |
| enable-properties.md | Enable/disable specific features (toolbar, annotations, forms, navigation, text selection, download, print). | "disable toolbar", "hide features", "enable/disable", "read-only mode", "restrict features" |
📐 Navigation() & Page Management
| File | Purpose | Route When User Asks About |
|---|---|---|
| page-navigation.md | Navigate between pages (first, last, next, previous page), go to specific page numbers. | "page navigation", "go to page", "next page", "previous page", "jump to page" |
| bookmark-navigation.md | Navigate using PDF bookmarks/table of contents in the bookmark panel. *CRITICAL: All bookmark methods MUST be accessed via `viewerRef.current.bookmark. (e.g., viewerRef.current.bookmark.openBookmarkPane()), NOT directly on viewerRef.current`** | "bookmarks", "bookmark", "table of contents", "TOC navigation", "outline panel", "get bookmarks", "retrieve bookmarks", "fetch bookmarks", "bookmarks programmatically", "getBookmarks", "goToBookmark", "bookmark API", "list bookmarks", "open bookmark", "close bookmark" |
| hyperlink-navigation.md | Configure hyperlink navigation behavior and external link handling in PDFs. | "hyperlinks", "external links", "URL navigation", "clickable links", "url", "link" |
| thumbnail-navigation.md | Display and navigate using page thumbnails in the thumbnail panel. | "thumbnails", "preview pages", "thumbnail panel", "thumbnail","page previews" |
🔍 Viewing & Interaction
| File | Purpose | Route When User Asks About |
|---|---|---|
| magnification.md | Configure zoom levels, zoom modes, and magnification controls (fit-to-page, fit-to-width). | "zoom", "magnification", "fit to page", "zoom levels", "scale document" |
| interaction-mode.md | Switch between Selection mode (text selection) and Panning mode (touch scrolling). | "text selection", "panning", "scroll mode", "interaction mode", "touch navigation" |
| text-selection.md | Enable text selection, copying text, and text selection events. | "select text", "copy text", "highlight text to copy", "text selection mode" |
| text-search.md | Implement text search functionality with search options and navigation. | "search text", "find in PDF", "search functionality", "highlight search results" |
🛠️ Toolbar & Context Menu
Toolbar Configuration
| File | Purpose | Route When User Asks About |
|---|---|---|
| toolbar-settings.md | Configure toolbar visibility, tooltip behavior, and customize/remove toolbar items. | "customize toolbar", "hide toolbar items", "remove toolbar buttons", "toolbar configuration" |
| toolbar-methods.md | Programmatically show/hide toolbars and enable/disable toolbar items at runtime. | "show/hide toolbar dynamically", "toggle toolbar", "enable/disable toolbar items programmatically" |
⚠️ STRICT VALIDATION FOR TOOLBAR ITEM NAMES
When generating toolbar configurations, you MUST follow these rules to prevent incorrect toolbar item names:
1. ALWAYS reference exact item names from `toolbar-settings.md`
- Do NOT invent, guess, or assume toolbar item names
- Do NOT apply naming pattern logic to derive names
- Use ONLY names listed in the "Available Primary Toolbar Items", "Available Annotation Toolbar Items", and "Available Form Designer Items" sections in
toolbar-settings.md
2. VALIDATE item names character-by-character
- Case sensitivity matters:
HighlightTool≠HighlightOption - Exact names only:
AnnotationEditTool≠AnotatetionEditTool - No abbreviations or shortcuts
3. Before generating toolbar configuration code:
- [ ] Open
toolbar-settings.mdreference file - [ ] Locate: "Available Primary Toolbar Items" section
- [ ] Locate: "Available Annotation Toolbar Items" section
- [ ] Locate: "Available Form Designer Items" section
- [ ] Copy exact names from THESE SECTIONS ONLY
- [ ] Cross-check every single item name character-by-character
- [ ] If ANY item name is not in the reference sections, DO NOT USE IT
- [ ] Consult the "❌ COMMON MISTAKES TO AVOID" table in
toolbar-settings.mdif unsure
4. Common errors to prevent:
- ❌
AnotatetionEditTool→ ✅AnnotationEditTool(typo) - ❌
CalibrationOption→ ✅CalibrateTool(wrong suffix) - ❌
ShapeAnnotationOption→ ✅ShapeTool(annotation toolbar version) - ❌
InkAnnotationOption→ ✅InkAnnotationTool(annotation toolbar version) - For complete list of mistakes to avoid, see
toolbar-settings.md"❌ COMMON MISTAKES TO AVOID" table
Context Menu Customization
| File | Purpose | Route When User Asks About |
|---|---|---|
| contextmenu.md | Customize context menu items and handle context menu events. | "right-click menu", "context menu", "custom context menu", "disable context menu items" |
📝 Annotations
| File | Purpose | Route When User Asks About |
|---|---|---|
| annotation-settings.md | Configure annotation appearance (colors, opacity, styles) and behavior for all annotation types. | "annotation colors", "annotation styles", "customize annotation appearance", "annotation defaults" |
| annotation-events.md | Handle annotation lifecycle events (add, delete, move, resize, select, property change). | "annotation events", "when annotation is added", "annotation change detection", "annotation callbacks" |
| shape-label-settings.md | Customize shape and measure annotation labels (position, color, font, visibility). | "annotation labels", "shape labels", "measurement labels", "label customization" |
| redaction-annotation.md | Create, configure, and apply redaction annotations to permanently remove sensitive content. | "redaction", "redact content", "remove sensitive data", "black out text", "permanent removal" |
📄 Forms
| File | Purpose | Route When User Asks About |
|---|---|---|
| form-field-settings.md | Configure default properties for form fields (text, checkbox, radio, dropdown, signature). | "form field defaults", "form field styles", "configure form fields", "form field properties" |
| form-field-events.md | Handle form field interaction events (focus, blur, value change, validation). | "form field events", "when field changes", "form validation events", "field interaction callbacks" |
📋 Document Actions
| File | Purpose | Route When User Asks About |
|---|---|---|
| download.md | Enable/configure PDF download functionality with custom filenames. | "download PDF", "save PDF", "export document", "download button" |
| print.md | Configure and trigger PDF printing functionality. | "print PDF", "print document", "printing options", "print button" |
| organize-pages.md | Reorder, rotate, insert, remove, copy, import, and extract PDF pages. | "reorder pages", "rotate pages", "add blank pages", "remove pages", "rearrange pages", "merge PDFs" |
⚙️ Advanced Features
| File | Purpose | Route When User Asks About |
|---|---|---|
| api-methods.md | Programmatic control: load documents, manage forms, annotations, extract text, undo/redo, navigation APIs. | "load PDF programmatically", "API methods", "export form data", "extract text", "undo/redo", "programmatic control" |
| events.md | Complete list of all PDFViewer events (document load, download, annotations, forms, search, navigation). | "event list", "all events", "available events", "event reference", "event handlers" |
Quick Start Example
import * as ReactDOM from 'react-dom/client';
import * as React from 'react';
import './index.css';
import {
PdfViewerComponent, Toolbar, Magnification, Navigation, LinkAnnotation,
BookmarkView, ThumbnailView, Print, TextSelection, Annotation, TextSearch,
FormFields, FormDesigner, Inject
} from '@syncfusion/ej2-react-pdfviewer';
function App() {
return (
<div>
<div className='control-section'>
<PdfViewerComponent
id="container"
documentPath="https://cdn.syncfusion.com/content/pdf/pdf-succinctly.pdf"
style={{ 'height': '640px' }}>
<Inject services={[
Toolbar, Magnification, Navigation, Annotation, LinkAnnotation,
BookmarkView, ThumbnailView, Print, TextSelection, TextSearch,
FormFields, FormDesigner
]} />
</PdfViewerComponent>
</div>
</div>
);
}
const root = ReactDOM.createRoot(document.getElementById('sample'));
root.render(<App />);⚙️ SETTINGS CONFIGURATION BEST PRACTICES
When generating code with settings (toolbarSettings, annotationSettings, annotationSelectorSettings, arrowSettings, rectangleSettings, etc.), follow these guidelines to prevent unnecessary imports and over-engineering:
Rule 1: Simple Settings → Define INLINE in Component Props
Use this approach when:
- Configuring only 1-3 properties
- Settings are straightforward without complex enums or custom types
- No need for TypeScript typed constants
Example (DO THIS):
<PdfViewerComponent
id="container"
documentPath="https://cdn.syncfusion.com/content/pdf/pdf-succinctly.pdf"
annotationSelectorSettings={{
selectionBorderColor: '#0000ff',
selectionBorderThickness: 2,
resizerBorderColor: '#ff0000',
resizerFillColor: '#4070ff',
resizerSize: 8,
}}
style={{ height: '640px' }}
>
<Inject services={[Annotation]} />
</PdfViewerComponent>Benefits:
- ✅ No extra imports needed
- ✅ Simple and readable
- ✅ Less code clutter
- ✅ Type checking still works
---
Rule 2: Complex Settings → Define as Typed Constant (OUTSIDE component)
Use this approach when:
- Configuring 4+ properties OR multiple related settings
- Using enums or complex configurations
- Need to reuse the same configuration across multiple components
- Settings are complex enough to warrant separate definition
Example (DO THIS ONLY FOR COMPLEX CASES):
import { PdfViewerComponent, Inject, Annotation } from '@syncfusion/ej2-react-pdfviewer';
import type { AnnotationSelectorSettingsModel } from '@syncfusion/ej2-react-pdfviewer';
import { AnnotationResizerLocation, CursorType } from '@syncfusion/ej2-react-pdfviewer';
// Define constant OUTSIDE component with proper types and enums
const annotationSelectorConfig: AnnotationSelectorSettingsModel = {
selectionBorderColor: '#0000ff',
selectionBorderThickness: 2,
resizerBorderColor: '#ff0000',
resizerFillColor: '#4070ff',
resizerSize: 8,
resizerShape: 'Square',
selectorLineDashArray: [5, 6],
resizerLocation: AnnotationResizerLocation.Corners | AnnotationResizerLocation.Edges,
resizerCursorType: CursorType.grab,
};
export function App() {
return (
<PdfViewerComponent
id="container"
documentPath="https://cdn.syncfusion.com/content/pdf/pdf-succinctly.pdf"
annotationSelectorSettings={annotationSelectorConfig}
style={{ height: '640px' }}
>
<Inject services={[Annotation]} />
</PdfViewerComponent>
);
}When to import types and enums:
- [ ] Import
type { SettingsNameModel }for TypeScript type checking - [ ] Import any enums that are used in the settings (e.g.,
AnnotationResizerLocation,CursorType) - [ ] Keep imports minimal - import ONLY what is used in the settings
Benefits:
- ✅ Type-safe configuration
- ✅ Proper enum usage
- ✅ Reusable across multiple components
- ✅ Clean component code
---
Rule 3: NEVER Over-Engineer Simple Cases
❌ DO NOT DO THIS (Over-engineered):
import { PdfViewerComponent, Inject, Annotation } from '@syncfusion/ej2-react-pdfviewer';
import type { ToolbarSettingsModel } from '@syncfusion/ej2-react-pdfviewer';
// Unnecessary constant for 2 simple properties
const toolbarSettings: ToolbarSettingsModel = {
showTooltip: true,
};
export function App() {
return (
<PdfViewerComponent
toolbarSettings={toolbarSettings}
// ... rest of props
/>
);
}✅ DO THIS INSTEAD (Simple & Clean):
<PdfViewerComponent
toolbarSettings={{ showTooltip: true }}
// ... rest of props
/>---
Syncfusion React PDF Viewer — Skill
Overview
The syncfusion-react-pdf-viewer skill enables AI-assisted code generation for the Syncfusion React PDF Viewer (`PdfViewerComponent`). It produces minimal, copy-pasteable TSX/JSX code to embed, configure, and interact with PDF documents inside React applications.
---
Compatibility
| Requirement | Version |
|---|---|
| React | >= 15.5.4 |
| Node.js | >= 14.0.0 |
| Package Manager | NPM |
| Framework | React (TypeScript or JavaScript) |
---
Skill Structure
syncfusion-react-pdfviewer/
├── SKILL.md # Skill rules, routing, and code generation guidelines
├── README.md # This file
└── references/
├── getting-started.md # Minimal setup & initialization template
├── general-properties.md # Core viewer properties (documentPath, height, locale, etc.)
├── enable-properties.md # Feature toggle properties (enableToolbar, enableAnnotation, etc.)
├── toolbar-settings.md # Toolbar visibility and item customization
├── toolbar-methods.md # Programmatic toolbar show/hide at runtime
├── contextmenu.md # Right-click context menu customization
├── page-navigation.md # Navigate between pages programmatically
├── bookmark-navigation.md # Bookmark panel and navigation
├── thumbnail-navigation.md # Thumbnail panel and page previews
├── hyperlink-navigation.md # Hyperlink and external link behavior
├── magnification.md # Zoom levels, zoom modes, fit-to-page/width
├── interaction-mode.md # Selection mode vs. panning mode
├── text-selection.md # Enable text select, copy, and selection events
├── text-search.md # Find text in PDF with search options
├── annotation-settings.md # Annotation appearance (colors, opacity, styles)
├── annotation-events.md # Annotation lifecycle events (add, delete, resize, etc.)
├── shape-label-settings.md # Shape/measure annotation label customization
├── redaction-annotation.md # Redaction: create, configure, and apply
├── form-field-settings.md # Form field default properties
├── form-field-events.md # Form field interaction events (focus, blur, change)
├── download.md # PDF download configuration
├── print.md # PDF print configuration
├── organize-pages.md # Reorder, rotate, insert, remove, merge pages
├── api-methods.md # Programmatic API (load, export, undo/redo, extract text)
└── events.md # Complete PDF Viewer event reference---
Quick Start
1. Create a React Project
# TypeScript
npm create vite@latest my-app -- --template react-ts
cd my-app
# JavaScript
npm create vite@latest my-app -- --template react
cd my-app2. Install the Package
npm install @syncfusion/ej2-react-pdfviewer --save3. Copy WebAssembly Resources
cp -R ./node_modules/@syncfusion/ej2-pdfviewer/dist/ej2-pdfviewer-lib public/ej2-pdfviewer-lib4. Add CSS Imports (src/index.css)
@import '../node_modules/@syncfusion/ej2-base/styles/material.css';
@import '../node_modules/@syncfusion/ej2-buttons/styles/material.css';
@import '../node_modules/@syncfusion/ej2-dropdowns/styles/material.css';
@import '../node_modules/@syncfusion/ej2-inputs/styles/material.css';
@import '../node_modules/@syncfusion/ej2-navigations/styles/material.css';
@import '../node_modules/@syncfusion/ej2-popups/styles/material.css';
@import '../node_modules/@syncfusion/ej2-splitbuttons/styles/material.css';
@import '../node_modules/@syncfusion/ej2-pdfviewer/styles/material.css';5. Basic Component (src/App.tsx)
import * as React from 'react';
import {
PdfViewerComponent, Toolbar, Magnification, Navigation,
LinkAnnotation, BookmarkView, ThumbnailView, Print,
TextSelection, Annotation, TextSearch, FormFields, FormDesigner, Inject
} from '@syncfusion/ej2-react-pdfviewer';
function App() {
return (
<PdfViewerComponent
id="container"
documentPath="https://cdn.syncfusion.com/content/pdf/pdf-succinctly.pdf"
resourceUrl="https://cdn.syncfusion.com/ej2/31.2.2/dist/ej2-pdfviewer-lib"
style={{ height: '640px' }}
>
<Inject services={[
Toolbar, Magnification, Navigation, Annotation, LinkAnnotation,
BookmarkView, ThumbnailView, Print, TextSelection, TextSearch,
FormFields, FormDesigner
]} />
</PdfViewerComponent>
);
}
export default App;6. Run the App
npm run dev---
Available Services
Inject only the services your use-case requires to keep the bundle lean.
| Service | Purpose |
|---|---|
Toolbar | Main toolbar with document controls |
Magnification | Zoom and magnification |
Navigation | Page navigation controls |
Annotation | All annotation capabilities |
LinkAnnotation | Clickable hyperlinks in PDFs |
BookmarkView | Bookmark/outline panel |
ThumbnailView | Page thumbnail panel |
Print | Print functionality |
TextSelection | Select and copy text |
TextSearch | Find text in document |
FormFields | Interactive form field support |
FormDesigner | Create and edit form fields |
---
Reference File Routing
Use the table below to find the correct reference file for any feature request.
Core Setup
| Reference File | Use When … |
|---|---|
getting-started.md | Getting started, minimal setup, loading a PDF |
general-properties.md | Configuring server URL, locale, width/height, resourceUrl |
enable-properties.md | Enabling/disabling toolbar, annotations, forms, download, print |
Navigation
| Reference File | Use When … |
|---|---|
page-navigation.md | Go to first/last/next/previous page or a specific page number |
bookmark-navigation.md | Navigate via bookmarks or open/close bookmark panel |
thumbnail-navigation.md | Display or navigate with the thumbnail panel |
hyperlink-navigation.md | Configure clickable hyperlinks and external URL behavior |
Viewing & Interaction
| Reference File | Use When … |
|---|---|
magnification.md | Zoom controls, fit-to-page, fit-to-width, zoom levels |
interaction-mode.md | Switch between text-selection and panning modes |
text-selection.md | Enable/handle text selection and copy events |
text-search.md | Implement in-document text search and result highlighting |
Toolbar & Context Menu
| Reference File | Use When … |
|---|---|
toolbar-settings.md | Customize toolbar items, visibility, and tooltip behavior |
toolbar-methods.md | Show/hide toolbars programmatically at runtime |
contextmenu.md | Add, remove, or handle right-click context menu items |
Annotations
| Reference File | Use When … |
|---|---|
annotation-settings.md | Set default annotation colors, opacity, author, styles |
annotation-events.md | Handle annotation add/delete/move/resize/select events |
shape-label-settings.md | Customize labels on shape and measure annotations |
redaction-annotation.md | Create and apply redactions to remove sensitive content |
Forms
| Reference File | Use When … |
|---|---|
form-field-settings.md | Configure default properties for text, checkbox, radio, dropdown, signature fields |
form-field-events.md | Handle form field focus, blur, and value-change events |
Document Actions
| Reference File | Use When … |
|---|---|
download.md | Enable download and set custom filenames |
print.md | Configure and trigger printing |
organize-pages.md | Reorder, rotate, insert, remove, or merge pages |
Advanced / API
| Reference File | Use When … |
|---|---|
api-methods.md | Load documents programmatically, export form data, undo/redo, extract text |
events.md | Browse all available PDF Viewer events and their signatures |
---
Metadata
| Field | Value |
|---|---|
| Skill Name | syncfusion-react-pdf-viewer |
| Author | Syncfusion Inc |
| Version | 1.0.0 |
| Category | Document Viewing |
| Framework | React |
| Reference Files | 25 |
Annotation Events
Description: Annotation events in React PDF Viewer are triggered when annotations are added, removed, moved, resized, selected, or modified on PDF document pages. These events enable custom workflows and UI updates based on annotation interactions.
Table of Contents
- When to Use Annotation Events
- Choosing the Right Event
- How to Use Annotation Events
- Annotation Events Reference
- Annotation Object Reference
- Common Use Cases
---
When to Use Annotation Events
Guide users to implement annotation events when they need to:
- Track user interactions - Log annotation changes for audit trails, analytics, or compliance
- Implement custom workflows - Trigger actions when annotations are added, modified, or removed
- Build custom UI - Update properties panels, toolbars, or status displays based on annotation state
- Enforce business rules - Validate or restrict annotation placement, modifications, or deletions
- Synchronize data - Save annotation changes to a backend, sync across users, or update related data
- Enhance UX - Provide real-time feedback, tooltips, or guided workflows during annotation
Why events matter: The PDF Viewer fires events at key moments in the annotation lifecycle. By handling these events, users can extend the viewer's behavior without modifying its internals.
---
Choosing the Right Event
Help users select the appropriate event based on their goal:
| User Goal | Recommended Event | Why This Event |
|---|---|---|
| Detect when user creates a new annotation | annotationAdd | Fires immediately after annotation is added, providing full annotation object |
| Prevent annotation on specific pages | beforeAddFreeText | Only "before" event that supports cancellation via args.cancel = true |
| Track annotation movements | annotationMove | Fires after move completes with updated position; use annotationMoving for real-time tracking |
| Update UI when annotation is selected | annotationSelect | Provides selected annotation details and supports multi-select detection |
| Log property changes for audit | annotationPropertiesChange | Includes flags (isColorChanged, isThicknessChanged) to identify what changed |
| Detect annotation deletion | annotationRemove | Fires when annotation is removed, providing the removed annotation object |
| Show tooltips on hover | annotationMouseover / annotationMouseLeave | Mouse events provide coordinates and annotation context |
| Track signature additions | addSignature | Specific event for signature objects (not generic annotations) |
| Handle bulk operations | annotationSelect with isMultiSelect check | Use annotationCollection array to process multiple annotations |
Decision Pattern: If user needs to prevent an action → use beforeAdd* events with args.cancel. If user needs to react after an action → use lifecycle events like annotationAdd, annotationMove, annotationRemove.
---
How to Use Annotation Events
Annotation events allow you to respond to user interactions with annotations in the PDF Viewer. Each event provides detailed information about the annotation and the action performed.
Basic Event Handler Pattern
const eventHandler = (args: any): void => {
// Handle the event
console.log('Event triggered:', args);
};
// Attach event handler to PdfViewerComponent
<PdfViewerComponent
annotationAdd={eventHandler} // Example: Use specific event name like annotationAdd, annotationRemove, etc.
>
</PdfViewerComponent>---
Annotation Events Reference
The following table lists all available annotation events. Use this reference to identify event names, understand what triggers them, and access the data they provide.
How to read this table:
- Event Name: The prop name to use on
<PdfViewerComponent> - Description: When the event fires during the annotation lifecycle
- Args: The TypeScript type of the event arguments object
- Args Properties: Key properties available in the event handler, including data types
Usage tip: Most events provide annotationId, pageIndex, and the complete annotation object. Use the annotation object to access all properties listed in the Annotation Object Reference section below.
| Event Name | Description | Args | Args Properties |
|---|---|---|---|
| annotationAdd | Fires when an annotation is added to a page in the PDF document. | AnnotationAddEventArgs | annotationId - (string) - Unique identifier of the annotation. pageIndex - (number) - Page index where the annotation was added. annotation - (object) - Annotation object containing all properties. annotationAddMode - (string) - Mode of annotation addition (UI Drawn, Programmatic, etc.). |
| annotationDoubleClick | Fires when an annotation is double-clicked. | AnnotationDoubleClickEventArgs | annotationId - (string) - ID of the annotation that was double-clicked. pageIndex - (number) - Page index where the annotation was double-clicked. annotation - (object) - Annotation object containing all properties. |
| annotationMouseLeave | Fires when the mouse pointer moves away from an annotation object. | AnnotationMouseLeaveEventArgs | annotationId - (string) - ID of the annotation. pageIndex - (number) - Page index of the annotation. |
| annotationMouseover | Fires when the mouse pointer moves over an annotation object. | AnnotationMouseOverEventArgs | annotationId - (string) - ID of the annotation. pageIndex - (number) - Page index of the annotation. X - (number) - X coordinate of mouse position. Y - (number) - Y coordinate of mouse position. |
| annotationMove | Fires when an annotation is moved on a page in the PDF document. | AnnotationMoveEventArgs | annotationId - (string) - ID of the annotation that was moved. pageIndex - (number) - Page index where the annotation was moved. annotation - (object) - Updated annotation object. |
| annotationMoving | Fires while an annotation is being moved. | AnnotationMovingEventArgs | annotationId - (string) - ID of the annotation being moved. pageIndex - (number) - Page index. currentPosition - (object) - Current position during movement. |
| annotationPropertiesChange | Fires when the properties of an annotation are modified on a PDF page. | AnnotationPropertiesChangeEventArgs | annotationId - (string) - ID of the annotation. pageIndex - (number) - Page index. isColorChanged - (boolean) - Indicates if color was changed. isThicknessChanged - (boolean) - Indicates if thickness was changed. isOpacityChanged - (boolean) - Indicates if opacity was changed. annotation - (object) - Updated annotation object. |
| annotationRemove | Fires when an annotation is removed from a page in the PDF document. | AnnotationRemoveEventArgs | annotationId - (string) - ID of the removed annotation. pageIndex - (number) - Page index where the annotation was removed. annotation - (object) - Annotation object that was removed. |
| annotationResize | Fires when an annotation is resized on a page in the PDF document. | AnnotationResizeEventArgs | annotationId - (string) - ID of the resized annotation. pageIndex - (number) - Page index. annotation - (object) - Updated annotation object with new bounds. |
| annotationSelect | Fires when an annotation is selected on a page in the PDF document. | AnnotationSelectEventArgs | annotationId - (string) - ID of the selected annotation. pageIndex - (number) - Page index. annotation - (object) - Selected annotation object. annotationCollection - (array) - Collection of overlapping annotations. isMultiSelect - (boolean) - Indicates if multiple annotations are selected. |
| annotationUnSelect | Fires when an annotation is unselected on a page in the PDF document. | AnnotationUnSelectEventArgs | annotationId - (string) - ID of the unselected annotation. pageIndex - (number) - Page index where the annotation was unselected. |
| beforeAddFreeText | Fires before a free-text annotation is added. | BeforeAddFreeTextEventArgs | pageIndex - (number) - Page index where the annotation will be added. cancel - (boolean) - Set to true to prevent the annotation from being added. |
| addSignature | Fires when a signature is added to a page of a PDF document. | AddSignatureEventArgs | pageIndex - (number) - Page index where the signature was added. signature - (object) - Signature object with properties like bounds, opacity, strokeColor, thickness. |
| removeSignature | Fires when the signature is removed from the page of a PDF document. | RemoveSignatureEventArgs | pageIndex - (number) - Page index where the signature was removed. signature - (object) - Signature object that was removed. |
| resizeSignature | Fires when the signature is resized on a page in the PDF document. | ResizeSignatureEventArgs | pageIndex - (number) - Page index. signature - (object) - Updated signature object with new bounds. previousPosition - (object) - Previous position before resize. currentPosition - (object) - Current position after resize. |
| signaturePropertiesChange | Fires when the properties of a signature are changed on a page in the PDF document. | SignaturePropertiesChangeEventArgs | pageIndex - (number) - Page index. isThicknessChanged - (boolean) - Indicates if thickness was changed. isOpacityChanged - (boolean) - Indicates if opacity was changed. isStrokeColorChanged - (boolean) - Indicates if stroke color was changed. signature - (object) - Updated signature object. |
| signatureSelect | Fires when a signature is selected on a page in the PDF document. | SignatureSelectEventArgs | pageIndex - (number) - Page index where the signature was selected. signature - (object) - Selected signature object. |
| signatureUnselect | Fires when a signature is unselected on a page in the PDF document. | SignatureUnSelectEventArgs | pageIndex - (number) - Page index where the signature was unselected. |
---
Annotation Object Reference
Purpose: When event handlers receive an annotation object in their arguments, use this reference to understand which properties are available and how to access them.
When to consult this reference:
- User needs to read annotation properties (color, opacity, position, type)
- User wants to display annotation details in a custom UI
- User needs to filter or validate annotations based on specific properties
- User is building custom logic based on annotation state
Usage pattern: Access properties directly from the args.annotation object:
const onAnnotationSelect = (args: any): void => {
const annotation = args.annotation;
// Access common properties
console.log('Type:', annotation.type); // e.g., "FreeText", "Ink"
// Type-specific properties
if (annotation.type === 'FreeText') {
console.log('Content:', annotation.content); // Text content
}
};Property availability: Not all properties are present on all annotation types. Check type or subType to determine which type-specific properties are available.
Core Properties (Available on All Annotation Types)
| Property Name | Description | Data type |
|---|---|---|
| annotationId | Unique identifier for the annotation. | string |
| id | Internal identifier for the annotation (e.g., ink0, free_text0). | string |
| randomId | Random identifier for certain annotation types like stamps. | string |
| author | Author of the annotation. | string |
| pageNumber / pageIndex | Page number/index where the annotation is located. | number |
| type | Type of annotation (TextMarkup, FreeText, Ink, Measure, Stamp, StickyNotes, etc.). | string |
| subType | Subtype of the annotation (Highlight, Underline, Strikethrough, Squiggly, Area, etc.). | string |
| shapeAnnotationType | Shape type of the annotation (textMarkup, Polygon, Ink, FreeText, Stamp, sticky, etc.). | string |
| subject | Subject or title of the annotation. | string |
| note / notes | Note/comment associated with the annotation. | string |
| color | Color of the annotation (hex value or rgba). | string |
| strokeColor | Stroke/border color of the annotation. | string |
| fillColor | Fill color of the annotation (hex or rgba). | string |
| opacity | Opacity value of the annotation (0-1). | number |
| thickness | Thickness/width of the stroke. | number |
| bounds | Boundary object with x, y, width, height, left, top, right values. | object |
| rect | Rectangle object with bottom, left, right, top, height, width values. | object |
| width / height / left / top | Direct dimension and position properties. | number |
| customData | Custom data associated with the annotation. | object |
| modifiedDate | Last modified date of the annotation. | string |
| creationDate | Creation date of the annotation. | string |
| annotationAddMode | Mode of annotation addition (UI Drawn Annotation, Programmatic, etc.). | string |
| isLocked | Whether the annotation is locked from editing. | boolean |
| isCommentLock | Whether comments on the annotation are locked. | boolean |
| isPrint | Whether the annotation is included in print. | boolean |
| isMultiSelect | Whether annotation spans multiple pages. | boolean |
| isAnnotationRotated | Whether the annotation is rotated. | boolean |
| rotateAngle | Rotation angle of the annotation (RotateAngle0, RotateAngle90, etc. or numeric). | string \ |
| comments | Array of comment objects for this annotation. | array |
| review | Review status information. | object |
| annotationSettings | Annotation settings with isLock, isPrint, min/max height/width. | object |
| annotationSelectorSettings | Settings for the annotation selector (resizer, border, etc.). | object |
| annotationCollection | Collection of overlapping annotations. | array |
| allowedInteractions | Array of allowed interactions for locked annotations. | array |
| vertexPoints | Array of vertex points for polygon-type annotations. | array |
| rectangleDifference | Difference rectangle data. | array |
Type-Specific Properties
Different annotation types expose additional properties. Check the type property to determine which properties are available.
| Property Name | Description | Data type |
|---|---|---|
| TextMarkup Properties | Available when type === "TextMarkup" | |
| textMarkupContent | The text content that was marked up. | string |
| textMarkupStartIndex | Start index of the marked text. | number |
| textMarkupEndIndex | End index of the marked text. | number |
| Measure/Shape Properties | Available when type === "Shape" or measurement annotations | |
| caption | Whether caption is enabled for the annotation. | boolean |
| captionPosition | Position of the caption (Top, Bottom, Left, Right). | string |
| enableShapeLabel | Whether shape label is enabled. | boolean |
| labelContent | Content of the label. | string |
| labelBounds | Boundary of the label. | object |
| labelBorderColor | Border color of the label. | string |
| labelFillColor | Fill color of the label. | string |
| labelSettings | Label settings object with borderColor, fillColor, fontColor, fontSize, etc. | object |
| fontColor | Font color for text. | string |
| fontSize | Font size for text. | number |
| indent | Indent value for measure annotations. | string |
| leaderLength | Length of the leader line. | number |
| leaderLineExtension | Extension of the leader line. | number |
| leaderLineOffset | Offset of the leader line. | number |
| lineHeadStart | Style of line head start (Arrow, Closed, Diamond, None, etc.). | string |
| lineHeadEnd | Style of line head end. | string |
| cloudIntensity | Intensity of cloud shape. | number |
| isCloudShape | Whether the shape is a cloud shape. | boolean |
| calibrate | Calibration data with ratio, x, distance, area information. | object |
| FreeText Properties | Available when type === "FreeText" | |
| content | Text content of the free text annotation. | string |
| dynamicText | Dynamic text of the annotation. | string |
| fontFamily | Font family for the text. | string |
| textAlign | Text alignment (Left, Center, Right, Justify). | string |
| font | Font object with isBold, isItalic, isStrikeout, isUnderline properties. | object |
| isReadonly | Whether the free text is read-only. | boolean |
| Ink Properties | Available when type === "Ink" (hand-drawn annotations) | |
| data | Path data for ink annotation (SVG path format). | string |
| Stamp Properties | Available when type === "Stamp" | |
| icon | Icon/stamp type (Revised, Approved, AsIs, Expired, etc.). | string |
| customStampName | Name of custom stamp. | string |
| isDynamicStamp | Whether the stamp is dynamic. | boolean |
| isMaskedImage | Whether the stamp has a masked image. | boolean |
| stampAnnotationType | Type of stamp annotation. | string |
| stampAnnotationPath | Path data for stamp annotation. | array |
| stampFillcolor | Fill color of the stamp. | string |
| template | Stamp template. | string |
| templateSize | Size of the stamp template. | string |
| StickyNotes Properties | Available when type === "StickyNotes" | |
| state | State of the sticky note. | string |
| stateModel | State model of the sticky note. | string |
| pathData | Path data for sticky note. | string |
| borderDashArray | Border dash array style. | number |
| borderStyle | Border style. | string |
Nested Object Structures
Many annotation properties are complex objects. Use these references to understand their structure and access nested properties.
Rect Object
Purpose: Represents the rectangular boundary of an annotation. Available via args.annotation.rect.
Usage example:
const rect = args.annotation.rect;
console.log(`Position: (${rect.left}, ${rect.top})`);
console.log(`Size: ${rect.width} x ${rect.height}`);| Property Name | Description | Data type |
|---|---|---|
| bottom | Bottom coordinate value. | number |
| left | Left coordinate value. | number |
| right | Right coordinate value. | number |
| top | Top coordinate value. | number |
| height | Height of the rectangle. | number |
| width | Width of the rectangle. | number |
Review Object
Purpose: Contains review/approval status for annotations. Available via args.annotation.review.
Usage example:
if (args.annotation.review) {
console.log('Review state:', args.annotation.review.state);
console.log('Reviewed by:', args.annotation.review.author);
}| Property Name | Description | Data type |
|---|---|---|
| state | State of the review (Accepted, Rejected, Cancelled, etc.). | string |
| stateModel | State model of the review. | string |
| author | Author of the review. | string |
| modifiedDate | Modified date of the review. | string |
AnnotationSettings Object
Purpose: Configuration settings for the annotation. Available via args.annotation.annotationSettings.
Usage example:
if (args.annotation.annotationSettings?.isLock) {
console.log('This annotation is locked');
}| Property Name | Description | Data type |
|---|---|---|
| isLock | Whether the annotation is locked. | boolean |
| isPrint | Whether the annotation should be printed. | boolean |
| maxHeight | Maximum height of the annotation. | number |
| maxWidth | Maximum width of the annotation. | number |
| minHeight | Minimum height of the annotation. | number |
| minWidth | Minimum width of the annotation. | number |
AnnotationSelectorSettings Object
Purpose: Visual appearance settings for annotation selection handles and borders. Available via args.annotation.annotationSelectorSettings.
| Property Name | Description | Data type |
|---|---|---|
| resizerFillColor | Fill color of the resizer handles. | string |
| resizerBorderColor | Border color of the resizer handles. | string |
| resizerSize | Size of the resizer handles. | number |
| resizerShape | Shape of the resizer handles (Square, Circle, etc.). | string |
| resizerLocation | Location of resizers (corners, edges, etc.). | number |
| resizerCursorType | Cursor type for the resizer. | string |
| selectionBorderColor | Color of the selection border. | string |
| selectionBorderThickness | Thickness of the selection border. | number |
| selectorLineDashArray | Dash array pattern for the selector line. | array |
LabelSettings Object
Purpose: Styling configuration for annotation labels (used in shape and measurement annotations). Available via args.annotation.labelSettings.
| Property Name | Description | Data type |
|---|---|---|
| borderColor | Border color of the label. | string |
| fillColor | Fill color of the label. | string |
| fontColor | Font color for label text. | string |
| fontSize | Font size for label text. | number |
| labelContent | Default content of the label. | string |
| fontFamily | Font family for label text. | string |
| notes | Notes associated with the label. | string |
| opacity | Opacity of the label. | number |
Font Object
Purpose: Text formatting properties for free text annotations. Available via args.annotation.font.
Usage example:
if (args.annotation.type === 'FreeText') {
const font = args.annotation.font;
if (font.isBold) console.log('Text is bold');
if (font.isItalic) console.log('Text is italic');
}| Property Name | Description | Data type |
|---|---|---|
| isBold | Whether the text is bold. | boolean |
| isItalic | Whether the text is italic. | boolean |
| isStrikeout | Whether the text has strikeout. | boolean |
| isUnderline | Whether the text is underlined. | boolean |
Calibrate Object
Purpose: Measurement calibration data for distance/area annotations. Available via args.annotation.calibrate.
| Property Name | Description | Data type |
|---|---|---|
| ratio | Calibration ratio (e.g., "1 in = 1 in"). | string |
| x | Array of X calibration values. | array |
| distance | Array of distance calibration values. | array |
| area | Array of area calibration values. | array |
Bounds Object
Purpose: Position and dimensions of an annotation. Available via args.annotation.bounds.
Usage example:
const bounds = args.annotation.bounds;
console.log(`Annotation at (${bounds.x}, ${bounds.y})`);
console.log(`Size: ${bounds.width} x ${bounds.height}`);
// Bounds provides multiple coordinate representations
console.log(`Alternative: left=${bounds.left}, top=${bounds.top}, right=${bounds.right}`);| Property Name | Description | Data type |
|---|---|---|
| x | X coordinate. | number |
| y | Y coordinate. | number |
| left | Left coordinate. | number |
| top | Top coordinate. | number |
| width | Width of the bounds. | number |
| height | Height of the bounds. | number |
| right | Right coordinate. | number |
VertexPoint Object
Purpose: Represents individual points in polygon-based annotations. Available via args.annotation.vertexPoints (array).
Usage example:
if (args.annotation.vertexPoints) {
args.annotation.vertexPoints.forEach((point, index) => {
console.log(`Point ${index}: (${point.x}, ${point.y})`);
});
}| Property Name | Description | Data type |
|---|---|---|
| x | X coordinate of the vertex. | number |
| y | Y coordinate of the vertex. | number |
---
Common Use Cases
Purpose: Guide users through practical implementations that solve real-world requirements. Each example demonstrates a specific pattern and explains when to apply it.
How to use these examples: 1. Identify the user's requirement (audit logging, access control, custom UI, etc.) 2. Point them to the matching use case 3. Explain how to adapt the pattern to their specific needs 4. Highlight which event properties are essential for their scenario
---
1. Tracking Annotation Changes
User Need: Log user interactions, implement audit trails, or send analytics data.
When to recommend: User mentions "tracking", "logging", "audit", "analytics", "telemetry", or "history".
Pattern: Attach handlers to lifecycle events (annotationAdd, annotationMove, annotationRemove) and log relevant data.
const onAnnotationMove = (args: any): void => {
// Track annotation movement for telemetry
logEvent('annotation_moved', {
annotationId: args.annotationId,
page: args.pageIndex,
timestamp: new Date().toISOString()
});
};
<PdfViewerComponent annotationMove={onAnnotationMove} />Why this works: annotationMove fires after the move completes, providing the final position. For real-time tracking during drag, use annotationMoving instead.
Key properties: annotationId (identifier), pageIndex (location), timestamp (when).
---
2. Preventing Certain Actions
User Need: Restrict annotation placement on specific pages (e.g., cover pages, signature pages) or enforce business rules.
When to recommend: User mentions "prevent", "restrict", "block", "validation", "business rules", or "access control".
Pattern: Use beforeAddFreeText event and set args.cancel = true to prevent the action.
Important: This is the only event that supports cancellation. Use it for validation before annotations are created.
const onBeforeAddFreeText = (args: any): void => {
// Prevent free text annotation on first page (cover page)
if (args.pageIndex === 0) {
args.cancel = true;
alert('Annotations are not allowed on the cover page.');
}
};
<PdfViewerComponent beforeAddFreeText={onBeforeAddFreeText} />Why this works: Setting args.cancel = true stops the annotation from being added. The event fires before the action completes, allowing intervention.
Limitation: Currently only available for beforeAddFreeText. For other annotation types, handle in annotationAdd and remove if invalid using deleteAnnotationById().
---
3. Accessing Annotation Properties
User Need: Display annotation details in a properties panel, inspector, or custom UI.
When to recommend: User mentions "properties panel", "inspector", "details view", "custom UI", or "show annotation info".
Pattern: Use annotationSelect to get the full annotation object when user selects an annotation, then display its properties.
const onAnnotationSelect = (args: any): void => {
const annotation = args.annotation;
console.log('Color:', annotation.color);
// Update UI with annotation properties
updatePropertiesPanel(args.annotationId, annotation);
};
<PdfViewerComponent annotationSelect={onAnnotationSelect} />Why this works: annotationSelect provides the complete annotation object with all properties. Reference the Annotation Object Reference above to see all available properties.
Key insight: Use args.isMultiSelect to detect if multiple annotations are selected, and args.annotationCollection to process them.
---
4. Validating Property Changes
User Need: Track specific property modifications for compliance, review workflows, or change detection.
When to recommend: User mentions "property changes", "detect modifications", "compliance", "track edits", or "change history".
Pattern: Use annotationPropertiesChange event with boolean flags to identify which properties changed.
const onAnnotationPropertiesChange = (args: any): void => {
if (args.isColorChanged) {
console.log('Annotation color changed to:', args.annotation.color);
}
};
<PdfViewerComponent annotationPropertiesChange={onAnnotationPropertiesChange} />Why this works: The event provides boolean flags (isColorChanged, isThicknessChanged, isOpacityChanged) so you can detect exactly what changed without comparing old/new values.
Key properties: Use args.annotation to access the updated property values.
Advanced: Combine with annotationSelect to show real-time property updates in a UI panel.
---
5. Handling Multiple Selections
User Need: Perform bulk operations on multiple annotations (delete all, change color, export selected).
When to recommend: User mentions "bulk operations", "multiple annotations", "select all", "batch processing", or "group actions".
Pattern: Check args.isMultiSelect in annotationSelect event and use args.annotationCollection to process each annotation.
const onAnnotationSelect = (args: any): void => {
if (args.isMultiSelect) {
console.log('Multiple annotations selected');
console.log('Selected annotations count:', args.annotationCollection.length);
// Process each selected annotation
args.annotationCollection.forEach((annotation: any) => {
console.log('Annotation ID:', annotation.annotationId);
});
} else {
console.log('Single annotation selected:', args.annotationId);
}
};
<PdfViewerComponent annotationSelect={onAnnotationSelect} />Why this works: annotationCollection contains all selected annotations when isMultiSelect === true. Loop through this array to apply operations to each annotation.
Implementation tip: After bulk operations, use the viewer's API methods (e.g., deleteAnnotationById(), updateAnnotationProperties()) on each annotation ID from the collection.
UI consideration: Provide clear feedback showing how many annotations are selected and which operation will be applied.
Annotation Settings in React PdfViewer Component
Description: Configure PDF annotation settings immediately to control appearance, behavior, and interaction of text markup, shape, and stamp annotations in the SfPdfViewer component. Customize colors, styles, author details, and access restrictions to achieve specific annotation requirements
Table of Contents
- Overview
- Quick Start
- Global vs Type-Specific Settings
- Annotation Types Available
- Settings Properties Reference
- Annotation-Related Component Properties
- Core Properties for All Annotations
- Selector Customization
- Common Use Cases
- Type Definitions
Important: Bounds Format for Annotations (Lowercase)
⚠️ When adding annotations programmatically, ALWAYS use lowercase property names in the bounds object:
// CORRECT ✅ - Use LOWERCASE bounds
pdfViewerRef.current?.annotation.addAnnotation('Rectangle', {
bounds: { x: 100, y: 100, width: 200, height: 50 },
color: '#FF0000'
});
// INCORRECT ❌ - Do NOT use capitalized letters
pdfViewerRef.current?.annotation.addAnnotation('Rectangle', {
bounds: { X: 100, Y: 100, Width: 200, Height: 50 }, // WRONG for annotations
color: '#FF0000'
});---
Overview
Configure annotation settings immediately to control how PDF annotations display and behave in your viewer. Choose between applying settings globally to all annotation types or customizing individual annotation behaviors through type-specific properties like highlightSettings, areaSettings, stampSettings, etc.
When to use: Whenever you need to customize annotation appearance (colors, size, opacity), control user interactions (lock state, allowed actions), set author details, or restrict features (disable downloads/printing).
How to Use the Settings in PDF Viewer
Quick Start
Apply Settings to Specific Annotation Type
Customize appearance and behavior for individual annotation types by setting type-specific properties:
const highlightSettings = {
color: 'green', // Text highlight color
opacity: 0.6, // Transparency (0-1)
author: 'John Doe', // Who created the annotation
isLock: false // Allow user interaction
};
<PdfViewerComponent
highlightSettings={highlightSettings}
>
<Inject services={[Annotation, TextSelection]} />
</PdfViewerComponent>Use this when: You need to control how a specific annotation type (highlight, underline, stamp, etc.) appears and behaves across your PDF.
Apply Global Settings to All Annotations
Use annotationSettings property to apply common settings across every annotation type at once:
const annotationSettings = {
author: 'PDF Author',
opacity: 0.7,
isLock: false
};
<PdfViewerComponent
annotationSettings={annotationSettings}
>
<Inject services={[Annotation]} />
</PdfViewerComponent>Use this when: You want consistent author names, security levels, or opacity across all annotations in the PDF.
Global vs Type-Specific Settings
Global Settings (annotationSettings):
- Applied to all annotation types unless overridden
- Best for company-wide policies (author name, lock state, download restrictions)
- Properties:
author,subject,customData,isLock,isPrint,skipDownload,skipPrint,maxWidth,maxHeight,minWidth,minHeight,opacity,allowedInteractions
Type-Specific Settings:
- Override global settings for individual annotation behaviors
- Best for controlling how each annotation type looks and acts
- Examples:
highlightSettings,areaSettings,stampSettings,freeTextSettings - Each type has unique properties (e.g.,
highlightSettingshasenableMultiPageAnnotation,enableTextMarkupResizer)
Decision Guide:
- Setting author name? → Use
annotationSettings(global) - Customizing highlight color only? → Use
highlightSettings(type-specific) - Locking all annotations? → Use
annotationSettings(global) - Need different colors for different types? → Use multiple type-specific settings
Annotation Types Available
| Name | Description |
|---|---|
| Area | Represents the Area annotation |
| Arrow | Represents the Arrow annotation |
| Circle | Represents the Circle annotation |
| Distance | Represents the Distance annotation |
| FreeText | Represents the FreeText annotation |
| HandWrittenSignature | Represents the HandWrittenSignature annotation |
| Highlight | Represents the Highlight annotation |
| Ink | Represents the Ink annotation |
| Line | Represents the Line annotation |
| Perimeter | Represents the Perimeter annotation |
| Polygon | Represents the Polygon annotation |
| Radius | Represents the Radius annotation |
| Rectangle | Represents the Rectangle annotation |
| Squiggly | Represents the Squiggly annotation |
| Stamp | Represents the Stamp annotation |
| StickyNotes | Represents the StickyNotes annotation |
| Strikethrough | Represents the Strikethrough annotation |
| Underline | Represents the Underline annotation |
| Volume | Represents the Volume annotation |
All supported annotation types and their corresponding settings properties:
| Annotation Type | Property Name | Use When |
|---|---|---|
| Area | areaSettings | User needs to draw enclosed area measurements |
| Arrow | arrowSettings | User needs to draw directional arrows or connectors |
| Circle | circleSettings | User needs to mark circular regions |
| Distance | distanceSettings | User needs to measure distance between points |
| FreeText | freeTextSettings | User needs to add text boxes with custom styling |
| HandWrittenSignature | handwrittenSignatureSettings | User needs to add handwritten signatures |
| Highlight | highlightSettings | User needs to highlight text (most common) |
| Ink | inkAnnotationSettings | User needs freehand drawing or handwriting |
| Line | lineSettings | User needs to draw lines with arrow styles |
| Perimeter | perimeterSettings | User needs to measure perimeter of shapes |
| Polygon | polygonSettings | User needs to draw multi-sided shapes |
| Radius | radiusSettings | User needs to measure radius or diameter |
| Rectangle | rectangleSettings | User needs to mark rectangular regions |
| Squiggly | squigglySettings | User needs wavy line text markup |
| Stamp | stampSettings | User needs predefined stamps (Approved, Confidential, etc.) |
| StickyNotes | stickyNotesSettings | User needs comment notes on PDF |
| Strikethrough | strikethroughSettings | User needs strikethrough text markup |
| Underline | underlineSettings | User needs underline text markup |
| Volume | volumeSettings | User needs to calculate volume of 3D objects |
Settings Properties Reference
Annotation-Related Component Properties
These properties are available directly on the PdfViewerComponent to control annotation-related functionality:
| Property Name | Description | Type | Default Value |
|---|---|---|---|
| annotation | Get the annotation object of the PDF Viewer. | Annotation | null |
| annotationCollection | Get the annotation collection of the PDF Viewer. | AnnotationCollection | null |
| annotationDrawingOptions | Configure annotation drawing options. | AnnotationDrawingOptions | null |
| dateTimeFormat | Customize the date and time format for dynamic stamps and annotations. | string | "MM/dd/yyyy" |
| exportAnnotationFileName | Set the filename when exporting annotations. | string | "annotations" |
| handWrittenSignatureSettings | Configure handwritten signature settings. | HandWrittenSignatureSettings | null |
| isAnnotationToolbarVisible | Show or hide the annotation toolbar. | boolean | true |
| isSignatureEditable | Allow or prevent editing of signatures after creation. | boolean | true |
| isValidFreeText | Validate free text before rendering. | boolean | true |
| showDigitalSignatureAppearance | Show or hide digital signature appearance dialog. | boolean | true |
| signatureCollection | Get the collection of digital signatures in the PDF. | SignatureCollection | null |
| signatureDialogSettings | Configure signature dialog settings. | SignatureDialogSettings | null |
| signatureFitMode | Set how signatures fit in the signature field. | SignatureFitMode | Default |
Core Properties for All Annotations
| Property Name | Description | Data Type | Applicable To |
|---|---|---|---|
| annotationSettings | Settings applicable for all types of annotations | AnnotationSettings | All annotations |
| areaSettings | Settings applicable for area annotations | AreaSettings | Area |
| arrowSettings | Settings applicable for arrow annotations | ArrowSettings | Arrow |
| circleSettings | Settings applicable for circle annotations | CircleSettings | Circle |
| distanceSettings | Settings applicable for distance annotations | DistanceSettings | Distance |
| freeTextSettings | Settings applicable for free text annotations | FreeTextSettings | FreeText |
| handwrittenSignatureSettings | Settings applicable for handwritten signature annotations | HandWrittenSignatureSettings | HandWrittenSignature |
| highlightSettings | Settings applicable for highlight annotations | HighlightSettings | Highlight |
| inkAnnotationSettings | Settings applicable for ink annotations | InkAnnotationSettings | Ink |
| lineSettings | Settings applicable for line annotations | LineSettings | Line |
| measurementSettings | Settings applicable for distance, perimeter, area, radius, volume annotations | MeasurementSettings | Distance, Perimeter, Area, Radius, Volume |
| perimeterSettings | Settings applicable for perimeter annotations | PerimeterSettings | Perimeter |
| polygonSettings | Settings applicable for polygon annotations | PolygonSettings | Polygon |
| radiusSettings | Settings applicable for radius annotations | RadiusSettings | Radius |
| rectangleSettings | Settings applicable for rectangle annotations | RectangleSettings | Rectangle |
| squigglySettings | Settings applicable for squiggly annotations | SquigglySettings | Squiggly |
| stampSettings | Settings applicable for stamp annotations | StampSettings | Stamp |
| stickyNotesSettings | Settings applicable for sticky notes annotations | StickyNotesSettings | StickyNotes |
| strikethroughSettings | Settings applicable for strikethrough annotations | StrikethroughSettings | Strikethrough |
| underlineSettings | Settings applicable for underline annotations | UnderlineSettings | Underline |
| volumeSettings | Settings applicable for volume annotations | VolumeSettings | Volume |
Common Use Cases
Use Case 1: Apply Company Branding to All Annotations
// All annotations created by users will show your company name
<PdfViewerComponent
annotationSettings={{
author: 'Acme Corporation',
subject: 'Document Review',
customData: { department: 'Legal', version: '1.0' }
}}
>
<Inject services={[Annotation]} />
</PdfViewerComponent>Use Case 2: Make Annotations Non-Editable After Creation
// Users can see annotations but cannot modify them
<PdfViewerComponent
annotationSettings={{
isLock: true, // Prevent editing
allowedInteractions: [] // Restrict all interactions
}}
>
<Inject services={[Annotation]} />
</PdfViewerComponent>Use Case 3: Customize Highlight and Underline Appearance
// Make highlights green and underlines blue
<PdfViewerComponent
highlightSettings={{ color: '#00FF00', opacity: 0.5 }}
underlineSettings={{ color: '#0000FF', opacity: 0.4 }}
>
<Inject services={[Annotation, TextSelection]} />
</PdfViewerComponent>Use Case 4: Restrict Annotation Download/Print
// Annotations won't appear in exported files or print output
<PdfViewerComponent
annotationSettings={{
skipDownload: true, // Hide from downloaded PDFs
skipPrint: true // Hide from printed pages
}}
>
<Inject services={[Annotation]} />
</PdfViewerComponent>Use Case 5: Customize Resize Handles When Editing Annotations
// Control how annotation selection handles appear during editing
<PdfViewerComponent
annotationSelectorSettings={{
resizerBorderColor: '#FF0000', // Red border
resizerFillColor: '#FFE0E0', // Light red fill
resizerSize: 8, // Handle size in pixels
resizerShape: 'Circle' // Circle or Square
}}
>
<Inject services={[Annotation]} />
</PdfViewerComponent>Selector Customization
Apply Selection Styling Globally
Apply resize handle customization to all annotations:
<PdfViewerComponent
annotationSelectorSettings={{ resizerBorderColor: 'green' }}
>
<Inject services={[Annotation]} />
</PdfViewerComponent>Apply Selection Styling to Specific Annotation Type
Customize resize handles for individual annotation types:
<PdfViewerComponent
areaSettings={{ annotationSelectorSettings: { resizerBorderColor: 'green' } }}
>
<Inject services={[Annotation]} />
</PdfViewerComponent>Type Definitions
| Property Name | Description | Data Type | Applicable Settings |
|---|---|---|---|
| allowedInteractions | Gets or sets the allowed interactions for the locked annotations. IsLock can be configured using settings. | AllowedInteraction[] | AnnotationSettings, All annotation type settings |
| annotationSelectorSettings | Defines the annotation selector settings for the annotation. | AnnotationSelectorSettings | AreaSettings, ArrowSettings, CircleSettings, DistanceSettings, FreeTextSettings, HandwrittenSignatureSettings, InkAnnotationSettings, LineSettings, PerimeterSettings, PolygonSettings, RadiusSettings, RectangleSettings, StampSettings, VolumeSettings |
| author | Specifies the author's name to add annotation or review the PDF document. By default it is Guest. | string | AnnotationSettings, All annotation type settings |
| borderColor | Defines the border color for free text annotation. By default it is "#ffffff00". | string | FreeTextSettings |
| borderDashArray | Defines the border dash array. | number[] | AreaSettings, ArrowSettings, CircleSettings, DistanceSettings, HandwrittenSignatureSettings, InkAnnotationSettings, LineSettings, PerimeterSettings, PolygonSettings, RadiusSettings, RectangleSettings, StampSettings, VolumeSettings |
| borderStyle | Defines the border style for free text annotation. By default it is "solid". | string | FreeTextSettings |
| borderWidth | Defines the border width for free text annotation. By default it is 1. | number | FreeTextSettings |
| color | Defines the color for text markup annotations. | string | HighlightSettings, SquigglySettings, StrikethroughSettings, UnderlineSettings |
| conversionUnit | Defines the unit for measuring annotation. By default it is "in". | CalibrationUnit | MeasurementSettings |
| customData | Specifies the user's defined information related to the annotations. By default it is null. | object | AnnotationSettings, All annotation type settings |
| customStamps | Gets or sets a collection of custom stamps for the PDF Viewer. | CustomStampSettings[] | StampSettings |
| dateTimeFormat | Customize desired date and time format for dynamic stamps. | string | StampSettings |
| defaultText | Defines the default text for free text annotation. By default it is "Type Here". | string | FreeTextSettings |
| depth | Defines the value for depth. By default it is 96. | number | MeasurementSettings |
| displayUnit | Defines the display unit for measuring annotation. By default it is "in". | CalibrationUnit | MeasurementSettings |
| dynamicStamps | Provide option to define the required dynamic stamp items to be displayed in annotation toolbar menu. | DynamicStampItem[] | StampSettings |
| enableAutoFit | Enable or disable auto fit mode for FreeText annotation. By default it is false. | boolean | FreeTextSettings |
| enableCustomStamp | If it is set as false, then we can't add the custom stamp annotation in the PDF Viewer. By default it is true. | boolean | StampSettings |
| enableMultiPageAnnotation | If it is set as true, then can add text markup annotation with multiple pages. Otherwise can add text markup annotation only within the page. By default it is false. | boolean | HighlightSettings, SquigglySettings, StrikethroughSettings, UnderlineSettings |
| enableTextMarkupResizer | If it is set as true, resizer for text markup annotation will be enabled. By default it is false. | boolean | HighlightSettings, SquigglySettings, StrikethroughSettings, UnderlineSettings |
| fillColor | Specifies the fill color of the annotation. | string | AreaSettings, ArrowSettings, CircleSettings, DistanceSettings, FreeTextSettings, HandwrittenSignatureSettings, InkAnnotationSettings, LineSettings, PerimeterSettings, PolygonSettings, RadiusSettings, RectangleSettings, StampSettings, VolumeSettings |
| fontColor | Defines the font color for free text annotation. By default it is "#000". | string | FreeTextSettings |
| fontFamily | Defines the font family for free text annotation. By default it is "Helvetica". | string | FreeTextSettings |
| fontSize | Defines the font size for free text annotation. By default it is 16. | number | FreeTextSettings |
| fontStyle | Defines the font style for free text annotation. By default it is None. | FontStyle | FreeTextSettings |
| height | Specifies the height of the annotation. | number | FreeTextSettings, HandwrittenSignatureSettings, InkAnnotationSettings, StampSettings |
| isAddToMenu | Specifies to maintain the newly added custom stamp element in the menu items. By default it is false. | boolean | StampSettings |
| isLock | If it is set as true, can't interact with annotation. Otherwise can interact with annotations. By default it is false. | boolean | AnnotationSettings, All annotation type settings |
| isPrint | Gets or sets the value for individual annotations to be included or not in print actions. | boolean | AnnotationSettings, All annotation type settings |
| leaderLength | Defines the leader length of the annotation. By default it is 40. | number | DistanceSettings |
| lineHeadEndStyle | Defines the head end style of the line annotation. | LineHeadStyle | AreaSettings, ArrowSettings, DistanceSettings, LineSettings |
| lineHeadStartStyle | Defines the head start style of the line annotation. | LineHeadStyle | AreaSettings, ArrowSettings, DistanceSettings, LineSettings |
| maxHeight | Sets the maximum height of annotations. It prevents the height of the annotation becoming larger than the values provided in MaxHeight. By default it is 0. | number | AnnotationSettings, All annotation type settings |
| maxWidth | Sets the maximum width of annotations. It prevents the width of the annotation becoming larger than values provided in MaxWidth. By default it is 0. | number | AnnotationSettings, All annotation type settings |
| minHeight | Sets the minimum height of annotations. It prevents the height of the annotation becoming smaller than values provided in MinHeight. By default it is 0. | number | AnnotationSettings, All annotation type settings |
| minWidth | Sets the minimum width of annotations. It prevents the width of the annotation becoming smaller than values provided in MinWidth. By default it is 0. | number | AnnotationSettings, All annotation type settings |
| opacity | Defines the opacity for the annotations. By default it is 1. It's range varies 0 to 1. | number | AnnotationSettings, All annotation type settings |
| scaleRatio | Defines the scale ratio for measuring annotation. By default it is 1. It will be multiplied the actual value of measurement and this multiplied value only displayed in UI. | number | MeasurementSettings |
| signStamps | Provide option to define the required sign stamp items to be displayed in annotation toolbar menu. | SignStampItem[] | StampSettings |
| skipDownload | If it is set as true, newly added annotations won't be included in downloaded file. By default it is false. | boolean | AnnotationSettings, All annotation type settings |
| skipPrint | If it is set as true, newly added annotations won't be included in printing. By default it is false. | boolean | AnnotationSettings, All annotation type settings |
| standardBusinessStamps | Provide option to define the required standard business stamp items to be displayed in annotation toolbar menu. | StandardBusinessStampItem[] | StampSettings |
| strokeColor | Defines the stroke color of the shape annotations. | string | AreaSettings, ArrowSettings, CircleSettings, DistanceSettings, HandwrittenSignatureSettings, InkAnnotationSettings, LineSettings, PerimeterSettings, PolygonSettings, RadiusSettings, RectangleSettings, StampSettings, VolumeSettings |
| subject | Specifies the subject of the annotation. | string | AnnotationSettings, All annotation type settings |
| textAlignment | Defines the text alignment for free text annotation. By default it is Left. | TextAlignment | FreeTextSettings |
| thickness | Defines the thickness of the shape annotations. By default it is 1. It's range varies 1 to 10. | number | AreaSettings, ArrowSettings, CircleSettings, DistanceSettings, HandwrittenSignatureSettings, InkAnnotationSettings, LineSettings, PerimeterSettings, PolygonSettings, RadiusSettings, RectangleSettings, StampSettings, VolumeSettings |
| width | Specifies the width of the annotation. | number | FreeTextSettings, HandwrittenSignatureSettings, InkAnnotationSettings, StampSettings |
AnnotationSelectorSettings
| Property Name | Description | Data Type |
|---|---|---|
| resizerBorderColor | Defines the annotation resizer border color. By default it is black. | string |
| resizerCursorType | Defines the annotation resizer Type. By default it is null. | CursorType |
| resizerFillColor | Defines the annotation resizer fill color. | string |
| resizerLocation | Defines the location for the resizer of the annotation. It is used to customize the resizer location of the annotation. | AnnotationResizerLocation |
| resizerShape | Defines the shape of the resizer. By default it is Square. Different shapes of resizer are circle and square. | AnnotationResizerShape |
| resizerSize | Defines the size of the resizer used for annotations. | number |
| selectionBorderColor | Defines the selection border color for the annotation. By default it is empty. It is used to customize the selection border color for the annotation. | string |
| selectionBorderThickness | Defines the selection border thickness for the annotation. By default it is 1. It is used to customize the selection border thickness for the annotation. It's range varies from 1 to 10. | number |
| selectorLineDashArray | Defines the selector line dash array. By default it is empty. | number[] |
CursorType
| Property Name | Description | Data Type |
|---|---|---|
| auto | Represents the default cursor type Auto. | enum |
| crossHair | Represents the cursor type CrossHair. | enum |
| e_resize | The cursor indicates that an edge of a box is to be moved right (east). | enum |
| ew_resize | Represents a bidirectional resize cursor. | enum |
| grab | Represents a grab cursor. | enum |
| grabbing | Represents a grabbing cursor. | enum |
| move | Represents a Move cursor when moving on something. | enum |
| n_resize | The cursor indicates that an edge of a box is to be moved up (north). | enum |
| ne_resize | The cursor indicates that an edge of a box is to be moved up and right (north/east). | enum |
| ns_resize | Represents a bidirectional resize cursor. | enum |
| nw_resize | The cursor indicates that an edge of a box is to be moved up and left (north/west). | enum |
| pointer | Represents Pointer cursor type. | enum |
| s_resize | The cursor indicates that an edge of a box is to be moved down (south). | enum |
| se_resize | The cursor indicates that an edge of a box is to be moved down and right (south/east). | enum |
| sw_resize | The cursor indicates that an edge of a box is to be moved down and left (south/west). | enum |
| text | The cursor indicates text that may be selected. | enum |
| w_resize | The cursor indicates that an edge of a box is to be moved left (west). | enum |
AnnotationResizerLocation
| Property Name | Description | Data Type |
|---|---|---|
| Corners | When resizing annotation, Resizer location is represented by corners. | enum |
| Edges | When resizing annotation, Resizer location is represented by Edges. | enum |
AnnotationResizerShape
| Property Name | Description | Data Type |
|---|---|---|
| Circle | Represent the Resizer shape by Circle when resizing annotations. | enum |
| Square | Represent the Resizer shape by Square when resizing annotations. | enum |
LineHeadStyle
| Name | Description | Data Type |
|---|---|---|
| Arrow | Represents the line with Arrow head style. | enum |
| Closed | Represents the line with closed head style. | enum |
| ClosedArrow | Represents the line with Closed Arrow head style. | enum |
| Diamond | Represents the line with diamond head style. | enum |
| None | Represents the line with no head style. | enum |
| Open | Represents the line with open arrow head style. | enum |
| OpenArrow | Represents the line with Open Arrow head style. | enum |
| Round | Represents the line with round head style. | enum |
| Square | Represents the line with square head style. | enum |
CustomStampSettings
| Name | Description | Data Type |
|---|---|---|
| customStampImageSource | Defines the custom stamp images source to be added in stamp menu of the PDF Viewer toolbar. | string |
| customStampName | Defines the custom stamp name to be added in stamp menu of the PDF Viewer toolbar. | string |
FontStyle
| Name | Description | Data Type |
|---|---|---|
| Bold | Represents the text content style will be bold. | enum |
| Italic | Represents the text content style will be italic. | enum |
| None | Represents the text content style does not set. | enum |
| Strikethrough | Represents the text content style will be strikethrough. | enum |
| Underline | Represents the text content style will be underline. | enum |
TextAlignment
| Name | Description | Data Type |
|---|---|---|
| Center | Represents the text alignment in Center. The text content will be shown at center. | enum |
| Justify | Represents the text alignment of Justify. The text is aligned along the left margin. | enum |
| Left | Represents the text alignment in left. The text content will be shown in left side. | enum |
| Right | Represents the text alignment in Right. The text content will be shown in right side. | enum |
CalibrationUnit
| Name | Description | Data Type |
|---|---|---|
| cm | Represents the unit of centimeter. | enum |
| ft | Represents the unit of feet. | enum |
| in | Represents the unit of inch. | enum |
| mm | Represents the unit of millimeter. | enum |
| p | Represents the unit of points. | enum |
| pt | Represents the unit of points. | enum |
DynamicStampItem
| Name | Description | Data Type |
|---|---|---|
| Approved | Represents a stamp indicating the document is approved. | enum |
| Confidential | Represents a stamp indicating the document is confidential. | enum |
| NotApproved | Represents a stamp indicating the document is not approved. | enum |
| Received | Represents a stamp indicating the document has been received. | enum |
| Reviewed | Represents a stamp indicating the document has been reviewed. | enum |
| Revised | Represents a stamp indicating the document has been revised. | enum |
SignStampItem
| Name | Description | Data Type |
|---|---|---|
| Accepted | Represents a stamp indicating the document is accepted. | enum |
| InitialHere | Represents a stamp indicating the initial placement here. | enum |
| Rejected | Represents a stamp indicating the document is rejected. | enum |
| SignHere | Represents a stamp indicating where the sign is needed. | enum |
| Witness | Represents a stamp indicating a witness is required. | enum |
StandardBusinessStampItem
| Name | Description | Data Type |
|---|---|---|
| Approved | Represents a stamp indicating the document is approved. | enum |
| Completed | Represents a stamp indicating the document is completed. | enum |
| Confidential | Represents a stamp indicating the document is confidential. | enum |
| Draft | Represents a stamp indicating the document is a draft. | enum |
| Final | Represents a stamp indicating the document is final. | enum |
| ForComment | Represents a stamp indicating the document is for comment. | enum |
| ForPublicRelease | Represents a stamp indicating the document is for public release. | enum |
| InformationOnly | Represents a stamp indicating the document is for information only. | enum |
| NotApproved | Represents a stamp indicating the document is not approved. | enum |
| NotForPublicRelease | Represents a stamp indicating the document is not for public release. | enum |
| PreliminaryResults | Represents a stamp indicating the document contains preliminary results. | enum |
| Void | Represents a stamp indicating the document is void. | enum |
API Methods in React PdfViewer Component
When user requests programmatic control beyond UI interactions, guide them to these API methods. This reference helps you recommend the right method based on user goals: loading documents, managing form fields, handling annotations, exporting data, or manipulating viewer state.
Your role: Match user intent to appropriate API methods, explain when to use each method, and provide complete working examples.
Table of Contents
- When to Use These APIs
- API Categories
- Complete API Reference
- Common Parameter Types
- Usage Examples by Scenario
When to Use These APIs
Guide user to these methods when they express these needs:
- "Load a PDF programmatically" → Use
load()andunload()methods - "Process form data from PDF" → Use
exportFormFieldsAsObject()orimportFormFields() - "Add/edit PDF annotations dynamically" → Use
addAnnotation(),deleteAnnotations(),exportAnnotation() - "Extract text from PDF" → Use
extractText()with bounds parameter - "Implement undo/redo for PDF edits" → Use
undo()andredo()methods - "Respond to layout changes" → Use
updateViewerContainer()after resize - "Navigate to specific coordinates" → Use
zoomToRect()or coordinate conversion methods
Alternative approaches: If user needs simple page navigation or UI interactions, refer to navigation.md or events.md instead of programmatic APIs.
API Categories
When user describes their goal, identify which category fits best, then recommend specific methods:
| Category | Methods | When to Recommend |
|---|---|---|
| Document Loading | load, unload | User wants to open PDF from URL/Blob or close current document (e.g., "switch between multiple PDFs", "clear viewer") |
| Document Operations | download, extractPages, saveAsBlob | User needs to save modified PDF, extract specific pages, or get PDF as Blob for upload (e.g., "let user download annotated PDF", "extract pages 1-5") |
| Form Fields | updateFormFields, updateFormFieldsValue, clearFormFields, resetFormFields, retrieveFormFields, focusFormField, importFormFields, exportFormFields, exportFormFieldsAsObject, addFormField, updateFormField, deleteFormField, selectFormField, resetFormField, setFormFieldMode, clearSelection, getRgbToHex | User works with fillable PDF forms - needs to pre-fill, validate, export, clear field data, or create form fields programmatically (e.g., "populate form from database", "dynamically add textbox", "create dropdown") |
| Annotations | addAnnotation, deleteAnnotations, exportAnnotation, exportAnnotationsAsBase64String, exportAnnotationsAsObject, importAnnotation, selectAnnotation, editAnnotation, setAnnotationMode, clearSelection, hexToRgba | User wants to add/remove/save PDF markup, manage annotations programmatically, set drawing mode (e.g., "save annotations", "highlight search results", "enable rectangle drawing mode") |
| Navigation | getPageNumberFromClientPoint, getPageInfo, zoomToRect, convertClientPointToPagePoint, convertPagePointToClientPoint, convertPagePointToScrollingPoint | User needs programmatic zoom or coordinate-based navigation (e.g., "zoom to search result", "highlight region at coordinates") |
| Text Extraction | extractText | User wants to extract text from specific PDF region for processing (e.g., "OCR alternative", "copy text from bounds") |
| State Management | undo, redo, setJsonData, destroy, updateViewerContainer | User needs undo/redo functionality, viewer cleanup, or layout refresh (e.g., "undo last annotation", "update viewer after resize") |
| UI Customization | addCustomMenu, showNotificationPopup | User wants custom context menu items or in-viewer notifications (e.g., "add 'Send to Email' menu option", "show save confirmation") |
Complete API Reference
How to use this reference: When user describes what they want to do, scan this table for matching methods. Then provide complete code examples with error handling and explain why that method fits their use case.
The table below lists all available methods - use it to recommend the right API based on user intent, not as copy-paste reference material.
List of Methods
| Method Name | Description | Parameters | Return Type | Code Snippet |
|---|---|---|---|---|
| addAnnotation | Adds annotations programmatically with specific annotation type and options | annotationType: AnnotationType, options?: AnnotationSettings | void | pdfViewerRef.current?.annotation.addAnnotation('Highlight', {bounds: {x: 100, y: 100, width: 200, height: 50}}); |
| addCustomMenu | Adds a custom menu item to the context menu of the PDF viewer | items: CustomToolbarItem[], targetId: string | void | pdfViewerRef.current?.addCustomMenu([{id: 'custom1', text: 'Custom Item'}], 'targetId'); |
| addFormField | Adds form field to the PDF page programmatically | formFieldType: FormFieldType, options?: FormFieldSettings | HTMLElement | pdfViewerRef.current?.formDesigner.addFormField('Textbox', {name: 'field1', bounds: {x: 100, y: 100, width: 200, height: 30}}); |
| clearFormFields | Clears all form field values in the PDF document | - | void | pdfViewerRef.current?.clearFormFields(); |
| convertClientPointToPagePoint | Converts a client point (screen coordinates) to page point coordinates | clientPoint: IPoint | IPoint | const pagePoint = pdfViewerRef.current?.convertClientPointToPagePoint({x: 100, y: 200}); |
| convertPagePointToClientPoint | Converts a page point to client point (screen coordinates) | pagePoint: IPoint | IPoint | const clientPoint = pdfViewerRef.current?.convertPagePointToClientPoint({x: 50, y: 75}); |
| convertPagePointToScrollingPoint | Converts a page point to scrolling point coordinates within the viewport | pagePoint: IPoint | IPoint | const scrollPoint = pdfViewerRef.current?.convertPagePointToScrollingPoint({x: 50, y: 75}); |
| deleteAnnotations | Deletes specified annotations from the PDF document | annotationId: string | void | pdfViewerRef.current?.deleteAnnotations('annotation-id-123'); |
| destroy | Destroys the PdfViewer component and releases its resources | - | void | pdfViewerRef.current?.destroy(); |
| download | Downloads the current PDF document to the client machine | - | void | pdfViewerRef.current?.download(); |
| exportAnnotation | Exports annotations from the PDF document as a string in JSON format | - | string | const annotations = pdfViewerRef.current?.exportAnnotation(); |
| exportAnnotationsAsBase64String | Exports annotations from the PDF document as a Base64 encoded string | - | string | const base64Annotations = pdfViewerRef.current?.exportAnnotationsAsBase64String(); |
| exportAnnotationsAsObject | Exports annotations from the PDF document as a JSON object | - | object | const annotationsObj = pdfViewerRef.current?.exportAnnotationsAsObject(); |
| exportFormFields | Exports form fields data from the PDF document as XML string | - | string | const formFieldsXml = pdfViewerRef.current?.exportFormFields(); |
| exportFormFieldsAsObject | Exports form fields data from the PDF document as a JSON object | - | object | const formFieldsObj = pdfViewerRef.current?.exportFormFieldsAsObject(); |
| extractPages | Extracts specified pages from the PDF document | pageIndexes: number[] | void | pdfViewerRef.current?.extractPages([0, 1, 2]); |
| extractText | Extracts text from the PDF document based on the selection region | bounds: IRect | string | const text = pdfViewerRef.current?.extractText({x: 0, y: 0, width: 100, height: 100}); |
| clearSelection | Clears the selection of the annotation or form field | formFieldId?: `string \ | object` | void |
| deleteFormField | Deletes the form field from the PDF page | formFieldId: `string \ | object, addAction: boolean` | void |
| editAnnotation | Updates existing properties of the specified annotation object | annotation: any | void | pdfViewerRef.current?.annotation.editAnnotation({id: 'annot-123', color: 'red', opacity: 0.8}); |
| focusFormField | Sets focus to a specific form field in the PDF document | fieldName: string | void | pdfViewerRef.current?.focusFormField('fieldName'); |
| getPageInfo | Retrieves information about a specific page in the PDF document | pageIndex: number | PageInfo | const pageInfo = pdfViewerRef.current?.getPageInfo(0); |
| getPageNumberFromClientPoint | Gets the page number at a specific client point (screen coordinates) | clientPoint: IPoint | number | const pageNum = pdfViewerRef.current?.getPageNumberFromClientPoint({x: 100, y: 200}); |
| getRgbToHex | Gets the Hex value from the RGB value | color: any | string | const hexColor = pdfViewerRef.current?.formDesigner.getRgbToHex({r: 255, g: 87, b: 51}); |
| hexToRgba | Converts a hex color string to an RGBA color string | hex: string | string | const rgba = pdfViewerRef.current?.annotation.hexToRgba('#FF5733'); |
| importAnnotation | Imports annotations into the PDF document from a JSON string | annotationData: string | void | pdfViewerRef.current?.importAnnotation(jsonAnnotationString); |
| importFormFields | Imports form field data into the PDF document from XML format | formFieldData: string | void | pdfViewerRef.current?.importFormFields(xmlFormFieldData); |
| load | Loads a PDF document from a specified URL or file path | document: `string \ | Blob` | void |
| redo | Redoes the last undone action in the PDF viewer | - | void | pdfViewerRef.current?.redo(); |
| resetFormField | Resets the form field to its original state | formFieldId: `string \ | object` | void |
| resetFormFields | Resets all form field values to their default values | - | void | pdfViewerRef.current?.resetFormFields(); |
| retrieveFormFields | Retrieves all form field data from the PDF document | - | FormField[] | const formFields = pdfViewerRef.current?.retrieveFormFields(); |
| saveAsBlob | Saves the current PDF document as a Blob object | - | Blob | const blob = pdfViewerRef.current?.saveAsBlob(); |
| selectAnnotation | Selects annotations using annotation object or annotation ID | annotationId: `string \ | object` | void |
| selectFormField | Selects the form field in the PDF Viewer | formFieldId: `string \ | object` | void |
| setAnnotationMode | Sets annotation type to be added in next user interaction | type: AnnotationType | void | pdfViewerRef.current?.annotation.setAnnotationMode('Rectangle'); |
| setFormFieldMode | Sets the form field mode to add form field on user interaction | formFieldType: FormFieldType | void | pdfViewerRef.current?.formDesigner.setFormFieldMode('Textbox'); |
| setJsonData | Sets JSON data for the PDF viewer configuration and state | jsonData: string | void | pdfViewerRef.current?.setJsonData(jsonConfigString); |
| showNotificationPopup | Displays a notification popup message in the PDF viewer | message: string, timeout?: number | void | pdfViewerRef.current?.showNotificationPopup('Success!', 3000); |
| undo | Undoes the last action performed in the PDF viewer | - | void | pdfViewerRef.current?.undo(); |
| unload | Unloads the currently loaded PDF document from the viewer | - | void | pdfViewerRef.current?.unload(); |
| updateFormField | Updates the form field with the given properties and value | formFieldId: `string \ | object, options: FormFieldSettings` | void |
| updateFormFields | Updates specific form fields in the PDF document | formFields: FormField[] | void | pdfViewerRef.current?.updateFormFields([{name: 'field1', value: 'newValue'}]); |
| updateFormFieldsValue | Updates the values of form fields in the PDF document | fieldName: string, fieldValue: string | void | pdfViewerRef.current?.updateFormFieldsValue('fieldName', 'newValue'); |
| updateViewerContainer | Updates the PDF viewer container size and layout | - | void | pdfViewerRef.current?.updateViewerContainer(); |
| zoomToRect | Zooms the PDF viewer to fit a specific rectangular region | rect: IRect | void | pdfViewerRef.current?.zoomToRect({x: 0, y: 0, width: 200, height: 300}); |
Common Parameter Types
When constructing method calls, guide user on parameter structure. Many methods require specific object types - reference these schemas when building examples.
⚠️ CRITICAL: Bounds Format Differs Between Annotations and Form Fields
IMPORTANT - These two APIs have DIFFERENT bounds property casing:
Annotations – bounds (lowercase):
pdfViewerRef.current?.annotation.addAnnotation('Rectangle', {
bounds: { x: 100, y: 100, width: 200, height: 50 }
});Form Fields – bounds (capitalized):
pdfViewerRef.current?.formDesigner.addFormField('Textbox', {
bounds: { X: 100, Y: 100, Width: 200, Height: 30 }
});Do NOT mix or interchange these formats - each API expects its specific casing
---
IPoint
When to use: Methods involving coordinates (click detection, point conversion). Used for coordinate points in the PDF viewer.
| Property | Description | Data Type |
|---|---|---|
| x | The x-coordinate value | number |
| y | The y-coordinate value | number |
IRect
When to use: Methods involving regions (text extraction, zoom to area). Used for rectangular regions in the PDF document.
| Property | Description | Data Type |
|---|---|---|
| x | The x-coordinate of the top-left corner | number |
| y | The y-coordinate of the top-left corner | number |
| width | The width of the rectangle | number |
| height | The height of the rectangle | number |
PageInfo
When to use: Returned by getPageInfo() - use for dynamic layout calculations. Contains information about a specific page in the PDF document.
| Property | Description | Data Type |
|---|---|---|
| pageNumber | The page number. It starts from the 1 and it is not a index based. | number |
| width | The width of the page | number |
| height | The height of the page | number |
| rotation | The rotation angle of the page | number |
FormField
When to use: Working with form field methods (retrieve, update, export). Represents a form field in the PDF document.
| Property | Description | Data Type |
|---|---|---|
| name | The name of the form field | string |
| value | The current value of the form field | string |
| fieldType | The type of form field (text, checkbox, radio, etc.) | string |
PdfAnnotationBase
When to use: Required parameter for addAnnotation() method. Base class for PDF annotations.
| Property | Description | Data Type |
|---|---|---|
| annotationType | The type of annotation | string |
| pageIndex | The page index where annotation is placed | number |
| bounds | The bounds of the annotation | IRect |
CustomToolbarItem
When to use: Required parameter for addCustomMenu() method. Represents a custom toolbar menu item.
| Property | Description | Data Type |
|---|---|---|
| id | Unique identifier for the menu item | string |
| text | Display text for the menu item | string |
| tooltipText | Tooltip text for the menu item | string |
AnnotationType
When to use: Used with annotation module methods to specify annotation types. Valid annotation types include:
'None'- No annotation'Highlight'- Text highlight annotation'Underline'- Text underline annotation'Strikethrough'- Text strikethrough annotation'Squiggly'- Text squiggly underline annotation'Line'- Line annotation'Arrow'- Arrow annotation'Rectangle'- Rectangle shape annotation'Circle'- Circle shape annotation'Polygon'- Polygon shape annotation'Distance'- Distance measurement annotation'Perimeter'- Perimeter measurement annotation'Area'- Area measurement annotation'Radius'- Radius measurement annotation'Volume'- Volume measurement annotation'FreeText'- Free text annotation'HandWrittenSignature'- Handwritten signature annotation'Ink'- Ink annotation (freehand drawing)'Stamp'- Stamp annotation'Image'- Image stamp annotation'StickyNotes'- Sticky notes annotation
AnnotationSettings
When to use: Optional parameter for annotation.addAnnotation() to customize annotation properties. Annotation settings object can include:
| Property | Description | Data Type |
|---|---|---|
| bounds | The bounds of the annotation | IRect |
| pageNumber | The page number where annotation is placed. It starts from the 1 and it is not a index based. | number |
| author | Author of the annotation | string |
| subject | Subject of the annotation | string |
| note | Note/comment text | string |
| color | Color of the annotation | string |
| opacity | Opacity value (0-1) | number |
| strokeColor | Stroke color for shapes | string |
| fillColor | Fill color for shapes | string |
| thickness | Line/border thickness | number |
| fontSize | Font size for text annotations | number |
| fontFamily | Font family for text annotations | string |
| path | SVG path data for Ink annotations (array of point commands: M for move, L for line) | string |
FormFieldType
When to use: Used with form designer module methods to specify form field types. Valid form field types include:
'Textbox'- Text input field'Password'- Password input field'Checkbox'- Checkbox field'RadioButton'- Radio button field'DropDown'- Dropdown list field'ListBox'- List box field'SignatureField'- Signature field'InitialField'- Initial field
FormFieldSettings
When to use: Used with form designer methods to configure form field properties. Form field settings object can include:
| Property | Description | Data Type |
|---|---|---|
| name | Name of the form field | string |
| bounds | The bounds of the form field | IRect |
| value | Default value of the form field | string |
| fontFamily | Font family for the field | string |
| fontSize | Font size for the field | number |
| fontStyle | Font style (Bold, Italic, etc.) | string |
| color | Text color | string |
| backgroundColor | Background color | string |
| borderColor | Border color | string |
| thickness | Border thickness | number |
| alignment | Text alignment | string |
| isReadOnly | Whether field is read-only | boolean |
| visibility | Visibility of the field | string |
| maxLength | Maximum length for text fields | number |
| isRequired | Whether field is required | boolean |
| isPrint | Whether field should be printed | boolean |
| tooltip | Tooltip text | string |
| options | Options for dropdown/listbox | Item[] |
| isChecked | Checked state for checkbox/radio | boolean |
| isSelected | Selected state for radio button | boolean |
CustomStamp
When to use: Used to define custom stamp images for the PDF Viewer. Custom stamp object structure:
| Property | Description | Data Type |
|---|---|---|
| customStampName | Name of the custom stamp | string |
| customStampImageSource | Base64 encoded image source | string |
AnnotationDrawingOptions
When to use: Used to configure annotation drawing behavior with angular constraints. Annotation drawing options object:
| Property | Description | Data Type |
|---|---|---|
| enableLineAngleConstraints | Enables angular constraints for line-type annotations | boolean |
| restrictLineAngleTo | Angle in degrees to constrain line annotations | number |
Usage Examples by Scenario
Use these patterns when user describes matching scenarios. Provide complete examples with error handling and explain why this approach fits their needs.
Scenario 1: Load and Download PDF
When: User needs to open a PDF file and allow downloading it.
Why: Use load() for dynamic document switching and download() to save modified PDFs client-side without server roundtrip.
// Load a PDF document
pdfViewerRef.current?.load('loaded document.pdf');
// Later, allow user to download
pdfViewerRef.current?.download();Scenario 2: Manage Interactive Form Fields
When: Working with fillable PDFs that have form fields (text inputs, checkboxes).
Why: Use retrieveFormFields() to read current state, updateFormFieldsValue() for programmatic pre-fill (e.g., from database), and exportFormFieldsAsObject() for structured data submission.
// Retrieve all form fields
const formFields = pdfViewerRef.current?.retrieveFormFields();
// Update specific field values
pdfViewerRef.current?.updateFormFieldsValue('firstName', 'John');
pdfViewerRef.current?.updateFormFieldsValue('email', 'john@example.com');
// Export filled form data
const formData = pdfViewerRef.current?.exportFormFieldsAsObject();
console.log(formData);Scenario 3: Work with Annotations
When: Adding comments, highlights, or other markup to PDFs.
Why: Use exportAnnotation() to save user markup for later sessions, importAnnotation() to restore saved annotations, and deleteAnnotations() for programmatic cleanup.
// Export current annotations
const annotations = pdfViewerRef.current?.exportAnnotation();
// Import previously saved annotations
pdfViewerRef.current?.importAnnotation(annotationJSON);
// Delete specific annotation
pdfViewerRef.current?.deleteAnnotations('annotation-id-123');Scenario 4: Extract Text from PDF
When: You need to get text content from a specific region.
Why: Use extractText() with bounds parameter for targeted text extraction - ideal for processing specific fields, copying text from coordinates, or building search/highlight features.
// Extract text from a rectangular region
const bounds = { x: 100, y: 150, width: 200, height: 100 };
const extractedText = pdfViewerRef.current?.extractText(bounds);
console.log('Extracted:', extractedText);Scenario 5: Navigate and Zoom
When: Programmatically moving to specific pages or zooming regions.
Why: Use getPageInfo() for dynamic layout calculations and zoomToRect() to focus on specific regions (e.g., highlighting search results, focusing on form fields).
// Get page information
const pageInfo = pdfViewerRef.current?.getPageInfo(0);
console.log('Page dimensions:', pageInfo?.width, pageInfo?.height);
// Zoom to specific rectangular area
const rect = { x: 50, y: 50, width: 300, height: 300 };
pdfViewerRef.current?.zoomToRect(rect);Scenario 6: Implement Undo/Redo
When: Allowing users to undo/redo annotations or form changes.
Why: Use undo() and redo() to provide familiar editing experience - essential for annotation workflows where users need to revert mistakes.
// User clicks undo button
pdfViewerRef.current?.undo();
// User clicks redo button
pdfViewerRef.current?.redo();Scenario 7: Custom UI Integration
When: Adding custom menu items or notifications.
Why: Use addCustomMenu() to extend context menu with app-specific actions (e.g., "Send to Email", "Share") and showNotificationPopup() for in-viewer feedback without blocking dialogs.
// Add custom context menu item
const customItems = [
{ id: 'custom-1', text: 'My Action', tooltipText: 'Do something custom' }
];
pdfViewerRef.current?.addCustomMenu(customItems, 'target-element-id');
// Show notification
pdfViewerRef.current?.showNotificationPopup('PDF loaded successfully', 3000);Scenario 8: Programmatic Annotation Management
When: You need to add, select, edit, or manage annotations programmatically without user interaction.
Why: Use the annotation module methods to create annotations dynamically (e.g., highlighting search results), programmatically select/edit annotations, or set annotation mode for user drawing.
- Note: Pagenumber is starts from 1.
// Add a highlight annotation programmatically
pdfViewerRef.current?.annotation.addAnnotation('Highlight', {
bounds: { x: 100, y: 100, width: 200, height: 50 },
pageNumber: 0,color: '#FFFF00',opacity: 0.5,author: 'System',
subject: 'Auto-highlight',note: 'Important section'
});
// Select an existing annotation by ID
pdfViewerRef.current?.annotation.selectAnnotation('annotation-id-123');
// Edit an existing annotation's properties
pdfViewerRef.current?.annotation.editAnnotation({
id: 'annotation-id-123',color: '#FF0000',opacity: 0.8, note: 'Updated comment'
});
// Set annotation mode for user to add rectangles
pdfViewerRef.current?.annotation.setAnnotationMode('Rectangle');
// Clear current annotation selection
pdfViewerRef.current?.annotation.clearSelection();
// Convert color formats
const rgbaColor = pdfViewerRef.current?.annotation.hexToRgba('#FF5733');
console.log('RGBA Color:', rgbaColor);Ink Annotation with Path Points (Freehand Drawing):
const viewer = getViewer();
// Add ink annotation with SVG path data representing freehand drawing
viewer?.annotation.addAnnotation('Ink', {
offset: { x: 150, y: 100 }, pageNumber: 1, width: 200, height: 60,
path: '[{"command":"M","x":244.83,"y":982.00},{"command":"L","x":250.83,"y":953.33},{"command":"L","x":260.83,"y":920.33}]', strokeColor: '#0000FF', thickness: 2,opacity: 1, author: 'User'
});Scenario 9: Dynamic Form Field Creation and Management
When: Creating fillable PDF forms programmatically or modifying existing form fields.
Why: Use the formDesigner module to dynamically add form fields (textboxes, checkboxes, dropdowns), select/modify form fields, or enable form field drawing mode.
// Add a textbox form field programmatically
const textboxElement = pdfViewerRef.current?.formDesigner.addFormField('Textbox', {
name: 'firstName', bounds: { x: 100, y: 100, width: 200, height: 30 },
value: '', fontSize: 12,fontFamily: 'Helvetica',color: '#000000', backgroundColor: '#FFFFFF',
borderColor: '#000000', thickness: 1,isRequired: true,tooltip: 'Enter your first name'
});
// Add a checkbox form field
pdfViewerRef.current?.formDesigner.addFormField('Checkbox', {
name: 'agreeTerms',bounds: { x: 100, y: 150, width: 20, height: 20 }, isChecked: false,
borderColor: '#000000',backgroundColor: '#FFFFFF'
});
// Add a dropdown form field with options
pdfViewerRef.current?.formDesigner.addFormField('DropDown', {
name: 'country', bounds: { x: 100, y: 200, width: 200, height: 30 },
options: [
{ itemName: 'USA', itemValue: 'us' }, { itemName: 'Canada', itemValue: 'ca' }, { itemName: 'UK', itemValue: 'uk' }
], fontSize: 12, fontFamily: 'Helvetica'
});
// Select a form field for editing
pdfViewerRef.current?.formDesigner.selectFormField('firstName');
// Update existing form field properties
pdfViewerRef.current?.formDesigner.updateFormField('firstName', {
backgroundColor: '#FFFF00',
fontSize: 14,
value: 'John'
});
// Reset a form field to original state
pdfViewerRef.current?.formDesigner.resetFormField('firstName');
// Delete a form field
pdfViewerRef.current?.formDesigner.deleteFormField('firstName', true);
// Set form field mode for user to add textboxes
pdfViewerRef.current?.formDesigner.setFormFieldMode('Textbox');
// Clear form field selection
pdfViewerRef.current?.formDesigner.clearSelection('firstName');
// Convert RGB to Hex color
const hexColor = pdfViewerRef.current?.formDesigner.getRgbToHex({r: 255, g: 87, b: 51});
console.log('Hex Color:', hexColor);Scenario 10: Custom Stamps Configuration
When: Adding custom stamp images to the PDF Viewer stamp menu.
Why: Use custom stamps to provide organization-specific stamps (company logo, approval stamps, etc.) that users can add to PDFs.
function App() {
const customStamps = [
{
customStampName: 'Approved', customStampImageSource: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...'
},
{
customStampName: 'Confidential', customStampImageSource: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...'
}
];
return (
<PdfViewerComponent customStamp={customStamps}/>
);
}Scenario 11: Annotation Drawing with Angular Constraints
When: You want to restrict line and arrow annotations to specific angles for precise diagrams.
Why: Use annotationDrawingOptions to enable angular constraints, making it easier to draw perfectly horizontal, vertical, or angled lines.
function App() {
const annotationDrawingOptions = {
enableLineAngleConstraints: true,
restrictLineAngleTo: 45 // Lines snap to 0°, 45°, 90°, 135°, etc.
};
return (
<PdfViewerComponent annotationDrawingOptions={annotationDrawingOptions}/>
);
}---
Bookmark Navigation
Brief: Bookmark navigation enables users to navigate through embedded PDF bookmarks. The React PDF Viewer automatically loads and presents bookmarks for easy document traversal.
⚠️ CRITICAL: Correct API Usage
ALL bookmark methods MUST be accessed via `pdfViewerRef.current.bookmark` module:
// ✅ CORRECT - Access via bookmark module
pdfViewerRef.current.bookmark.openBookmarkPane();
pdfViewerRef.current.bookmark.closeBookmarkPane();
pdfViewerRef.current.bookmark.getBookmarks();
pdfViewerRef.current.bookmark.goToBookmark(pageIndex, y);
// ❌ WRONG - These methods DO NOT exist on pdfViewerRef.current
pdfViewerRef.current.openBookmarkPanel(); // ❌ NOT A VALID METHOD
pdfViewerRef.current.closeBookmarkPanel(); // ❌ NOT A VALID METHOD
pdfViewerRef.current.openBookmarkPane(); // ❌ WRONG - Missing .bookmark
pdfViewerRef.current.closeBookmarkPane(); // ❌ WRONG - Missing .bookmarkTable of Contents
- When to Use
- Prerequisites
- Enabling Bookmarks
- API Methods
- Complete Examples
- Bookmark Data Structure
- Best Practices
When to Use
Use bookmarks when:
- Jump to specific sections in long PDFs (reports, manuals, specifications)
- Navigate document hierarchy without manual scrolling
- Display table of contents extracted from PDF
- Build custom navigation UIs beyond default sidebar
Skip bookmarks if PDF has no embedded bookmarks or only needs simple page navigation.
Prerequisites
Before using bookmark features, ensure:
enableBookmark={true}is set on the PdfViewerComponentBookmarkViewservice is injected into the component- The PDF document contains embedded bookmarks (many don't)
Enabling Bookmarks
<PdfViewerComponent
ref={viewerRef}
enableBookmark={true}
documentPath="document.pdf"
>
<Inject services={[BookmarkView]} />
</PdfViewerComponent>What happens: Bookmarks load automatically, sidebar panel appears with hierarchy, and all bookmark API methods become available.
API Methods
1. openBookmarkPane()
Signature: pdfViewerRef.current.bookmark.openBookmarkPane(): void
Opens the bookmark panel in the left sidebar.
const openBookmark = () => {
if (viewerRef.current && viewerRef.current.bookmark) {
viewerRef.current.bookmark.openBookmarkPane();
}
};2. closeBookmarkPane()
Signature: pdfViewerRef.current.bookmark.closeBookmarkPane(): void
Closes the bookmark panel.
const closeBookmark = () => {
if (viewerRef.current && viewerRef.current.bookmark) {
viewerRef.current.bookmark.closeBookmarkPane();
}
};3. getBookmarks()
Signature: pdfViewerRef.current.bookmark.getBookmarks(): any
Retrieves all bookmarks as hierarchical array. Returns [] if no bookmarks exist.
const [bookmarks, setBookmarks] = React.useState([]);
React.useEffect(() => {
const timer = setTimeout(() => {
if (viewerRef.current && viewerRef.current.bookmark) {
const allBookmarks = viewerRef.current.bookmark.getBookmarks();
setBookmarks(allBookmarks || []);
}
}, 1000); // Wait for PDF to load
return () => clearTimeout(timer);
}, []);4. goToBookmark()
Signature: pdfViewerRef.current.bookmark.goToBookmark(pageIndex: number, y: number): boolean
Navigates to specific page and Y coordinate. Returns true if successful.
Parameters:
pageIndex(number): Zero-based page index (0 = first page)y(number): Vertical pixel coordinate (0 = top of page)
const navigateToBookmark = (bookmark) => {
if (viewerRef.current && viewerRef.current.bookmark) {
const success = viewerRef.current.bookmark.goToBookmark(bookmark.page, bookmark.y);
if (!success) {
console.error('Navigation failed');
}
}
};Complete Examples
Example 1: Open/Close Buttons
import { useRef } from 'react';
import { PdfViewerComponent, Inject, BookmarkView } from '@syncfusion/ej2-react-pdfviewer';
export function App() {
const viewerRef = useRef(null);
const openBookmark = () => {
if (viewerRef.current && viewerRef.current.bookmark) {
viewerRef.current.bookmark.openBookmarkPane();
}
};
const closeBookmark = () => {
if (viewerRef.current && viewerRef.current.bookmark) {
viewerRef.current.bookmark.closeBookmarkPane();
}
};
return (
<div>
<div style={{ marginBottom: '10px' }}>
<button onClick={openBookmark} style={{ marginRight: '10px' }}>
Open Bookmarks
</button>
<button onClick={closeBookmark}>
Close Bookmarks
</button>
</div>
<PdfViewerComponent
ref={viewerRef}
documentPath="https://cdn.syncfusion.com/content/pdf/pdf-succinctly.pdf"
enableBookmark={true}
style={{ height: '640px' }}
>
<Inject services={[BookmarkView]} />
</PdfViewerComponent>
</div>
);
}Example 2: Toggle Button
const [isPaneOpen, setIsPaneOpen] = React.useState(false);
const toggleBookmarks = () => {
if (viewerRef.current && viewerRef.current.bookmark) {
if (isPaneOpen) {
viewerRef.current.bookmark.closeBookmarkPane();
} else {
viewerRef.current.bookmark.openBookmarkPane();
}
setIsPaneOpen(!isPaneOpen);
}
};
<button onClick={toggleBookmarks}>
{isPaneOpen ? 'Hide Bookmarks' : 'Show Bookmarks'}
</button>Example 3: Auto-Open on Load
const handleDocumentLoad = () => {
if (viewerRef.current && viewerRef.current.bookmark) {
viewerRef.current.bookmark.openBookmarkPane();
}
};
<PdfViewerComponent
ref={viewerRef}
documentPath="document.pdf"
enableBookmark={true}
documentLoad={handleDocumentLoad}
>
<Inject services={[BookmarkView]} />
</PdfViewerComponent>Example 4: Custom Bookmark Sidebar
const [bookmarks, setBookmarks] = React.useState([]);
React.useEffect(() => {
const timer = setTimeout(() => {
if (viewerRef.current && viewerRef.current.bookmark) {
const allBookmarks = viewerRef.current.bookmark.getBookmarks();
setBookmarks(allBookmarks || []);
}
}, 1000);
return () => clearTimeout(timer);
}, []);
const handleBookmarkClick = (bookmark) => {
if (viewerRef.current && viewerRef.current.bookmark) {
viewerRef.current.bookmark.goToBookmark(bookmark.page, bookmark.y);
}
};
return (
<div style={{ display: 'flex', height: '100vh' }}>
<div style={{ width: '250px', overflowY: 'auto' }}>
<h3>Table of Contents</h3>
{bookmarks.length > 0 ? (
<ul>
{bookmarks.map((bm, i) => (
<li key={i}>
<button onClick={() => handleBookmarkClick(bm)}>
{bm.title}
</button>
</li>
))}
</ul>
) : (
<p>No bookmarks</p>
)}
</div>
<div style={{ flex: 1 }}>
<PdfViewerComponent
ref={viewerRef}
documentPath="document.pdf"
enableBookmark={true}
>
<Inject services={[BookmarkView]} />
</PdfViewerComponent>
</div>
</div>
);Bookmark Data Structure
Each bookmark object returned by getBookmarks() has:
| Property | Type | Description | Example |
|---|---|---|---|
| title | string | Display name | "Chapter 1" |
| page | number | Zero-based page index | 0 (first page) |
| y | number | Vertical Y coordinate | 150 |
| children | array | Nested sub-bookmarks | [{title: "Section 1.1", ...}] |
[
{
title: "Chapter 1",
page: 0,
y: 150,
children: [
{ title: "Section 1.1", page: 2, y: 200, children: [] },
{ title: "Section 1.2", page: 5, y: 100, children: [] }
]
},
{
title: "Chapter 2",
page: 10,
y: 50,
children: []
}
]Bookmark Properties
The following property is available on the PdfViewerComponent to control bookmark panel state:
| Property Name | Description | Type | Default Value |
|---|---|---|---|
| isBookmarkPanelOpen | Get or set whether the bookmark panel is open. | boolean | false |
Usage Example
<PdfViewerComponent
ref={viewerRef}
enableBookmark={true}
isBookmarkPanelOpen={true}
documentPath="document.pdf"
>
<Inject services={[BookmarkView]} />
</PdfViewerComponent>When to use `isBookmarkPanelOpen`:
- Programmatically open the bookmark panel on document load
- Control panel visibility based on document type or user preferences
- Set default panel state for specific workflows
- Implement custom bookmark panel toggle buttons
Example - Auto-open bookmarks for long documents:
const handleDocumentLoad = () => {
if (viewerRef.current.pageCount > 30) {
// Auto-open bookmark panel for documents with more than 30 pages
viewerRef.current.isBookmarkPanelOpen = true;
}
};
<PdfViewerComponent
ref={viewerRef}
enableBookmark={true}
documentLoad={handleDocumentLoad}
>
<Inject services={[BookmarkView]} />
</PdfViewerComponent>---
Best Practices
1. Always validate references before calling methods:
if (viewerRef.current && viewerRef.current.bookmark) {
viewerRef.current.bookmark.openBookmarkPane();
}2. Wait for PDF to load before accessing bookmarks:
- Use
setTimeout(1-1.5s delay) ordocumentLoadevent
React.useEffect(() => {
const timer = setTimeout(() => {
const bookmarks = viewerRef.current?.bookmark.getBookmarks();
setBookmarks(bookmarks || []);
}, 1000);
return () => clearTimeout(timer);
}, []);3. Handle PDFs with no bookmarks gracefully:
getBookmarks()returns[]if no bookmarks exist
{bookmarks.length > 0 ? renderBookmarks() : <p>No bookmarks</p>}4. Cache bookmarks in state:
- Call
getBookmarks()once on load, store inuseState, reuse
5. Validate data before navigation:
if (typeof bookmark.page === 'number' && typeof bookmark.y === 'number') {
viewerRef.current.bookmark.goToBookmark(bookmark.page, bookmark.y);
}