
Syncfusion Javascript Pdf Viewer
- 1 installs
- 1 repo stars
- Updated July 6, 2026
- syncfusion/pdf-viewer-sdk-skills
Generates TypeScript (EJ2 class-based) and HTML code to embed and configure the Syncfusion PdfViewer for rendering PDF documents.
About
Generates TypeScript and HTML code using the Syncfusion EJ2 class-based PdfViewer to render and interact with PDFs. A developer uses it when embedding a PDF viewer in a TypeScript EJ2 project.
- Uses the @syncfusion/ej2-pdfviewer package
- Detects app type and enforces reference-file-only code generation
Syncfusion Javascript Pdf Viewer by the numbers
- 1 all-time installs (skills.sh)
- Ranked #1,912 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-javascript-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 TypeScript (EJ2 class-based) and HTML code to embed and configure the Syncfusion PdfViewer for rendering PDF documents.
Files
Syncfusion TypeScript PdfViewer – UI Sample Generator
Generate Code for the User's Project (default)
Trigger keywords: "how to", "add pdfviewer", "code sample", "show me", "example", "snippet", "integrate", "component", "create sample", "typescript sample".
Purpose: Generate minimal, copy-pasteable TypeScript (.ts) and HTML code that the user can integrate directly into their TypeScript EJ2 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 TypeScript 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(check for@syncfusion/ej2-pdfvieweror@syncfusion/ej2dependency)tsconfig.json(TypeScript configuration)webpack.config.js(EJ2 quickstart uses webpack)src/index.tsorsrc/app.ts(main TypeScript entry point)src/index.html(HTML container file)- Output: Confirm the detected application type is a TypeScript EJ2 webpack project (NOT a React/Vue/Angular project) before proceeding.
- CRITICAL: This skill generates vanilla TypeScript code using the EJ2
PdfViewerclass. Do NOT generate React, Angular, or Vue component code.
Step 2 — Generate Code from Reference Files Only (REQUIRED)
- Before generating: Confirm that Step 1 is complete
- Read the relevant
references/*.mdfile(s) for the requested feature - Cross-reference EVERY API, property, and method against these tables
- CLASS-BASED APPROACH (MANDATORY - TypeScript EJ2 PATTERNS ONLY):
- Import
PdfViewerand required module classes from@syncfusion/ej2-pdfviewer - Use
PdfViewer.Inject(...)to inject required feature modules - Instantiate with
new PdfViewer({ ... })ornew PdfViewer()and set properties - Mount to DOM using
viewer.appendTo('#ElementId') - NEVER use JSX, TSX, React hooks, or component-based syntax
- NEVER use `<PdfViewerComponent>`, `<Inject services={...}>`, `useState`, `useRef`, or `useEffect`
- 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. If no keyword matches, return only the basic sample.
Checklist Before Generating Code
- [ ] Count the settings properties: 1-3? → Pass inline in constructor | 4+? → Extract to typed constant
- [ ] Are enums involved? Yes → Must use typed constant with enum imports | No → Can pass inline
- [ ] Is it reused elsewhere? Yes → Use constant | No → Prefer inline
- [ ] Do I need type safety? Yes → Import the model type | No → Skip model type import
- [ ] Do I need enums? Yes → Import required enums from
@syncfusion/ej2-pdfviewer| No → Skip enum imports - [ ] Package name correct? Always import from
@syncfusion/ej2-pdfviewer— NEVER from@syncfusion/ej2-typescript-pdfviewer
🎯 Core Setup & Configuration
| File | Purpose | Route When User Asks About |
|---|---|---|
| getting-started.md | Minimal PdfViewer setup: clone quickstart, install packages, import CSS, create PdfViewer instance with documentPath and resourceUrl, and appendTo HTML container. | "basic setup", "minimal example", "getting started", "how to load PDF" |
| general-properties.md | Configure core viewer properties (width, height, document path, locale, resourceUrl, serviceUrl, AJAX settings, scroll settings, commandManager). | "configuration", "server settings", "locale", "document path setup", "width height" |
| 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: Bookmark API methods are accessed on the `pdfviewer` instance directly (e.g., `pdfviewer.bookmark.openBookmarkPane()`). Requires `BookmarkView` to be injected and `enableBookmark: true`. | "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" |
� Comments & Panels
| File | Purpose | Route When User Asks About |
|---|---|---|
| general-properties.md | Configure core viewer properties including isCommandPanelOpen to show/hide the comments panel programmatically. See "Controlling Command Panel (Comments Panel)" section. REQUIREMENT: Set enableAnnotation: true for the command panel to be functional. PROPERTY: isCommandPanelOpen is read/write boolean (not read-only). | "show comments panel", "hide comments panel", "toggle comments", "command panel", "show/hide comments", "isCommandPanelOpen", "comments panel", "annotation comments" |
�🔍 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 using toolbarSettings. | "customize toolbar", "hide toolbar items", "remove toolbar buttons", "toolbar configuration" |
| toolbar-methods.md | Programmatically show/hide toolbars and enable/disable toolbar items at runtime using methods like showToolbar(). | "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 |
|---|---|---|
| context-menu.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). Use TextFieldSettings, CheckBoxFieldSettings, RadioButtonFieldSettings, etc. for proper type casting. CRITICAL: Form field bounds use capitalized properties (X, Y, Width, Height), NOT lowercase. TIMING CRITICAL: Always add form fields inside the documentLoad event callback - calling before document loads causes "formFieldCollections is not a function" error. | "form field defaults", "form field styles", "configure form fields", "form field properties", "add text field", "add form field", "add textbox", "add checkbox", "programmatically add field", "addFormField", "TextFieldSettings" |
| 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 { PdfViewer, Toolbar, Magnification, Navigation, Annotation, LinkAnnotation,
ThumbnailView, BookmarkView, TextSelection, TextSearch, FormFields, FormDesigner } from '@syncfusion/ej2-pdfviewer';
PdfViewer.Inject(Toolbar, Magnification, Navigation, Annotation, LinkAnnotation, ThumbnailView,
BookmarkView, TextSelection, TextSearch, FormFields, FormDesigner);
let pdfviewer: PdfViewer = new PdfViewer();
pdfviewer.documentPath = "https://cdn.syncfusion.com/content/pdf/pdf-succinctly.pdf";
pdfviewer.resourceUrl = "https://cdn.syncfusion.com/ej2/31.1.23/dist/ej2-pdfviewer-lib";
pdfviewer.appendTo('#PdfViewer');🔄 DOCUMENT LIFECYCLE REQUIREMENTS (CRITICAL)
When to Use documentLoad Event
Certain operations MUST be performed inside the documentLoad event callback, not immediately after instantiation:
Operations that REQUIRE `documentLoad`:
- ✅ Adding form fields programmatically (
formDesigner.addFormField()) - ✅ Adding annotations (
annotation.addAnnotation()) - ✅ Accessing form field collections (
formFieldCollections) - ✅ Accessing document metadata
- ✅ Modifying document-dependent properties
Operations safe at instantiation time:
- ✅ Setting
enableToolbar,enableAnnotation, etc. - ✅ Setting viewer properties like
width,height - ✅ Configuring settings objects
Example: Correct Timing for Form Fields
❌ WRONG - Causes "formFieldCollections.findIndex is not a function":
let pdfviewer = new PdfViewer({
documentPath: 'https://...',
resourceUrl: 'https://...'
});
pdfviewer.appendTo('#PdfViewer');
// ERROR! formFieldCollections not yet initialized
pdfviewer.formDesigner.addFormField('Textbox', { ... });✅ CORRECT - Inside documentLoad callback:
let pdfviewer = new PdfViewer({
documentPath: 'https://...',
resourceUrl: 'https://...',
documentLoad: () => {
// SAFE - Document fully loaded, formFieldCollections initialized
pdfviewer.formDesigner.addFormField('Textbox', { ... });
}
});
pdfviewer.appendTo('#PdfViewer');---
⚙️ SETTINGS CONFIGURATION BEST PRACTICES
When generating code with settings (toolbarSettings, annotationSettings, annotationSelectorSettings, arrowSettings, rectangleSettings, etc.), follow these guidelines:
Rule 1: Simple Settings → Pass directly to the PdfViewer constructor
Use this approach when:
- Configuring only 1-3 properties
- Settings are straightforward without complex enums or custom types
Example (DO THIS):
import { PdfViewer, Toolbar, Annotation } from '@syncfusion/ej2-pdfviewer';
PdfViewer.Inject(Toolbar, Annotation);
let pdfviewer: PdfViewer = new PdfViewer({
documentPath: 'https://cdn.syncfusion.com/content/pdf/pdf-succinctly.pdf',
resourceUrl: 'https://cdn.syncfusion.com/ej2/31.1.23/dist/ej2-pdfviewer-lib',
annotationSelectorSettings: {
selectionBorderColor: '#0000ff',
resizerBorderColor: '#ff0000',
resizerSize: 8
}
});
pdfviewer.appendTo('#PdfViewer');Benefits:
- ✅ No extra imports needed
- ✅ Simple and readable
- ✅ Less code clutter
- ✅ Type checking still works
---
Rule 2: Complex Settings → Define as Typed Constant (OUTSIDE instantiation)
Use this approach when:
- Configuring 4+ properties OR multiple related settings
- Using enums or complex configurations
- Need to reuse the same configuration in multiple places
- Settings are complex enough to warrant separate definition
Example (DO THIS ONLY FOR COMPLEX CASES):
import { PdfViewer, Toolbar, Annotation, AnnotationResizerLocation, CursorType } from '@syncfusion/ej2-pdfviewer';
import { AnnotationSelectorSettingsModel } from '@syncfusion/ej2-pdfviewer';
PdfViewer.Inject(Toolbar, Annotation);
// Define constant OUTSIDE instantiation 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
};
let pdfviewer: PdfViewer = new PdfViewer({
documentPath: 'https://cdn.syncfusion.com/content/pdf/pdf-succinctly.pdf',
resourceUrl: 'https://cdn.syncfusion.com/ej2/31.1.23/dist/ej2-pdfviewer-lib',
annotationSelectorSettings: annotationSelectorConfig
});
pdfviewer.appendTo('#PdfViewer');When to import types and enums:
- [ ] Import model types (e.g.,
AnnotationSelectorSettingsModel) for TypeScript type checking - [ ] Import any enums used in the settings (e.g.,
AnnotationResizerLocation,CursorType) - [ ] Keep imports minimal - import ONLY what is used
Benefits:
- ✅ Type-safe configuration
- ✅ Proper enum usage
- ✅ Reusable across multiple viewer instances
- ✅ Clean instantiation code
---
Rule 3: NEVER Over-Engineer Simple Cases
❌ DO NOT DO THIS (Over-engineered):
import { PdfViewer, Toolbar } from '@syncfusion/ej2-pdfviewer';
import { ToolbarSettingsModel } from '@syncfusion/ej2-pdfviewer';
PdfViewer.Inject(Toolbar);
// Unnecessary constant for 2 simple properties
const toolbarSettings: ToolbarSettingsModel = {
showTooltip: true
};
let pdfviewer: PdfViewer = new PdfViewer({
toolbarSettings: toolbarSettings
});
pdfviewer.appendTo('#PdfViewer');✅ DO THIS INSTEAD (Simple & Clean):
import { PdfViewer, Toolbar } from '@syncfusion/ej2-pdfviewer';
PdfViewer.Inject(Toolbar);
let pdfviewer: PdfViewer = new PdfViewer({
documentPath: 'https://cdn.syncfusion.com/content/pdf/pdf-succinctly.pdf',
resourceUrl: 'https://cdn.syncfusion.com/ej2/31.1.23/dist/ej2-pdfviewer-lib',
toolbarSettings: { showTooltip: true }
});
pdfviewer.appendTo('#PdfViewer');Common Pitfalls and Corrections
- Extract Pages API location:
extractPages()is a method ofPdfViewer, not ofpageOrganizer. Callpdfviewer.extractPages('1-3'), notpdfviewer.pageOrganizer.extractPages('1-3'). ThePageOrganizerservice enables the UI and capabilities, but programmatic extraction uses the viewer instance.
- Loading extracted/serialized PDFs:
pdfviewer.load(document, password?)accepts two parameters. When loading output returned byextractPages(...), provide the password parameter as an empty string if the document is not protected, for example:pdfviewer.load(extractedPdf, ''). Supply the actual password only for password-protected PDFs.
- Event timing for document-dependent operations: Perform annotation and form field operations inside
documentLoadto avoid initialization errors (e.g.,formFieldCollectionsavailability).
---
Syncfusion<sup>®</sup> JavaScript PDF Viewer Skill
Overview
The syncfusion-javaScript-pdf-viewer skill enables AI-assisted code generation for the Syncfusion JavaScript (ES6) PDF Viewer (`PdfViewerComponent`). It produces minimal, copy-pasteable ts code to embed, configure, and interact with PDF documents inside JavaScript (ES6) applications.
See [SKILL.md](SKILL.md) for the full intent-routing guide and rules. ---
Compatibility
| Requirement | Version |
|---|---|
| Node.js | ≥ 14.15.0 (and later versions like 16, 18, 20). |
| Package Manager | NPM |
| Framework | Typescript |
---
Skill Structure
syncfusion-javascript-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. Set Up the Development Environment
1.Open a command prompt in your target directory.
2.Clone the Syncfusion Essential JS 2 quickstart project from GitHub:
git clone https://github.com/SyncfusionExamples/ej2-quickstart-webpack ej2-quickstartNavigate into the project
cd ej2-quickstart2. Install the Package
Syncfusion Essential JS 2 packages are available on npmjs.com. The quickstart project includes the @syncfusion/ej2 meta package in package.json.
npm install3. Add CSS Imports (src/index.css)
Add the required Syncfusion CSS files to src/styles/styles.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";
@import "../../node_modules/@syncfusion/ej2-notifications/styles/material.css";pdfviewer.documentPath = window.location.origin + “/pdfsuccinctly.pdf”; pdfviewer.resourceUrl = window.location.origin + “/ej2-pdfviewer-lib”;
5. Basic Component (src/index.ts)
import { PdfViewer, Toolbar, Magnification, Navigation, Annotation, LinkAnnotation,
ThumbnailView, BookmarkView, TextSelection, TextSearch, FormFields, FormDesigner } from '@syncfusion/ej2-pdfviewer';
PdfViewer.Inject(Toolbar, Magnification, Navigation, Annotation, LinkAnnotation, ThumbnailView,
BookmarkView, TextSelection, TextSearch, FormFields, FormDesigner);
let pdfviewer: PdfViewer = new PdfViewer();
pdfviewer.documentPath = "https://cdn.syncfusion.com/content/pdf/pdf-succinctly.pdf";
pdfviewer.resourceUrl = "https://cdn.syncfusion.com/ej2/31.1.23/dist/ej2-pdfviewer-lib";
pdfviewer.appendTo('#PdfViewer');6. Run the App
npm start---
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-javascript-pdf-viewer |
| Author | Syncfusion Inc |
| Version | 1.0.0 |
| Category | Document Viewing |
| Framework | Typescript |
| Reference Files | 25 |
Annotation Events
Description: Annotation events in TypeScript 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
let viewer: PdfViewer = new PdfViewer({
annotationAdd: function (args: any): void {
console.log('Event triggered:', args);
}
});---
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 property name to use when initializing
PdfViewer - 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. annotationType - (string) - Type of annotation added. |
| 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;
console.log('Type:', annotation.type);
if (annotation.type === 'FreeText') {
console.log('Content:', annotation.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}`);
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 => {
logEvent('annotation_moved', {
annotationId: args.annotationId,
page: args.pageIndex,
timestamp: new Date().toISOString()
});
};
let viewer: PdfViewer = new PdfViewer({
annotationMove: onAnnotationMove
});
viewer.appendTo('#pdfViewer');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 => {
if (args.pageIndex === 0) {
args.cancel = true;
alert('Annotations are not allowed on the cover page.');
}
};
let viewer: PdfViewer = new PdfViewer({
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);
console.log('Type:', annotation.type);
console.log('Page:', args.pageIndex);
updatePropertiesPanel(args.annotationId, annotation);
};
let viewer: PdfViewer = new PdfViewer({
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);
}
if (args.isThicknessChanged) {
console.log('Annotation thickness changed to:', args.annotation.thickness);
}
if (args.isOpacityChanged) {
console.log('Annotation opacity changed to:', args.annotation.opacity);
}
};
let viewer: PdfViewer = new PdfViewer({
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);
args.annotationCollection.forEach((annotation: any) => {
console.log('Annotation ID:', annotation.annotationId);
console.log('Annotation Type:', annotation.type);
});
} else {
console.log('Single annotation selected:', args.annotationId);
}
};
let viewer: PdfViewer = new PdfViewer({
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 TypeScript PDF Viewer
Description: Configure PDF annotation settings immediately to control appearance, behavior, and interaction of text markup, shape, and stamp annotations in the PDF Viewer. 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
pdfviewer.annotation.addAnnotation('Rectangle', {
bounds: { x: 100, y: 100, width: 200, height: 50 },
fillColor: '#FF0000'
});
// INCORRECT ❌ - Do NOT use capitalized letters
pdfviewer.annotation.addAnnotation('Rectangle', {
bounds: { X: 100, Y: 100, Width: 200, Height: 50 }, // WRONG for annotations
fillColor: '#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:
let pdfviewer: PdfViewer = new PdfViewer();
// Customize highlight settings
pdfviewer.highlightSettings = {
color: '#00ff00', // Text highlight color
opacity: 0.6, // Transparency (0-1)
author: 'John Doe', // Who created the annotation
isLock: false // Allow user interaction
};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:
let pdfviewer: PdfViewer = new PdfViewer();
// Global settings for all annotations
pdfviewer.annotationSettings = {
author: 'PDF Author',
opacity: 0.7,
isLock: false,
skipPrint: false,
skipDownload: false,
allowedInteractions: [AllowedInteraction.Select, AllowedInteraction.Move]
};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 PdfViewer instance 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 | | areaSettings | Settings applicable for area annotations | | arrowSettings | Settings applicable for arrow annotations | | circleSettings | Settings applicable for circle annotations | | distanceSettings | Settings applicable for distance annotations | | freeTextSettings | Settings applicable for free text annotations | | handwrittenSignatureSettings | Settings applicable for handwritten signature annotations | | highlightSettings | Settings applicable for highlight annotations | | inkAnnotationSettings | Settings applicable for ink annotations | | lineSettings | Settings applicable for line annotations | | measurementSettings | Settings applicable for distance, perimeter, area, radius, volume annotations | | perimeterSettings | Settings applicable for perimeter annotations | | polygonSettings | Settings applicable for polygon annotations | | radiusSettings | Settings applicable for radius annotations | | rectangleSettings | Settings applicable for rectangle annotations | | squigglySettings | Settings applicable for squiggly annotations | | stampSettings | Settings applicable for stamp annotations | | stickyNotesSettings | Settings applicable for sticky notes annotations | | strikethroughSettings | Settings applicable for strikethrough annotations | | underlineSettings | Settings applicable for underline annotations | | volumeSettings | Settings applicable for volume annotations |
Common Use Cases
Use Case 1: Apply Company Branding to All Annotations
let pdfviewer: PdfViewer = new PdfViewer();
pdfviewer.annotationSettings = {
author: 'Acme Corporation',
subject: 'Document Review',
customData: { department: 'Legal', version: '1.0' }
};Use Case 2: Make Annotations Non-Editable After Creation
let pdfviewer: PdfViewer = new PdfViewer();
pdfviewer.annotationSettings = {
isLock: true, // Prevent editing
allowedInteractions: [] // Restrict all interactions
};Use Case 3: Customize Highlight and Underline Appearance
// Make highlights green and underlines blue
let pdfviewer: PdfViewer = new PdfViewer();
pdfviewer.highlightSettings = { color: '#00FF00', opacity: 0.5 };
pdfviewer.underlineSettings = { color: '#0000FF', opacity: 0.4 };Use Case 4: Restrict Annotation Download/Print
// Annotations won't appear in exported files or print output
let pdfviewer: PdfViewer = new PdfViewer();
pdfviewer.annotationSettings = {
skipDownload: true, // Hide from downloaded PDFs
skipPrint: true // Hide from printed pages
};Use Case 5: Customize Resize Handles When Editing Annotations
// Control how annotation selection handles appear during editing
let pdfviewer: PdfViewer = new PdfViewer();
pdfviewer.annotationSelectorSettings = {
resizerBorderColor: '#FF0000', // Red border
resizerFillColor: '#FFE0E0', // Light red fill
resizerSize: 8, // Handle size in pixels
resizerShape: 'Circle', // Circle or Square
resizerLocation: AnnotationResizerLocation.Corners | AnnotationResizerLocation.Edges,
resizerCursorType: CursorType.grab
};Selector Customization
Apply Selection Styling Globally
Apply resize handle customization to all annotations:
let pdfviewer: PdfViewer = new PdfViewer();
pdfviewer.annotationSelectorSettings = { resizerBorderColor: 'green' };Apply Selection Styling to Specific Annotation Type
Customize resize handles for individual annotation types:
pdfviewer.areaSettings = {
annotationSelectorSettings: { resizerBorderColor: 'green' }
};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 TypeScript 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 | User works with fillable PDF forms - needs to pre-fill, validate, export, clear field data (e.g., "populate form from database") |
| Annotations | addAnnotation, deleteAnnotations, exportAnnotation, exportAnnotationsAsBase64String, exportAnnotationsAsObject, importAnnotation | User wants to add/remove/save PDF markup, manage annotations programmatically (e.g., "save annotations", "highlight search results") |
| 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 | annotation: any | void | viewer.addAnnotation(annotationObject); |
| addCustomMenu | Adds a custom menu item to the context menu of the PDF viewer | menuItems: MenuItemModel[], disableDefaultItems?: boolean, appendToEnd?: boolean | void | viewer.addCustomMenu([{id: 'custom1', text: 'Custom Item'}], false, true); |
| clearFormFields | Clears data from the form fields | formField?: any | void | viewer.clearFormFields(); |
| convertClientPointToPagePoint | Converts a client point (screen coordinates) to page point coordinates | clientPoint: Point, pageNumber: number | Point | const pagePoint = viewer.convertClientPointToPagePoint({x: 100, y: 200}, 0); |
| convertPagePointToClientPoint | Converts a page point to client point (screen coordinates) | pagePoint: Point, pageNumber: number | Point | const clientPoint = viewer.convertPagePointToClientPoint({x: 50, y: 75}, 0); |
| convertPagePointToScrollingPoint | Converts a page point to scrolling point coordinates within the viewport | pagePoint: Point, pageNumber: number | Point | const scrollPoint = viewer.convertPagePointToScrollingPoint({x: 50, y: 75}, 0); |
| deleteAnnotations | Deletes specified annotations from the PDF document | - | void | viewer.deleteAnnotations(); |
| destroy | Destroys the PdfViewer component and releases its resources | - | void | viewer.destroy(); |
| download | Downloads the current PDF document to the client machine | - | void | viewer.download(); |
| exportAnnotation | Exports annotations from the PDF document as a string in JSON format | annotationDataFormat?: AnnotationDataFormat | void | viewer.exportAnnotation(); |
| exportAnnotationsAsBase64String | Exports annotations from the PDF document as a Base64 encoded string | annotationDataFormat: AnnotationDataFormat | Promise<string> | const base64 = await viewer.exportAnnotationsAsBase64String(AnnotationDataFormat.Json); |
| exportAnnotationsAsObject | Exports annotations from the PDF document as a JSON object | annotationDataFormat: AnnotationDataFormat | Promise<object> | const annotationsObj = await viewer.exportAnnotationsAsObject(AnnotationDataFormat.Json); |
| exportFormFields | Exports form fields data from the PDF document as XML string | data?: string, formFieldDataFormat?: FormFieldDataFormat | void | viewer.exportFormFields(); |
| exportFormFieldsAsObject | Exports form fields data from the PDF document as a JSON object | formFieldDataFormat: FormFieldDataFormat | Promise<object> | const formFieldsObj = await viewer.exportFormFieldsAsObject(FormFieldDataFormat.Json); |
| extractPages | Extracts specified pages from the PDF document | value: string | Uint8Array | const extractedData = viewer.extractPages('1,2,3'); |
| extractText | Extracts text from a specific page of the PDF document | pageIndex: number, options: ExtractTextOption | Promise<any> | const text = await viewer.extractText(0, ExtractTextOption.TextOnly); |
| extractText (range) | Extracts text from a specified range of pages | startIndex: number, endIndex: number, options: ExtractTextOption | Promise<any> | const text = await viewer.extractText(0, 5, ExtractTextOption.TextAndBounds); |
| focusFormField | Sets focus to a specific form field in the PDF document | field: any | void | viewer.focusFormField('fieldName'); |
| getPageInfo | Retrieves information about a specific page in the PDF document | pageIndex: number | PageInfoModel | const pageInfo = viewer.getPageInfo(0); |
| getPageNumberFromClientPoint | Gets the page number at a specific client point (screen coordinates) | clientPoint: Point | number | const pageNum = viewer.getPageNumberFromClientPoint({x: 100, y: 200}); |
| importAnnotation | Imports annotations into the PDF document from a JSON string | importData: any, annotationDataFormat?: AnnotationDataFormat | void | viewer.importAnnotation(jsonAnnotationString); |
| importFormFields | Imports form field data into the PDF document from XML format | data?: string, formFieldDataFormat?: FormFieldDataFormat | void | viewer.importFormFields(xmlFormFieldData); |
| load | Loads a PDF document from a specified URL or file path | document: `string \ | Uint8Array, password?: string` | void |
| redo | Redoes the last undone action in the PDF viewer | - | void | viewer.redo(); |
| resetFormFields | Resets all form field values to their default values | - | void | viewer.resetFormFields(); |
| retrieveFormFields | Retrieves all form field data from the PDF document | - | FormFieldModel[] | const formFields = viewer.retrieveFormFields(); |
| saveAsBlob | Saves the current PDF document as a Blob object | - | Promise<Blob> | const blob = await viewer.saveAsBlob(); |
| setJsonData | Sets JSON data for the PDF viewer configuration and state | jsonData?: string | void | viewer.setJsonData(jsonConfigString); |
| showNotificationPopup | Displays a notification popup message in the PDF viewer | errorString: string | void | viewer.showNotificationPopup('Success!'); |
| undo | Undoes the last action performed in the PDF viewer | - | void | viewer.undo(); |
| unload | Unloads the currently loaded PDF document from the viewer | - | void | viewer.unload(); |
| updateFormFields | Updates specific form fields in the PDF document | formFields: any | void | viewer.updateFormFields(formFieldsArray); |
| updateFormFieldsValue | Updates the values of form fields in the PDF document | fieldValue: any | void | viewer.updateFormFieldsValue(fieldValueObject); |
| updateViewerContainer | Updates the PDF viewer container size and layout | - | void | viewer.updateViewerContainer(); |
| zoomToRect | Zooms the PDF viewer to fit a specific rectangular region | rectangle: Rect | void | viewer.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.
Point
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 |
Rect
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 |
PageInfoModel
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 | number |
| width | The width of the page | number |
| height | The height of the page | number |
| rotation | The rotation angle of the page | number |
FormFieldModel
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 |
MenuItemModel
When to use: Required parameter for addCustomMenu() method. Represents a custom 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 |
AnnotationDataFormat
When to use: Used with annotation export/import methods to specify data format. Valid annotation data formats include:
AnnotationDataFormat.Json- JSON formatAnnotationDataFormat.Xfdf- XFDF format
FormFieldDataFormat
When to use: Used with form field export/import methods to specify data format. Valid form field data formats include:
FormFieldDataFormat.Json- JSON formatFormFieldDataFormat.Xml- XML formatFormFieldDataFormat.Fdf- FDF formatFormFieldDataFormat.Xfdf- XFDF format
ExtractTextOption
When to use: Used with extractText() method to specify extraction type. Valid text extraction options include:
ExtractTextOption.TextAndBounds- Extracts both plain text and text with bounds (layout information)ExtractTextOption.TextOnly- Extracts only plain text without bounds informationExtractTextOption.BoundsOnly- Extracts text with layout information (bounds/coordinates) onlyExtractTextOption.None- No text information is returned
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.
import { PdfViewer, Toolbar, Magnification, Navigation, LinkAnnotation, ThumbnailView,
BookmarkView, TextSelection, TextSearch, Print, Annotation, FormFields, FormDesigner }
from '@syncfusion/ej2-pdfviewer';
PdfViewer.Inject(Toolbar, Magnification, Navigation, LinkAnnotation, ThumbnailView,
BookmarkView, TextSelection, TextSearch, Print, Annotation, FormFields, FormDesigner);
let viewer: PdfViewer = new PdfViewer();
viewer.serviceUrl = 'https://ej2services.syncfusion.com/production/web-services/api/pdfviewer';
viewer.appendTo('#pdfViewer');
// Load a PDF document
viewer.load('document.pdf', null);
// Later, allow user to download
viewer.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.
import { PdfViewer, Toolbar, Magnification, Navigation, LinkAnnotation, ThumbnailView,
BookmarkView, TextSelection, TextSearch, Print, Annotation, FormFields, FormDesigner }
from '@syncfusion/ej2-pdfviewer';
PdfViewer.Inject(Toolbar, Magnification, Navigation, LinkAnnotation, ThumbnailView,
BookmarkView, TextSelection, TextSearch, Print, Annotation, FormFields, FormDesigner);
let viewer: PdfViewer = new PdfViewer();
viewer.serviceUrl = 'https://ej2services.syncfusion.com/production/web-services/api/pdfviewer';
viewer.appendTo('#pdfViewer');
viewer.load('formDocument.pdf', null);
// Retrieve all form fields
const formFields = viewer.retrieveFormFields();
console.log(formFields);
// Update specific field values
viewer.updateFormFieldsValue({
'firstName': 'John',
'email': 'john@example.com'
});
// Export filled form data
const formData = await viewer.exportFormFieldsAsObject(FormFieldDataFormat.Json);
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.
import { PdfViewer, Toolbar, Magnification, Navigation, LinkAnnotation, ThumbnailView,
BookmarkView, TextSelection, TextSearch, Print, Annotation, FormFields, FormDesigner,
AnnotationDataFormat } from '@syncfusion/ej2-pdfviewer';
PdfViewer.Inject(Toolbar, Magnification, Navigation, LinkAnnotation, ThumbnailView,
BookmarkView, TextSelection, TextSearch, Print, Annotation, FormFields, FormDesigner);
let viewer: PdfViewer = new PdfViewer();
viewer.serviceUrl = 'https://ej2services.syncfusion.com/production/web-services/api/pdfviewer';
viewer.appendTo('#pdfViewer');
viewer.load('document.pdf', null);
// Export current annotations
viewer.exportAnnotation(AnnotationDataFormat.Json);
// Export annotations as object
const annotations = await viewer.exportAnnotationsAsObject(AnnotationDataFormat.Json);
console.log(annotations);
// Import previously saved annotations
viewer.importAnnotation(annotationJSON, AnnotationDataFormat.Json);
// Delete all annotations
viewer.deleteAnnotations();Scenario 4: Extract Text from PDF
When: You need to get text content from a specific region or pages.
Why: Use extractText() with options parameter for targeted text extraction - ideal for processing specific fields, copying text from coordinates, or building search/highlight features.
import { PdfViewer, Toolbar, Magnification, Navigation, LinkAnnotation, ThumbnailView,
BookmarkView, TextSelection, TextSearch, Print, Annotation, FormFields, FormDesigner,
ExtractTextOption } from '@syncfusion/ej2-pdfviewer';
PdfViewer.Inject(Toolbar, Magnification, Navigation, LinkAnnotation, ThumbnailView,
BookmarkView, TextSelection, TextSearch, Print, Annotation, FormFields, FormDesigner);
let viewer: PdfViewer = new PdfViewer();
viewer.serviceUrl = 'https://ej2services.syncfusion.com/production/web-services/api/pdfviewer';
viewer.appendTo('#pdfViewer');
viewer.load('document.pdf', null);
// Extract text from a single page
const pageText = await viewer.extractText(0, ExtractTextOption.TextOnly);
console.log('Page 0 text:', pageText);
// Extract text from multiple pages
const rangeText = await viewer.extractText(0, 5, ExtractTextOption.TextAndBounds);
console.log('Pages 0-5 text:', rangeText);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).
import { PdfViewer, Toolbar, Magnification, Navigation, LinkAnnotation, ThumbnailView,
BookmarkView, TextSelection, TextSearch, Print, Annotation, FormFields, FormDesigner }
from '@syncfusion/ej2-pdfviewer';
PdfViewer.Inject(Toolbar, Magnification, Navigation, LinkAnnotation, ThumbnailView,
BookmarkView, TextSelection, TextSearch, Print, Annotation, FormFields, FormDesigner);
let viewer: PdfViewer = new PdfViewer();
viewer.serviceUrl = 'https://ej2services.syncfusion.com/production/web-services/api/pdfviewer';
viewer.appendTo('#pdfViewer');
viewer.load('document.pdf', null);
// Get page information
const pageInfo = viewer.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 };
viewer.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.
import { PdfViewer, Toolbar, Magnification, Navigation, LinkAnnotation, ThumbnailView,
BookmarkView, TextSelection, TextSearch, Print, Annotation, FormFields, FormDesigner }
from '@syncfusion/ej2-pdfviewer';
PdfViewer.Inject(Toolbar, Magnification, Navigation, LinkAnnotation, ThumbnailView,
BookmarkView, TextSelection, TextSearch, Print, Annotation, FormFields, FormDesigner);
let viewer: PdfViewer = new PdfViewer();
viewer.serviceUrl = 'https://ej2services.syncfusion.com/production/web-services/api/pdfviewer';
viewer.appendTo('#pdfViewer');
viewer.load('document.pdf', null);
// User clicks undo button
document.getElementById('undoBtn').addEventListener('click', () => {
viewer.undo();
});
// User clicks redo button
document.getElementById('redoBtn').addEventListener('click', () => {
viewer.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.
import { PdfViewer, Toolbar, Magnification, Navigation, LinkAnnotation, ThumbnailView,
BookmarkView, TextSelection, TextSearch, Print, Annotation, FormFields, FormDesigner,
MenuItemModel } from '@syncfusion/ej2-pdfviewer';
PdfViewer.Inject(Toolbar, Magnification, Navigation, LinkAnnotation, ThumbnailView,
BookmarkView, TextSelection, TextSearch, Print, Annotation, FormFields, FormDesigner);
let viewer: PdfViewer = new PdfViewer();
viewer.serviceUrl = 'https://ej2services.syncfusion.com/production/web-services/api/pdfviewer';
viewer.appendTo('#pdfViewer');
viewer.load('document.pdf', null);
// Add custom context menu item
const customItems: MenuItemModel[] = [
{ id: 'custom-1', text: 'My Custom Action', tooltipText: 'Do something custom' }
];
viewer.addCustomMenu(customItems, false, true);
// Show notification
viewer.showNotificationPopup('PDF loaded successfully');Scenario 8: Coordinate Conversion for Custom Interactions
When: Building custom interactions that require converting between different coordinate systems.
Why: Use coordinate conversion methods to map between client (screen), page, and scrolling coordinates for features like custom annotations, highlights at specific positions, or interactive overlays.
import { PdfViewer, Toolbar, Magnification, Navigation, LinkAnnotation, ThumbnailView,
BookmarkView, TextSelection, TextSearch, Print, Annotation, FormFields, FormDesigner }
from '@syncfusion/ej2-pdfviewer';
PdfViewer.Inject(Toolbar, Magnification, Navigation, LinkAnnotation, ThumbnailView,
BookmarkView, TextSelection, TextSearch, Print, Annotation, FormFields, FormDesigner);
let viewer: PdfViewer = new PdfViewer();
viewer.serviceUrl = 'https://ej2services.syncfusion.com/production/web-services/api/pdfviewer';
viewer.appendTo('#pdfViewer');
viewer.load('document.pdf', null);
// Get page number from click position
const clientPoint = { x: 100, y: 200 };
const pageNumber = viewer.getPageNumberFromClientPoint(clientPoint);
console.log('Clicked on page:', pageNumber);
// Convert client point to page coordinates
const pagePoint = viewer.convertClientPointToPagePoint(clientPoint, pageNumber);
console.log('Page coordinates:', pagePoint);
// Convert page point back to client coordinates
const newClientPoint = viewer.convertPagePointToClientPoint(pagePoint, pageNumber);
console.log('Client coordinates:', newClientPoint);
// Convert page point to scrolling coordinates
const scrollPoint = viewer.convertPagePointToScrollingPoint(pagePoint, pageNumber);
console.log('Scroll coordinates:', scrollPoint);Scenario 9: Save PDF as Blob for Upload
When: User needs to save the modified PDF to a server or process it further.
Why: Use saveAsBlob() to get the PDF as a Blob object which can be uploaded to a server using fetch/XMLHttpRequest, or processed client-side.
import { PdfViewer, Toolbar, Magnification, Navigation, LinkAnnotation, ThumbnailView,
BookmarkView, TextSelection, TextSearch, Print, Annotation, FormFields, FormDesigner }
from '@syncfusion/ej2-pdfviewer';
PdfViewer.Inject(Toolbar, Magnification, Navigation, LinkAnnotation, ThumbnailView,
BookmarkView, TextSelection, TextSearch, Print, Annotation, FormFields, FormDesigner);
let viewer: PdfViewer = new PdfViewer();
viewer.serviceUrl = 'https://ej2services.syncfusion.com/production/web-services/api/pdfviewer';
viewer.appendTo('#pdfViewer');
viewer.load('document.pdf', null);
// Save as Blob and upload to server
document.getElementById('saveBtn').addEventListener('click', async () => {
const blob = await viewer.saveAsBlob();
// Create FormData to upload
const formData = new FormData();
formData.append('file', blob, 'document.pdf');
// Upload to server
const response = await fetch('/api/upload', {
method: 'POST',
body: formData
});
if (response.ok) {
viewer.showNotificationPopup('PDF saved successfully!');
}
});Scenario 10: Extract Specific Pages
When: User needs to extract and save specific pages from a PDF.
Why: Use extractPages() to extract specific pages as a new PDF, useful for splitting documents or creating page-specific copies.
import { PdfViewer, Toolbar, Magnification, Navigation, LinkAnnotation, ThumbnailView,
BookmarkView, TextSelection, TextSearch, Print, Annotation, FormFields, FormDesigner }
from '@syncfusion/ej2-pdfviewer';
PdfViewer.Inject(Toolbar, Magnification, Navigation, LinkAnnotation, ThumbnailView,
BookmarkView, TextSelection, TextSearch, Print, Annotation, FormFields, FormDesigner);
let viewer: PdfViewer = new PdfViewer();
viewer.serviceUrl = 'https://ej2services.syncfusion.com/production/web-services/api/pdfviewer';
viewer.appendTo('#pdfViewer');
viewer.load('document.pdf', null);
// Extract pages 1, 3, and 5
const extractedData = viewer.extractPages('1,3,5');
console.log('Extracted data:', extractedData);
// Extract a range of pages (1-5)
const rangeData = viewer.extractPages('1-5');
console.log('Range data:', rangeData);
// Create a blob from extracted data and download
const blob = new Blob([extractedData], { type: 'application/pdf' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'extracted-pages.pdf';
a.click();Scenario 11: Update Viewer Container
When: The viewer container is resized or layout changes occur.
Why: Use updateViewerContainer() to refresh the viewer dimensions and layout after container size changes, ensuring proper rendering.
import { PdfViewer, Toolbar, Magnification, Navigation, LinkAnnotation, ThumbnailView,
BookmarkView, TextSelection, TextSearch, Print, Annotation, FormFields, FormDesigner }
from '@syncfusion/ej2-pdfviewer';
PdfViewer.Inject(Toolbar, Magnification, Navigation, LinkAnnotation, ThumbnailView,
BookmarkView, TextSelection, TextSearch, Print, Annotation, FormFields, FormDesigner);
let viewer: PdfViewer = new PdfViewer();
viewer.serviceUrl = 'https://ej2services.syncfusion.com/production/web-services/api/pdfviewer';
viewer.appendTo('#pdfViewer');
viewer.load('document.pdf', null);
// Listen for window resize events
window.addEventListener('resize', () => {
viewer.updateViewerContainer();
});
// Or update after programmatic container resize
document.getElementById('resizeBtn').addEventListener('click', () => {
const container = document.getElementById('pdfViewer');
container.style.width = '800px';
container.style.height = '600px';
viewer.updateViewerContainer();
});Scenario 12: Form Field Focus Management
When: User needs to programmatically set focus to a specific form field.
Why: Use focusFormField() to guide users through form filling, highlight required fields, or implement custom navigation.
let viewer: PdfViewer = new PdfViewer();
viewer.serviceUrl = 'https://ej2services.syncfusion.com/production/web-services/api/pdfviewer';
viewer.appendTo('#pdfViewer');
viewer.load('formDocument.pdf', null);
// Focus on a specific field by name
viewer.focusFormField('firstName');
// Implement custom form navigation
document.getElementById('nextFieldBtn').addEventListener('click', () => {
const fields = viewer.retrieveFormFields();
const currentIndex = fields.findIndex(f => f.name === 'firstName');
if (currentIndex < fields.length - 1) {
viewer.focusFormField(fields[currentIndex + 1].name);
}
});---
Basic Sample
Description: Complete getting started guide for setting up and using the Syncfusion PDF Viewer in a TypeScript application using Essential JS 2 quickstart seed repository. This guide covers development environment setup, package installation, and basic PDF Viewer implementation.
---
Table of Contents
- Prerequisites
- Set up the development environment
- Add Syncfusion Javascript (ES6) packages
- Import Syncfusion CSS styles
- Add the PDF Viewer component
- Run the application
- Module injection
- Version Information
- Important Notes
Prerequisites
The sample project uses a webpack configuration (webpack.config.js) and the latest webpack-cli. Node.jsv14.15.0or later is required. For details, see the webpack getting started guide.
---
Set up the development environment
Step 1: Clone the quickstart project
Open a command prompt in your target directory and clone the Syncfusion Essential JS 2 quickstart project from GitHub:
git clone https://github.com/SyncfusionExamples/ej2-quickstart-webpack ej2-quickstartStep 2: Navigate to the project folder
cd ej2-quickstart---
Add Syncfusion Javascript (ES6) packages
Syncfusion Essential JS 2 packages are available on npmjs.com. The quickstart project includes the @syncfusion/ej2 meta package in package.json.
Install dependencies
npm install---
Import Syncfusion CSS styles
Add the required Syncfusion CSS files to src/styles/styles.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";
@import "../../node_modules/@syncfusion/ej2-notifications/styles/material.css";---
Add the PDF Viewer component
Step 1: Configure PDF Viewer in app.ts
In app.ts, import and inject the required modules, then create and configure the PDF Viewer:
import { PdfViewer, Toolbar, Magnification, Navigation, Annotation, LinkAnnotation, ThumbnailView, BookmarkView, TextSelection, TextSearch, FormFields, FormDesigner } from '@syncfusion/ej2-pdfviewer';
PdfViewer.Inject(Toolbar, Magnification, Navigation, Annotation, LinkAnnotation, ThumbnailView, BookmarkView, TextSelection, TextSearch, FormFields, FormDesigner);
let pdfviewer: PdfViewer = new PdfViewer();
pdfviewer.documentPath = "https://cdn.syncfusion.com/content/pdf/pdf-succinctly.pdf";
pdfviewer.resourceUrl = "https://cdn.syncfusion.com/ej2/31.1.23/dist/ej2-pdfviewer-lib";
pdfviewer.appendTo('#PdfViewer');Step 2: Using Local Resources (Optional)
To use local resources instead of CDN, follow these steps:
- Ensure the
ej2-pdfviewer-libfolder (containingpdfium.js,pdfium.wasm, and the PDF file) is present in your project'sdistdirectory. - Set the
documentPathandresourceUrlproperties to local paths:
pdfviewer.documentPath = window.location.origin + "/pdfsuccinctly.pdf";
pdfviewer.resourceUrl = window.location.origin + "/ej2-pdfviewer-lib";Reference Example: For a complete example, see load PDF Viewer with local resources.
Step 3: Add HTML container
Add a container element for the PDF Viewer in index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Essential JS 2</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
<meta name="description" content="Essential JS 2" />
<meta name="author" content="Syncfusion" />
<link rel="shortcut icon" href="resources/favicon.ico" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<!-- PDF Viewer container -->
<div id="PdfViewer"></div>
</body>
</html>---
Run the application
The quickstart project is preconfigured to build and launch in the browser. Start the application with:
npm startComplete Output Example
index.ts:
import { PdfViewer, Toolbar, Magnification, Navigation, Annotation, LinkAnnotation,
ThumbnailView, BookmarkView, TextSelection, TextSearch, FormFields, FormDesigner } from '@syncfusion/ej2-pdfviewer';
PdfViewer.Inject(Toolbar, Magnification, Navigation, Annotation, LinkAnnotation, ThumbnailView,
BookmarkView, TextSelection, TextSearch, FormFields, FormDesigner);
let pdfviewer: PdfViewer = new PdfViewer();
pdfviewer.documentPath = "https://cdn.syncfusion.com/content/pdf/pdf-succinctly.pdf";
pdfviewer.resourceUrl = "https://cdn.syncfusion.com/ej2/31.1.23/dist/ej2-pdfviewer-lib";
pdfviewer.appendTo('#PdfViewer');---
Module injection
To enable additional features, inject the required modules using PdfViewer.Inject. The following modules extend the PDF Viewer:
- LinkAnnotation: Hyperlink navigation
- BookmarkView: Bookmark display and navigation
- Magnification: Zoom in/out
- Navigation: Page navigation
- TextSelection: Text selection
- ThumbnailView: Page thumbnails
- Toolbar: Built-in toolbar UI
- Print: Printing support
- Annotation: Annotation features
- TextSearch: Text search
- FormFields: Form field support
- FormDesigner: Form field design and editing
---
Version Information
Resource URL Version: 31.1.23 (as referenced in the CDN path)
---
Important Notes
1. Node.js v14.15.0 or later is required 2. The sample uses webpack configuration and latest webpack-cli 3. The quickstart project includes the @syncfusion/ej2 meta package 4. All Syncfusion packages are available on npmjs.com 5. For local resources, ensure ej2-pdfviewer-lib folder is in the dist directory