
Syncfusion Aspnetmvc Pdf Viewer
- 1 installs
- 1 repo stars
- Updated July 6, 2026
- syncfusion/pdf-viewer-sdk-skills
Generates ASP.NET MVC Razor (.cshtml) code to embed and configure the Syncfusion EJ2 PDFViewer for displaying PDF documents.
About
Generates copy-pasteable Razor and HTML code that integrates the Syncfusion.EJ2.MVC5 PDFViewer into an ASP.NET MVC project. A developer uses it when rendering and configuring PDFs in an ASP.NET MVC app.
- Uses the Syncfusion.EJ2.MVC5 NuGet package
- Strict mode: only generates APIs documented in the reference files
Syncfusion Aspnetmvc Pdf Viewer by the numbers
- 1 all-time installs (skills.sh)
- Ranked #121 of 153 .NET & C# 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-aspnetmvc-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 ASP.NET MVC Razor (.cshtml) code to embed and configure the Syncfusion EJ2 PDFViewer for displaying PDF documents.
Files
Syncfusion ASP.NET MVC Pdfviewer – UI Sample Generator
NuGet: Syncfusion.EJ2.MVC5
Generate Code for the User's Project (default)
Trigger keywords: "how to", "add pdfviewer", "code sample", "show me", "example", "snippet", "integrate", "component", "create sample", "ASP.NET MVC sample".
Purpose: Generate minimal, copy-pasteable Razor + HTML code (.cshtml) that the user can integrate directly into their ASP.NET MVC 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 ASP.NET MVC 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 — Generate Code from Reference Files Only (REQUIRED)
- Read the relevant
references/*.mdfile(s) for the requested feature - Cross-reference EVERY API, property, and method against these tables
- 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
---
⚙️ SETTINGS CONFIGURATION BEST PRACTICES
When generating code with settings (toolbarSettings, annotationSettings, annotationSelectorSettings, arrowSettings, rectangleSettings, etc.), follow these guidelines to prevent unnecessary imports and over-engineering:
Rule 1: Simple Settings → Define as Razor inline code
Use this approach when:
- Configuring only 1-3 properties
- Settings are straightforward without custom types
Example (DO THIS):
@Html.EJS().PdfViewer("pdfviewer").AnnotationSelectorSettings(new Syncfusion.EJ2.PdfViewer.PdfViewerAnnotationSelectorSettings { ResizerBorderColor = "green", SelectionBorderColor = "blue", ResizerFillColor = "#4070ff", resizerSize = 8, SelectionBorderThickness = 1, SelectorLineDashArray = new int[] { 5, 6 }, ResizerLocation = "Corners|Edges", ResizerCursorType = "grab" }).Render()Benefits:
- ✅ Simple and readable
- ✅ Less code clutter
- ✅ Type checking still works
---
Rule 2: Complex Settings → Define as Razor code blocks outside HTML
Use this approach when:
- Configuring 4+ properties OR multiple related settings
- Using enums or complex configurations
- Need to reuse the same configuration across multiple components
- Settings are complex enough to warrant separate definition
Example (DO THIS ONLY FOR COMPLEX CASES):
@{
var annotationSelectorSettings = new {
selectionBorderColor = "blue",
resizerBorderColor = "red",
resizerFillColor = "#4070ff",
resizerSize = 8,
selectionBorderThickness = 1,
resizerShape = "Circle",
selectorLineDashArray = new int[] { 5, 6 },
resizerLocation = "Corners|Edges",
resizerCursorType = "grab"
};
}
@Html.EJS().PdfViewer("pdfviewer").AnnotationSelectorSettings(annotationSelectorSettings).Render()---
Rule 3: NEVER Over-Engineer Simple Cases
❌ DO NOT DO THIS (Over-engineered):
@{
var toolbarSettings = new Syncfusion.EJ2.PdfViewer.PdfViewerToolbarSettings { ShowTooltip = true };
}
@Html.EJS().PdfViewer("pdfviewer").ToolbarSettings(@toolbarSettings).Render()✅ DO THIS INSTEAD (Simple & Clean):
@Html.EJS().PdfViewer("pdfviewer").ToolbarSettings(new Syncfusion.EJ2.PdfViewer.PdfViewerToolbarSettings { ShowTooltip = true }).Render()---
Reference File Routing Guide
All templates and operation snippets live in references/*.md. Each file is a focused snippet or template the agent will combine when generating samples.
Flow: Always start with getting-started.md, then merge matched features into its anchors (PROPS, EVENTS, UI_BUTTONS, HANDLERS). If no keyword matches, return only the basic sample.
Checklist Before Generating Code
- [ ] Count the settings properties: 1-3? → Use inline | 4+? → Use separate razor code block
- [ ] Is the component prop simple enough? Yes → Keep inline | No → Extract to separate razor code block
- [ ] Are Default values set for properties explicitly? Yes → Remove | No → Keep it
🎯 MVC Setup & Configuration
| File | Purpose |
|---|---|
| getting-started.md | Minimal PDF Viewer with documentPath, height, and width. Base template for all samples. |
| enable-properties.md | Enable/disable specific features (toolbar, annotations, forms, navigation, text selection, download, print). |
| general-properties.md | Configure core viewer properties and behavior (documentPath, width/height, locale, zoom/initialRenderPages), server/integration settings (serviceUrl, ajaxRequestSettings, serverActionSettings), resource loading (resourceUrl, customFonts), and performance/retry options. |
Context Menu
| File | Purpose |
|---|---|
| contextmenu.md | Context-aware context menu for text, annotations, and form fields; add custom items via addCustomMenu, handle clicks with customContextMenuSelect, dynamically show/hide items with customContextMenuBeforeOpen, and disable the menu using contextMenuOption. Configure default context menu using context menu settings. |
Navigation Features
| File | Purpose |
|---|---|
| navigation.md | Enable/disable page navigation (first/last/previous/next/go to page), thumbnail view and navigation, hyperlink support (internal and external links), table of contents navigation, programmatic navigation methods, and navigation-related events. |
| bookmark-navigation.md | Enable/disable and show/hide bookmark navigation. Programmatically retrieve bookmarks for a document |
MVC Viewing and Interaction
| File | Purpose |
|---|---|
| viewing-and-interaction.md | Understand interaction modes (Text Selection/Pan), page scrolling & viewing behavior, panning operations, feature modules for modular architecture, enabling/disabling specific viewing features, and MVC viewing capabilities. |
| magnification.md | Configure zoom levels & zoom percentages, zoom modes (fit to page/fit to width/fit to visible area/automatic), custom zoom control, programmatic zoom operations, zoom toolbar configuration, and mouse wheel zoom behavior. |
Toolbar Configuration
| File | Purpose |
|---|---|
| toolbar-customization.md | Customize the PDF viewer primary, form designer, annotation toolbars. Programmatically enable/disable toolbar, enable/disable and show/hide toolbar items. Lists the toolbar items available for toolbars. Enable/disable form designer, annotation or primary toolbars during initialization. Create a custom toolbar item |
| toolbar-reference.md | Use the toolbar API methods/properties to show/hide the primary/annotation/navigation/redaction toolbars. |
| toolbar-customization-scenarios.md | Common toolbar customization scenarios |
Annotations and Markup
| File | Purpose |
|---|---|
| annotation-overview.md | Information about ink/freehand, sticky notes/comments, handwritten/digital signatures annotations and programmatically adding them. Overall annotation types and common default annotation settings example |
| text-markup-annotations.md | Programmatically add text markup annotations (Highlight, underline, strikethrough, squiggly). Manipulate default settings for each textmarkup annotations |
| shape-annotations.md | Information on shape annotations (Line, Arrow, Rectangle, Circle, Polygon). Programmatically adding shape annotations and manipulating default shape settings for each shape annotations |
| measurement-annotations.md | Information on measurement annotations (Distance, Perimeter, Area, Radius, Volume). Programmatically adding measurement annotations and manipulating default settings for each measurement annotations |
| stamp-annotation.md | Information on stamp annotations and different types of stamps available. Programmatically adding stamp annotations |
| free-text-annotations.md | Information on free text annotation. Programmatically adding free text annotations |
| annotation-settings.md | Configure appearance (colors, opacity, borders, styles) and behavior (restrictions, locking, printing) for all annotation types. Apply settings globally or per annotation type. Customize annotation selector (resizer, selection border). Set author, subject, and custom data. Control annotation-related component properties (toolbar visibility, signature settings, export options, drawing constraints). |
| annotation-events.md | Handle annotation lifecycle events (add, delete, move, resize, select, property change). |
| annotation-operations.md | Programmatically manipulate annotations like selection, moving and resizing, deleting, locking and importing and exporting annotations |
| annotation-use-cases.md | Common scenarios on how annotations can be programmatically manipulated |
| shape-label-settings.md | Configure shape and measure annotation label appearance (fill color, font, font size, opacity) and default content (label text, notes). |
| redaction-annotation.md | Hide and permanently remove sensitive information in PDFs. Mark content by area or full page, configure overlay text and styling, apply redactions irreversibly, search text and auto-redact, and manage redaction annotations programmatically. |
Forms Management
| File | Purpose |
|---|---|
| form-fields-overview.md | Fill and design PDF forms, manage form fields (field types like textbox/password/checkbox/radio/dropdown/listbox/signature), create fields programmatically, use the form designer toolbar/UI interactions, configure field properties/customization, apply validation rules and constraints/settings, use form field API methods, and handle import/export form data including custom field data. |
| supported-form-fields.md | Supported form field types and programmatically add each |
| form-fields-props.md | Lists properties of form fields. Lists common properties and specific properties to each field. Manipulate form field settings |
| import-export-form-data.md | Programmatically import and export form field data |
| form-operations.md | Programmatically manipulate form fields including updating properties and values, moving and resizing, deleting, grouping, adding custom data & retrieving form field data |
| form-field-validation.md | Enable/disable form field validation. Programmatic flow of form field validation and examples |
| form-field-settings.md | Configure default properties for form fields (text, checkbox, radio, dropdown, signature). |
| form-field-events.md | Handle form field interaction events (focus, blur, value change, validation). |
Text Operations
| File | Purpose |
|---|---|
| text-search.md | Implement text search in PDFs: search functionality, search options (case-sensitive/whole word), highlight search results, find next/previous occurrences, programmatic text search methods, search completion events, and custom highlight colors. Configure text extraction options/settings and programmatically extract text from pages. |
| text-selection.md | Enable text selection and text extraction: selection modes/behavior, copy selected text, text selection events, programmatic selection and text collections/bounds. |
Document Operations
| File | Purpose |
|---|---|
| opening-pdfs.md | Load PDFs from URL/local paths/base64, open encrypted/password-protected PDFs, support programmatic document loading, handle document load events/lifecycle, and manage load failures/errors. |
| saving-and-downloading.md | Download PDFs, save PDFs with annotations/modifications, download with form data included, retrieve PDFs as base64, customize download events, and set custom download filenames. |
| printing-and-organizing.md | Print PDFs (including print options like page range/quality and silent printing), handle print events, organize pages (overview/rearrange/reorder/rotate/delete), copy/duplicate/extract pages to a new document, and use the page organizer toolbar with programmatic + mobile page organization. |
⚙️ 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" |
---
Syncfusion ASP.NET MVC PDF Viewer — Skill
Overview
The syncfusion-aspnetmvc-pdf-viewer skill enables AI-assisted code generation for the Syncfusion ASP.NET MVC PDF Viewer. It produces minimal, copy-pasteable Razor markup and C# code to embed, configure, and interact with PDF documents inside ASP.NET MVC web applications.
---
Compatibility
| Requirement | Version |
|---|---|
| .NET | .NET 8.0 LTS or later |
| .NET Framework | 4.6.2 or later |
| Operating System | Windows, Linux, or macOS |
| Development Tools | Visual Studio 2022, Visual Studio Code, or JetBrains Rider |
| Web Browser | Modern browsers with HTML5 and WebAssembly support |
---
Skill Structure
syncfusion-aspnetmvc-pdf-viewer/
├── SKILL.md # Skill rules, routing, and code generation guidelines
├── README.md # This file
└── references/
├── getting-started.md # Minimal setup & initialization template
├── opening-pdfs.md # Load PDFs from various sources (URL, local, stream)
├── enable-properties.md # Feature toggle properties (toolbar, annotation, forms, etc.)
├── viewing-and-interaction.md # Display modes, interaction, and user control
├── navigation.md # Page navigation (first, last, next, previous, goto)
├── bookmark-navigation.md # Bookmark panel and outline navigation
├── magnification.md # Zoom levels, zoom modes, fit-to-page/width
├── text-selection.md # Enable text select, copy, and selection events
├── text-search.md # Find text in PDF with search options
├── toolbar-customization.md # Customize toolbar items, visibility, and behavior
├── contextmenu.md # Right-click context menu customization
├── annotation-overview.md # Annotation capabilities and types
├── annotation-settings.md # Annotation appearance (colors, opacity, author, styles)
├── annotation-events.md # Annotation lifecycle events (add, delete, move, etc.)
├── annotation-operations.md # Annotation API methods and programmatic control
├── annotation-use-cases.md # Common annotation patterns and workflows
├── shape-annotations.md # Rectangle, circle, line shape annotations
├── measurement-annotations.md # Measurement tool configurations
├── free-text-annotations.md # Text annotation creation and styling
├── stamp-annotation.md # Stamp annotations and presets
├── text-markup-annotations.md # Highlight, underline, strikethrough annotations
├── form-fields-overview.md # Form field capabilities and field types
├── form-fields-props.md # Form field properties and defaults
├── form-field-settings.md # Configure default properties for form fields
├── form-field-events.md # Form field interaction events (focus, blur, change)
├── form-field-validation.md # Form field validation and constraints
├── form-operations.md # Import/export form data and programmatic access
├── supported-form-fields.md # List of supported form field types
├── import-export-form-data.md # Import and export form field values
├── download.md # PDF download configuration and customization
├── printing-and-organizing.md # Print configuration and page organization
├── saving-and-downloading.md # Save and download options
├── api-methods.md # Programmatic API (load, export, undo/redo, extract)
└── events.md # Complete PDF Viewer event reference---
Quick Start
Step 1: Create ASP.NET MVC Project
1. Open Visual Studio and select Create a new project 2. Select ASP.NET Web Application (.NET Framework) 3. Enter your project name and location 4. Click Create 5. In the next dialog, select MVC as the project template 6. Click Create
Visual Studio 2022 Alternative:
1. Create a new project using ASP.NET MVC Web Application template 2. Select the target framework (.NET Framework 4.7.2 or later recommended) 3. Click Create
Step 2: Install NuGet Packages
Install the required Syncfusion NuGet package:
Package Manager Console:
Install-Package Syncfusion.EJ2.MVC5NuGet Package Manager UI: 1. Right-click project → Manage NuGet Packages 2. Search for Syncfusion.EJ2.MVC5 3. Click Install
Step 3: Add Namespace
Add the Syncfusion.EJ2 namespace to Web.config in the Views folder.
Open ~/Views/Web.config and locate the <namespaces> section. Add the following namespace:
<namespaces>
<add namespace="Syncfusion.EJ2"/>
</namespaces>Step 4: Add Styles (CDN)
Reference the Syncfusion theme in ~/Views/Shared/_Layout.cshtml inside the <head> tag:
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewBag.Title - PDF Viewer</title>
<!-- Syncfusion ASP.NET MVC controls styles -->
<link rel="stylesheet" href="https://cdn.syncfusion.com/ej2/31.1.23/fluent.css" />
</head>Step 5: Add Scripts (CDN)
Add the Syncfusion JavaScript library in _Layout.cshtml inside the <head> tag:
<head>
<!-- ... theme CSS ... -->
<!-- Syncfusion ASP.NET MVC controls scripts -->
<script src="https://cdn.syncfusion.com/ej2/31.1.23/dist/ej2.min.js"></script>
</head>Step 6: Register Script Manager
Register the Syncfusion script manager at the end of the `<body>` tag in _Layout.cshtml:
<body>
<!-- Other content -->
<!-- Syncfusion ASP.NET MVC Script Manager -->
@Html.EJS().ScriptManager()
</body>Important: The @Html.EJS().ScriptManager() must be placed at the end of the <body> element to ensure proper initialization.
Step 7: Add PDF Viewer Component
Add the PDF Viewer to ~/Views/Home/Index.cshtml:
@{
ViewBag.Title = "Home Page";
}
<div>
<div style="height:500px;width:100%;">
@Html.EJS().PdfViewer("pdfviewer").DocumentPath("https://cdn.syncfusion.com/content/pdf/pdf-succinctly.pdf").Render()
</div>
</div>Component Properties:
PdfViewer()- Creates a PDF Viewer component with the specified IDDocumentPath()- URL or path to the PDF document to display (required)Render()- Renders the component HTML
Note: The DocumentPath property is essential for loading a PDF file in the PDF Viewer.
Step 8: Configure Local Resources (Standalone)
To load resources locally with the PDF Viewer, follow these steps:
Step 8a: Create the folder structure under Content:
Content/
├── ej2-pdfviewer-lib/
│ ├── pdfium.js
│ └── pdfium.wasm
└── pdfsuccinctly.pdfStep 8b: Update Index.cshtml to use local paths:
@{
ViewBag.Title = "Home Page";
var originUrl = $"{Request.Url.Scheme}://{Request.Url.Authority}";
var document = originUrl + "/Content/pdfsuccinctly.pdf";
var resourceUrl = originUrl + "/Content/ej2-pdfviewer-lib";
}
<div style="height: 900px;width:100%;">
@Html.EJS().PdfViewer("pdfviewer").ResourceUrl(@resourceUrl).DocumentPath(@document).Render()
</div>Property Explanations:
DocumentPath()- Full URL to the PDF file (must be publicly accessible)ResourceUrl()- URL to the folder containing pdfium.js and pdfium.wasm files
---
Available Features
| Feature | Property | Description |
|---|---|---|
| Toolbar | enableToolbar | Show/hide the main toolbar |
| Navigation | enableNavigation | Enable page navigation controls |
| Annotations | enableAnnotation | Enable all annotation capabilities |
| Form Fields | enableFormFields | Support interactive form fields |
| Bookmarks | enableBookmark | Display bookmark/outline panel |
| Thumbnails | enableThumbnail | Show page thumbnail panel |
| Text Search | enableTextSearch | Enable find-in-document functionality |
| Text Selection | enableTextSelection | Allow text selection and copy |
enablePrint | Enable print functionality | |
| Download | enableDownload | Enable PDF download |
| Hyperlinks | enableHyperlink | Make URLs clickable |
---
Reference File Routing
Use the table below to find the correct reference file for any feature.
MVC Setup
| Reference File | Use When … |
|---|---|
getting-started.md | Getting started, minimal setup, loading a PDF |
opening-pdfs.md | Loading PDFs from URLs, local files, or streams |
enable-properties.md | Enabling/disabling toolbar, annotations, forms, download, print |
Navigation
| Reference File | Use When … |
|---|---|
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 |
viewing-and-interaction.md | Display modes, interaction, and zoom behavior |
Viewing & Interaction
| Reference File | Use When … |
|---|---|
magnification.md | Zoom controls, fit-to-page, fit-to-width, zoom levels |
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-customization.md | Customize toolbar items, visibility, and tooltip behavior |
contextmenu.md | Add, remove, or handle right-click context menu items |
Annotations
| Reference File | Use When … |
|---|---|
annotation-overview.md | Overview of annotation types and capabilities |
annotation-settings.md | Set default annotation colors, opacity, author, styles |
annotation-events.md | Handle annotation add/delete/move/resize/select events |
annotation-operations.md | Programmatic annotation API and methods |
annotation-use-cases.md | Common annotation patterns and workflows |
shape-annotations.md | Rectangle, circle, line shape annotations |
measurement-annotations.md | Measurement tool configurations |
free-text-annotations.md | Text annotation creation and styling |
stamp-annotation.md | Stamp annotations and presets |
text-markup-annotations.md | Highlight, underline, strikethrough annotations |
Forms
| Reference File | Use When … |
|---|---|
form-fields-overview.md | Overview of form field capabilities |
form-fields-props.md | Form field properties and defaults |
form-field-settings.md | Configure default properties for form fields |
form-field-events.md | Handle form field focus, blur, and value-change events |
form-field-validation.md | Form field validation and constraints |
form-operations.md | Import/export form data and programmatic access |
supported-form-fields.md | List of supported form field types |
import-export-form-data.md | Import and export form field values |
Document Actions
| Reference File | Use When … |
|---|---|
download.md | Enable download and set custom filenames |
printing-and-organizing.md | Configure printing and page organization |
saving-and-downloading.md | Save and download options |
Advanced / API
| Reference File | Use When … |
|---|---|
api-methods.md | Load documents programmatically, export form data, undo/redo |
events.md | Browse all available PDF Viewer events and signatures |
---
Annotation Events
Brief: Annotation events in ASP.NET MVC 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.
How to Use the Event in PDF Viewer
@Html.EJS().PdfViewer("pdfviewer").EventName("eventHandler").Render()
<script type="text/javascript">
function eventHandler(args) {
// Method Execution
console.log('Event triggered:', args);
}
</script>Note: The complete setup and component structure is available in the getting-started.md file.
---
Annotation Events
| Event Name | Description | Args | Args Properties |
|---|---|---|---|
| AnnotationAdd | Fires when an annotation is added to a page in the PDF document. | AnnotationAddEventArgs | annotationId - (string) - Unique identifier of the annotation. pageIndex - (number) - Page index where the annotation was added. annotation - (object) - Annotation object containing all properties. annotationAddMode - (string) - Mode of annotation addition (UI Drawn, Programmatic, etc.). |
| AnnotationDoubleClick | Fires when an annotation is double-clicked. | AnnotationDoubleClickEventArgs | annotationId - (string) - ID of the annotation that was double-clicked. pageIndex - (number) - Page index where the annotation was double-clicked. annotation - (object) - Annotation object containing all properties. |
| AnnotationMouseLeave | Fires when the mouse pointer moves away from an annotation object. | AnnotationMouseLeaveEventArgs | annotationId - (string) - ID of the annotation. pageIndex - (number) - Page index of the annotation. |
| AnnotationMouseover | Fires when the mouse pointer moves over an annotation object. | AnnotationMouseOverEventArgs | annotationId - (string) - ID of the annotation. pageIndex - (number) - Page index of the annotation. X - (number) - X coordinate of mouse position. Y - (number) - Y coordinate of mouse position. |
| AnnotationMove | Fires when an annotation is moved on a page in the PDF document. | AnnotationMoveEventArgs | annotationId - (string) - ID of the annotation that was moved. pageIndex - (number) - Page index where the annotation was moved. annotation - (object) - Updated annotation object. |
| AnnotationMoving | Fires while an annotation is being moved. | AnnotationMovingEventArgs | annotationId - (string) - ID of the annotation being moved. pageIndex - (number) - Page index. currentPosition - (object) - Current position during movement. |
| AnnotationPropertiesChange | Fires when the properties of an annotation are modified on a PDF page. | AnnotationPropertiesChangeEventArgs | annotationId - (string) - ID of the annotation. pageIndex - (number) - Page index. isColorChanged - (boolean) - Indicates if color was changed. isThicknessChanged - (boolean) - Indicates if thickness was changed. isOpacityChanged - (boolean) - Indicates if opacity was changed. annotation - (object) - Updated annotation object. |
| AnnotationRemove | Fires when an annotation is removed from a page in the PDF document. | AnnotationRemoveEventArgs | annotationId - (string) - ID of the removed annotation. pageIndex - (number) - Page index where the annotation was removed. annotation - (object) - Annotation object that was removed. |
| AnnotationResize | Fires when an annotation is resized on a page in the PDF document. | AnnotationResizeEventArgs | annotationId - (string) - ID of the resized annotation. pageIndex - (number) - Page index. annotation - (object) - Updated annotation object with new bounds. |
| AnnotationSelect | Fires when an annotation is selected on a page in the PDF document. | AnnotationSelectEventArgs | annotationId - (string) - ID of the selected annotation. pageIndex - (number) - Page index. annotation - (object) - Selected annotation object. annotationCollection - (array) - Collection of overlapping annotations. isMultiSelect - (boolean) - Indicates if multiple annotations are selected. |
| AnnotationUnSelect | Fires when an annotation is unselected on a page in the PDF document. | AnnotationUnSelectEventArgs | annotationId - (string) - ID of the unselected annotation. pageIndex - (number) - Page index where the annotation was unselected. |
| BeforeAddFreeText | Fires before a free-text annotation is added. | BeforeAddFreeTextEventArgs | pageIndex - (number) - Page index where the annotation will be added. cancel - (boolean) - Set to true to prevent the annotation from being added. |
| AddSignature | Fires when a signature is added to a page of a PDF document. | AddSignatureEventArgs | pageIndex - (number) - Page index where the signature was added. signature - (object) - Signature object with properties like bounds, opacity, strokeColor, thickness. |
| RemoveSignature | Fires when the signature is removed from the page of a PDF document. | RemoveSignatureEventArgs | pageIndex - (number) - Page index where the signature was removed. signature - (object) - Signature object that was removed. |
| ResizeSignature | Fires when the signature is resized on a page in the PDF document. | ResizeSignatureEventArgs | pageIndex - (number) - Page index. signature - (object) - Updated signature object with new bounds. previousPosition - (object) - Previous position before resize. currentPosition - (object) - Current position after resize. |
| SignaturePropertiesChange | Fires when the properties of a signature are changed on a page in the PDF document. | SignaturePropertiesChangeEventArgs | pageIndex - (number) - Page index. isThicknessChanged - (boolean) - Indicates if thickness was changed. isOpacityChanged - (boolean) - Indicates if opacity was changed. isStrokeColorChanged - (boolean) - Indicates if stroke color was changed. signature - (object) - Updated signature object. |
| SignatureSelect | Fires when a signature is selected on a page in the PDF document. | SignatureSelectEventArgs | pageIndex - (number) - Page index where the signature was selected. signature - (object) - Selected signature object. |
| SignatureUnselect | Fires when a signature is unselected on a page in the PDF document. | SignatureUnSelectEventArgs | pageIndex - (number) - Page index where the signature was unselected. |
---
Annotation Object Reference
| 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 |
| TextMarkup Properties | ||
| 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 | ||
| 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 | ||
| 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 | ||
| data | Path data for ink annotation (SVG path format). | string |
| Stamp Properties | ||
| 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 | ||
| 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 |
Rect Object
| 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
| 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
| 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
| 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
| 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
| 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
| 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
| 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
| Property Name | Description | Data type |
|---|---|---|
| x | X coordinate of the vertex. | number |
| y | Y coordinate of the vertex. | number |
---
Common Use Cases
Tracking Annotation Changes
<script>
function onAnnotationMove(args) {
// Track annotation movement for telemetry
logEvent('annotation_moved', {
annotationId: args.annotationId,
page: args.pageIndex,
timestamp: new Date().toISOString()
});
}
</script>Preventing Certain Actions
<script>
function onBeforeAddFreeText(args) {
// Prevent free text annotation on specific pages
if (args.pageIndex === 0) {
args.cancel = true;
}
}
</script>Accessing Annotation Properties
<script>
function onAnnotationSelect(args) {
// Access complete annotation details
const annotation = args.annotation;
console.log('Color:', annotation.color);
console.log('Opacity:', annotation.opacity);
console.log('Type:', annotation.type);
console.log('Author:', annotation.author);
console.log('Bounds:', annotation.bounds);
console.log('Rect:', annotation.rect);
// Update UI with annotation properties
updatePropertiesPanel(args.annotationId, annotation);
}
</script>Validating Property Changes
<script>
function onAnnotationPropertiesChange(args) {
if (args.isColorChanged) {
console.log('Annotation color changed to:', args.annotation.color);
}
if (args.isThicknessChanged) {
console.log('Annotation thickness changed');
}
if (args.isOpacityChanged) {
console.log('Annotation opacity changed to:', args.annotation.opacity);
}
}
</script>Handling Multiple Selections
<script>
function onAnnotationSelect(args) {
if (args.isMultiSelect) {
console.log('Multiple annotations selected');
console.log('Selected annotations count:', args.annotationCollection.length);
args.annotationCollection.forEach((annotation) => {
console.log('Annotation ID:', annotation.annotationId);
});
} else {
console.log('Single annotation selected:', args.annotationId);
}
}
</script>Common Annotation Operations
Selecting Annotations
Programmatic selection:
Select the annotations programmatically using annotation object or annotation Id using selectAnnotation(annotationId)
function selectAnnotation(annotationId) {
var viewer = document.getElementById('pdfviewer').ej2_instances[0];
viewer.annotation.selectAnnotation(annotationId);
}Parameter
| Parameter | Type | Description | Optional |
|---|---|---|---|
| annotationId | string or object | The annotation Id or the whole annotation that needs to be selected | No |
Returns
void
---
Moving and Resizing
Programmatic repositioning:
function moveAnnotation() {
var viewer = document.getElementById('pdfviewer').ej2_instances[0];
for (let i = 0; i < viewer.annotationCollection.length; i++) {
var annotation = viewer.annotationCollection[i];
if (annotation.annotationId === targetId) {
annotation.bounds.x = 150;
annotation.bounds.y = 200;
viewer.annotation.editAnnotation(annotation);
}
}
}---
Deleting Annotations
Delete the annotations programmatically using the deleteAnnotationById(annotationId) of the annotation module of PDF Viewer instance.
Programmatic deletion:
function deleteAnnotation(annotationId) {
var viewer = document.getElementById('pdfviewer').ej2_instances[0];
viewer.annotation.deleteAnnotationById(annotationId);
}Parameter
| Parameter | Type | Description | Optional |
|---|---|---|---|
| annotationId | string or object | The annotation Id or the whole annotation that needs to be deleted | No |
Returns
void
---
Locking Annotations
Locked annotations cannot be edited or deleted by users:
function lockAnnotation() {
var viewer = document.getElementById('pdfviewer').ej2_instances[0];
for (let i = 0; i < viewer.annotationCollection.length; i++) {
var annotation = viewer.annotationCollection[i];
if (annotation.annotationId === targetId) {
annotation.annotationSettings.isLock = true;
viewer.annotation.editAnnotation(annotation);
}
}
}Importing and Exporting
Export annotations programmatically using the exportAnnotation(AnnotationDataFormat) method of PDF Viewer instance.
Export annotations:
function exportAnnotations() {
var viewer = document.getElementById('pdfviewer').ej2_instances[0];
viewer.exportAnnotation();
}Parameter
| Parameter | Type | Description | Optional |
|---|---|---|---|
| annotationDataFormat | `AnnotationDataFormat` | The annotation data that needs to be imported | Yes |
Returns
void
Returns
void
Import annotations:
Import annotations using importAnnotation(importData, AnnotationDataFormat) method of PDF Viewer instance
function importAnnotations(annotationData) {
var viewer = document.getElementById('pdfviewer').ej2_instances[0];
viewer.importAnnotation(annotationData);
}Parameter
| Parameter | Type | Description | Optional |
|---|---|---|---|
| importData | any | The annotation data that needs to be imported | No |
| annotationDataFormat | `AnnotationDataFormat` | The annotation data that needs to be imported | Yes |
Returns
void
---
AnnotationDataFormat
Types for annotation file types
JsonXfdf
Type
string
Annotations Overview: ASP.NET MVC PDF Viewer
Purpose: Guide to implementing PDF annotations including shapes, text markup, stamps, ink drawings, sticky notes, free text, signatures, and measurements.
---
Table of Contents
1. Annotation Types and Capabilities 2. Ink Annotations 3. Sticky Notes 4. Handwritten Signatures 5. Configure Default Annotation Settings ---
Annotation Types and Capabilities
The PDF Viewer provides comprehensive annotation features for document markup, collaboration, and review workflows. Eight primary annotation categories support diverse use cases:
| Annotation Type | Use Cases | Key Features |
|---|---|---|
| Shape | Diagrams, callouts, highlighting areas | Lines, arrows, rectangles, circles, polygons |
| Text Markup | Document review, proofreading | Highlight, underline, strikethrough |
| Stamp | Approval workflows, document status | Dynamic, sign here, standard business, custom |
| Ink | Freehand drawing, sketches | Natural drawing with mouse/touch/stylus |
| Sticky Notes | Comments, discussions | Clickable note markers with threaded comments |
| Free Text | Labels, captions, document filling | Formatted text boxes with styling control |
| Signature | Document authentication, approval | Drawn, typed, or uploaded signatures |
| Measurement | Dimensional analysis, calculations | Distance, perimeter, area, radius, volume |
Common capabilities across all annotation types:
- Programmatic creation and editing via APIs
- Toolbar-based UI for manual addition
- Customizable appearance (colors, thickness, opacity)
- Default property configuration
- Save/load annotation data
- Annotation locking and permissions
---
Ink Annotations
Ink annotations enable freehand drawing for sketches, handwritten marks, and signatures using mouse, touchpad, or stylus input.
Adding Ink Annotations
Programmatic creation:
function addInkAnnotation() {
var viewer = document.getElementById('pdfviewer').ej2_instances[0];
viewer.annotation.addAnnotation("Ink", {
offset: { x: 150, y: 100 },
pageNumber: 1,
width: 200,
height: 60,
path: '[{"command":"M","x":244.83,"y":982.00},{"command":"L","x":250.83,"y":953.33}...]' // SVG path data
});
}Customizing Ink Appearance
Available properties:
- Stroke Color - Drawing line color
- Thickness - Line width (1-12px range)
- Opacity - Transparency (0.0-1.0 range)
Default settings:
@Html.EJS().PdfViewer("pdfviewer").InkAnnotationSettings(new Syncfusion.EJ2.PdfViewer.PdfViewerInkAnnotationSettings {Author="Reviewer", StrokeColor="green", Thickness=3, Opacity=0.6}).Render()---
Sticky Notes
Sticky notes provide clickable markers for attaching comments and threaded discussions to specific document locations.
Adding Sticky Notes
Via toolbar: 1. Click Comments button in toolbar 2. Click on desired page location 3. Sticky note marker appears at clicked position 4. Right-click note → Select Comment to add text
Programmatic creation:
function addStickyNote() {
var viewer = document.getElementById('pdfviewer').ej2_instances[0];
viewer.annotation.addAnnotation("StickyNotes", {
offset: { x: 100, y: 200 },
pageNumber: 1,
isLock: false
});
}Working with Comments
Comment operations:
- Add new comment text
- Edit existing comments
- Delete comments
- Reply to comments (threaded discussions)
- Mark comment status (Review/Done/Cancelled)
Comment panel:
- Access via Comment Panel button in toolbar
- View all comments across document
- Filter by status or author
- Navigate to comment locations
Default Settings
@Html.EJS().PdfViewer("pdfviewer").StickyNotesSettings(new Syncfusion.EJ2.PdfViewer.PdfViewerStickyNotesSettings {Author="Reviewer", Opacity=0.9}).Render()---
Handwritten Signatures
Handwritten signature annotations enable digital document signing with drawn, typed, or uploaded signature formats.
Enabling Signatures
@Html.EJS().PdfViewer("pdfviewer").EnableHandwrittenSignature(true).Render()Adding Signatures
Programmatic creation:
function addHandwrittenSignature() {
var viewer = document.getElementById('pdfviewer').ej2_instances[0];
viewer.annotation.addAnnotation("HandWrittenSignature", {
offset: { x: 220, y: 180 },
pageNumber: 1,
width: 150,
height: 60,
signatureItem: ['Signature'],
signatureDialogSettings: {
displayMode: ej.pdfviewer.DisplayMode.Draw
},
canSave: true,
path: '[{"command":"M","x":244.83...}]' // SVG path for drawn signature
});
}Signature vs. Initial
The PDF Viewer supports two signature annotation types:
- Signature - Full signature for primary signing
- Initial - Abbreviated initials for secondary approval
Both use identical capture methods and configuration.
Default Signature Settings
@Html.EJS().PdfViewer("pdfviewer").HandWrittenSignatureSettings(new Syncfusion.EJ2.PdfViewer.PdfViewerHandWrittenSignatureSettings {Opacity=0.7, StrokeColor="blue", Thickness=2}).Render()---
Default Annotation Settings
Configure consistent annotation behavior across the PDF Viewer by setting default properties during initialization:
Comprehensive Configuration Example
<!--Standalone Mode with All Annotation Settings-->
@Html.EJS().PdfViewer("pdfviewer").LineSettings=(new Syncfusion.EJ2.PdfViewer.PdfViewerLineSettings {FillColor="blue", Opacity=0.6, StrokeColor="green", Thickness=2}).ArrowSettings=(new Syncfusion.EJ2.PdfViewer.PdfViewerArrowSettings {FillColor="green", Opacity=0.6, StrokeColor="blue"}).RectangleSettings=(new Syncfusion.EJ2.PdfViewer.PdfViewerRectangleSettings {FillColor="yellow", Opacity=0.6, StrokeColor="orange"}).CircleSettings=(new Syncfusion.EJ2.PdfViewer.PdfViewerCircleSettings {FillColor="orange", Opacity=0.6, StrokeColor="pink"}).PolygonSettings=(new Syncfusion.EJ2.PdfViewer.PdfViewerPolygonSettings {FillColor="pink", Opacity=0.6, StrokeColor="yellow"}).StampSettings=(new Syncfusion.EJ2.PdfViewer.PdfViewerStampSettings {Opacity=0.3, Author="Reviewer"}).StickyNotesSettings=(new Syncfusion.EJ2.PdfViewer.PdfViewerStickyNotesSettings {Author="Reviewer"}).FreeTextSettings=(new Syncfusion.EJ2.PdfViewer.PdfViewerFreeTextSettings {FillColor="lightblue", BorderColor="navy", FontColor="black"}).InkAnnotationSettings=(new Syncfusion.EJ2.PdfViewer.PdfViewerInkAnnotationSettings {Author="Reviewer", StrokeColor="red", Thickness=3, Opacity=0.6}).HandWrittenSignatureSettings=(new Syncfusion.EJ2.PdfViewer.PdfViewerHandWrittenSignatureSettings {Opacity=0.7, StrokeColor="darkblue", Thickness=2}).DistanceSettings=(new Syncfusion.EJ2.PdfViewer.PdfViewerDistanceSettings {FillColor="blue", Opacity=0.6, StrokeColor="green"}).PerimeterSettings=(new Syncfusion.EJ2.PdfViewer.PdfViewerPerimeterSettings {FillColor="green", Opacity=0.6, StrokeColor="blue"}).AreaSettings=(new Syncfusion.EJ2.PdfViewer.PdfViewerAreaSettings {FillColor="yellow", Opacity=0.6, StrokeColor="orange"}).RadiusSettings=(new Syncfusion.EJ2.PdfViewer.PdfViewerRadiusSettings {FillColor="orange", Opacity=0.6, StrokeColor="pink"}).VolumeSettings=(new Syncfusion.EJ2.PdfViewer.PdfViewerVolumeSettings {FillColor="pink", Opacity=0.6, StrokeColor="yellow"}).MeasurementSettings=(new Syncfusion.EJ2.PdfViewer.PdfViewerMeasurementSettings {ScaleRatio=1, ConversionUnit=Syncfusion.EJ2.PdfViewer.CalibrationUnit.In}).Render()---
Annotation Settings in ASP.NET MVC PDF Viewer Component
It provides functionality to manage and initialize annotation settings for a PDF viewer, such as author details, custom data, interaction settings, and restrictions on download or printing. It ensures that the settings are initialized and updated whenever parameters are set.
How to Use the Settings in PDF Viewer (Need to use any one of the below implementations)
Usage
@Html.EJS().PdfViewer("pdfviewer").HighlightSettings(new Syncfusion.EJ2.PdfViewer.PdfViewerHighlightSettings { Color = "green", Opacity = 0.6 }).Render()Note: The complete setup and component structure is available in the getting-started.md file.
List of Annotations
| 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 |
List of Settings in PdfViewer
| Property Name | Description |
|---|---|
| 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 |
Settings Properties Reference
Defines the annotation selector settings for all types of annotations.
Annotation-Related Component Properties
Apply for All Annotations
These properties are available 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" |
| 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 |
AnnotationSelectorSettings
Defines the annotation selector settings for all types of annotations. See table for the properties of annotation selector settings.
Apply for All Annotations
@Html.EJS().PdfViewer("pdfviewer").AnnotationSelectorSettings(new Syncfusion.EJ2.PdfViewer.PdfViewerAnnotationSelectorSettings { ResizerBorderColor = "green" }).Render()Apply for Specific Annotation Type
@Html.EJS().PdfViewer("pdfviewer").AreaSettings(new Syncfusion.EJ2.PdfViewer.PdfViewerAreaSettings { AnnotationSelectorSettings = new Syncfusion.EJ2.PdfViewer.PdfViewerAnnotationSelectorSettings { ResizerBorderColor = "green" } }).Render()Note: The complete setup and component structure is available in the getting-started.md file.
List of Settings Properties
| 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 |
AnnotationDrawingOptions
| Name | Description | Data Type |
|---|---|---|
| enableLineAngleConstraints | Enables angular constraints for line-type annotations. | |
When set to true, lines and arrows are restricted to fixed angles defined by the restrictLineAngleTo property. | boolean | |
| restrictLineAngleTo | Specifies the angle (in degrees) to which line-type annotations are constrained. | number |
SignatureFitMode
- Default
- Stretch
SignatureDialogSettings
| Name | Description | Data Type |
|---|---|---|
| displayMode | Get or set the required signature options will be enabled in the signature dialog. | `DisplayMode` |
| hideSaveSignature | Get or set a boolean value to show or hide the save signature check box option in the signature dialog. | boolean |
DisplayMode
| Name | Description | Data Type |
|---|---|---|
| Draw | Display only the draw option in the signature dialog. | enum |
| Text | Display only the text option in the signature dialog. | enum |
| Upload | Display only the upload option in the signature dialog. | enum |
Common Annotation Use Cases
1. Document Review and Approval Workflow
Scenario: Legal department reviewing contracts
// Reviewer adds comments and stamps
function reviewDocument() {
var viewer = document.getElementById('pdfviewer').ej2_instances[0];
// Add sticky note for clause discussion
viewer.annotation.addAnnotation("StickyNotes", {
offset: { x: 450, y: 200 },
pageNumber: 2
});
// Add highlight to important section
viewer.annotation.setAnnotationMode('Highlight');
// User selects text, then:
// Add approval stamp
viewer.annotation.addAnnotation("Stamp", {
offset: { x: 400, y: 700 },
pageNumber: 5
}, 'Approved');
}2. Technical Drawing Markup
Scenario: Engineering team reviewing blueprints
// Add measurement annotations with scale
function markupBlueprint() {
var viewer = document.getElementById('pdfviewer').ej2_instances[0];
// Configure scale (1 inch = 10 feet)
viewer.measurementSettings = {
scaleRatio: 10,
conversionUnit: ej.pdfviewer.CalibrationUnit.Ft
};
// Add distance measurement
viewer.annotation.addAnnotation("Distance", {
offset: { x: 100, y: 150 },
pageNumber: 1,
vertexPoints: [{ x: 100, y: 150 }, { x: 400, y: 150 }]
});
// Add area calculation for room
viewer.annotation.addAnnotation("Area", {
offset: { x: 150, y: 300 },
pageNumber: 1,
vertexPoints: [
{ x: 150, y: 300 },
{ x: 350, y: 300 },
{ x: 350, y: 500 },
{ x: 150, y: 500 },
{ x: 150, y: 300 }
]
});
}3. Form Filling and Signature Collection
Scenario: HR collecting signed employment agreements
// Add form fields and signature placeholders
function prepareEmploymentForm() {
var viewer = document.getElementById('pdfviewer').ej2_instances[0];
// Add free text fields for employee information
viewer.annotation.addAnnotation("FreeText", {
offset: { x: 200, y: 100 },
pageNumber: 1,
width: 200,
height: 30,
defaultText: "Employee Name:",
fontSize: 12,
fontFamily: "Arial"
});
// Add signature placeholder
viewer.annotation.addAnnotation("FreeText", {
offset: { x: 200, y: 650 },
pageNumber: 3,
width: 200,
height: 40,
defaultText: "Signature:",
fontSize: 10,
borderStyle: 'dashed',
borderColor: 'gray'
});
// Add date stamp
viewer.annotation.addAnnotation("Stamp", {
offset: { x: 450, y: 650 },
pageNumber: 3
}, 'Final');
}4. Collaborative Document Review
Scenario: Team reviewing project proposal
// Multiple reviewers adding feedback
function collaborativeReview() {
var viewer = document.getElementById('pdfviewer').ej2_instances[0];
// Configure author for tracking
viewer.stickyNotesSettings = {
author: "John Doe"
};
// Add sticky note with comment
viewer.annotation.addAnnotation("StickyNotes", {
offset: { x: 500, y: 250 },
pageNumber: 1,
author: "John Doe"
});
// User adds comment text via UI
// Highlight key section
viewer.annotation.setAnnotationMode('Highlight');
// User selects text
// Add strikethrough for suggested deletion
viewer.annotation.setAnnotationMode('Strikethrough');
// User selects text to mark
}5. Quality Assurance Markup
Scenario: QA team marking defects on product diagrams
// Add visual markers for issues
function markDefects() {
var viewer = document.getElementById('pdfviewer').ej2_instances[0];
// Circle defect location
viewer.annotation.addAnnotation("Circle", {
offset: { x: 250, y: 300 },
pageNumber: 1,
width: 60,
height: 60,
strokeColor: "red",
thickness: 3
});
// Add arrow pointing to issue
viewer.annotation.addAnnotation("Arrow", {
offset: { x: 280, y: 330 },
pageNumber: 1,
vertexPoints: [
{ x: 280, y: 330 },
{ x: 350, y: 380 }
],
strokeColor: "red"
});
// Add free text note
viewer.annotation.addAnnotation("FreeText", {
offset: { x: 360, y: 380 },
pageNumber: 1,
width: 150,
height: 60,
defaultText: "Defect ID: QA-2024-001\nSeverity: High\nArea: Top-right corner",
fontSize: 10,
fillColor: "lightyellow",
borderColor: "red"
});
}6. Educational Content Annotation
Scenario: Instructor marking up course materials
// Add teaching annotations
function annotateCourseMaterial() {
var viewer = document.getElementById('pdfviewer').ej2_instances[0];
// Highlight key concepts
viewer.annotation.setAnnotationMode('Highlight');
// Instructor selects important text
// Add sticky note with additional explanation
viewer.annotation.addAnnotation("StickyNotes", {
offset: { x: 50, y: 200 },
pageNumber: 3
});
// Draw attention arrow
viewer.annotation.addAnnotation("Arrow", {
offset: { x: 100, y: 400 },
pageNumber: 3,
vertexPoints: [
{ x: 100, y: 400 },
{ x: 250, y: 450 }
],
strokeColor: "blue",
thickness: 2
});
// Add text box with study tip
viewer.annotation.addAnnotation("FreeText", {
offset: { x: 260, y: 455 },
pageNumber: 3,
width: 200,
height: 50,
defaultText: "💡 Study Tip: Review section 3.2 before exam",
fontSize: 11,
fillColor: "lightgreen"
});
}API Methods in ASP.NET MVC PdfViewer Component
The ASP.NET MVC PdfViewer component provides comprehensive API methods to control and interact with PDF documents, form fields, annotations, and viewer functionality. These methods enable programmatic access to all major operations.
List of Methods
| Method Name | Description | Parameters | Return Type |
|---|---|---|---|
| addAnnotation | Adds an annotation to the PDF document at the specified location | annotation: PdfAnnotationBase | void |
| addCustomMenu | Adds a custom menu item to the context menu of the PDF viewer | items: CustomToolbarItem[], targetId: string | void |
| clearFormFields | Clears all form field values in the PDF document | - | void |
| convertClientPointToPagePoint | Converts a client point (screen coordinates) to page point coordinates | clientPoint: IPoint | IPoint |
| convertPagePointToClientPoint | Converts a page point to client point (screen coordinates) | pagePoint: IPoint | IPoint |
| convertPagePointToScrollingPoint | Converts a page point to scrolling point coordinates within the viewport | pagePoint: IPoint | IPoint |
| deleteAnnotations | Deletes specified annotations from the PDF document | annotationId: string | void |
| destroy | Destroys the PdfViewer component and releases its resources | - | void |
| download | Downloads the current PDF document to the client machine | - | void |
| exportAnnotation | Exports annotations from the PDF document as a string in JSON format | - | string |
| exportAnnotationsAsBase64String | Exports annotations from the PDF document as a Base64 encoded string | - | string |
| exportAnnotationsAsObject | Exports annotations from the PDF document as a JSON object | - | object |
| exportFormFields | Exports form fields data from the PDF document as XML string | - | string |
| exportFormFieldsAsObject | Exports form fields data from the PDF document as a JSON object | - | object |
| extractPages | Extracts specified pages from the PDF document | pageIndexes: number[] | void |
| extractText | Extracts text from the PDF document based on the selection region | pageIndex: number, options: `string` | Promise<{textData, pageText}> |
| focusFormField | Sets focus to a specific form field in the PDF document | fieldName: string | void |
| getPageInfo | Retrieves information about a specific page in the PDF document | pageIndex: number | PageInfo |
| getPageNumberFromClientPoint | Gets the page number at a specific client point (screen coordinates) | clientPoint: IPoint | number |
| importAnnotation | Imports annotations into the PDF document from a JSON string | annotationData: string | void |
| importFormFields | Imports form field data into the PDF document from XML format | formFieldData: string | void |
| load | Loads a PDF document from a specified URL or file path | document: `string \ | Blob` |
| redo | Redoes the last undone action in the PDF viewer | - | void |
| resetFormFields | Resets all form field values to their default values | - | void |
| retrieveFormFields | Retrieves all form field data from the PDF document | - | FormField[] |
| saveAsBlob | Saves the current PDF document as a Blob object | - | Blob |
| setJsonData | Sets JSON data for the PDF viewer configuration and state | jsonData: string | void |
| showNotificationPopup | Displays a notification popup message in the PDF viewer | message: string, timeout?: number | void |
| undo | Undoes the last action performed in the PDF viewer | - | void |
| unload | Unloads the currently loaded PDF document from the viewer | - | void |
| updateFormFields | Updates specific form fields in the PDF document | formFields: FormField[] | void |
| updateFormFieldsValue | Updates the values of form fields in the PDF document | fieldName: string, fieldValue: string | void |
| updateViewerContainer | Updates the PDF viewer container size and layout | - | void |
| zoomToRect | Zooms the PDF viewer to fit a specific rectangular region | rect: IRect | void |
Common Parameter Types
IPoint
Used for coordinate points in the PDF viewer.
| Property | Description | Data Type |
|---|---|---|
| x | The x-coordinate value | number |
| y | The y-coordinate value | number |
IRect
Used for rectangular regions in the PDF document.
| Property | Description | Data Type |
|---|---|---|
| x | The x-coordinate of the top-left corner | number |
| y | The y-coordinate of the top-left corner | number |
| width | The width of the rectangle | number |
| height | The height of the rectangle | number |
PageInfo
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 |
FormField
Represents a form field in the PDF document.
| Property | Description | Data Type |
|---|---|---|
| name | The name of the form field | string |
| value | The current value of the form field | string |
| fieldType | The type of form field (text, checkbox, radio, etc.) | string |
PdfAnnotationBase
Base class for PDF annotations.
| Property | Description | Data Type |
|---|---|---|
| annotationType | The type of annotation | string |
| pageIndex | The page index where annotation is placed | number |
| bounds | The bounds of the annotation | IRect |
CustomToolbarItem
Represents a custom toolbar menu item.
| Property | Description | Data Type |
|---|---|---|
| id | Unique identifier for the menu item | string |
| text | Display text for the menu item | string |
| tooltipText | Tooltip text for the menu item | string |
ExtractTextOptions
Represents a custom toolbar menu item.
| Property | Description | Data Type |
|---|---|---|
| None | Indicates that no text information is returned. | string |
| TextOnly | Indicates that only plain text is extracted and returned. | string |
| BoundsOnly | Indicates that text is returned along with layout information, such as bounds or coordinates. | string |
| TextAndBounds | Indicates that both plain text and text with bounds (layout information) are returned. | string |
Basic Usage Example
Load PDF Document
<script>
var pdfViewer = document.getElementById('pdfViewer').ej2_instances[0];
pdfViewer.load('loaded document.pdf');
</script>Download PDF
<script>
var pdfViewer = document.getElementById('pdfViewer').ej2_instances[0];
pdfViewer.download();
</script>Export Annotations
<script>
var pdfViewer = document.getElementById('pdfViewer').ej2_instances[0];
var annotations = pdfViewer.exportAnnotation();
console.log(annotations);
</script>Note: The complete setup and component structure is available in the getting-started.md file.
Bookmark Navigation
Brief: Bookmark navigation enables users to navigate through embedded PDF bookmarks. The ASP.NET MVC PDF Viewer automatically loads and presents bookmarks for easy document traversal. Use the goToBookmark method to navigate to specific bookmarks and getBookmarks to retrieve all available bookmarks in a PDF document.
Enabling Bookmark Navigation
Enable bookmark functionality in the PDF Viewer component to display and interact with bookmarks embedded in the PDF document.
Property
EnableBookmark="true"
Description
Enables the bookmark panel in the PDF Viewer, allowing users to view and navigate through document bookmarks.
Usage
@Html.EJS().PdfViewer("pdfviewer").EnableBookmark(true).Render()Note: The complete setup and component structure is available in the getting-started.md file.
---
Navigate to Bookmark
Use the goToBookmark method to programmatically navigate to a specific bookmark location within the PDF document.
Method
goToBookmark(x, y)
Description
Navigates to a specific bookmark location in the PDF document. The method throws an error if the specified bookmark does not exist in the document.
Parameters
- x: (number) The zero-based page index to navigate to
- y: (number) The vertical Y coordinate on the target page to position the viewport
Usage
var onGoToBookmark = function() {
// Navigate to page index 0 with Y coordinate 100
var pdfViewer = document.getElementById('pdfViewer').ej2_instances[0];
if (pdfViewer) {
pdfViewer.bookmark.goToBookmark(0, 100);
}
};
// Button integration
<button onclick="onGoToBookmark()">Go to Specific Bookmark</button>Note: The complete setup and component structure is available in the getting-started.md file.
Behavior
- The method requires a valid page index (x parameter)
- The Y coordinate (y parameter) determines the vertical position on the target page
- An error is thrown if the page index is invalid or bookmark doesn't exist
- The view updates immediately upon successful navigation
---
Retrieve All Bookmarks
Use the getBookmarks method to retrieve a complete list of all bookmarks available in the PDF document.
Method
getBookmarks()
Description
Retrieves a list of all bookmarks in the PDF document. Returns a collection of Bookmark objects containing information about each bookmark, including title, page references, and hierarchy.
Return Value
- Type: Array of Bookmark objects
- Contains: Bookmark information including titles, page indices, and nested hierarchy
Usage
var onGetBookmarks = function() {
var pdfViewer = document.getElementById('pdfViewer').ej2_instances[0];
var bookmarks = pdfViewer && pdfViewer.bookmark.getBookmarks();
console.log(bookmarks);
// Process bookmarks
if (bookmarks && bookmarks.length > 0) {
bookmarks.forEach(function(bookmark, index) {
console.log('Bookmark ' + index + ': ' + bookmark.title);
});
}
};
// Button integration
<button onclick="onGetBookmarks()">Retrieve Bookmarks</button>Note: The complete setup and component structure is available in the getting-started.md file.
Behavior
- Returns an empty array if the document contains no bookmarks
- Bookmarks maintain their hierarchical structure in the returned list
- The method is non-destructive and does not modify the PDF document
- Can be called at any time during PDF document viewing
---
Bookmark Structure
Bookmark objects returned by getBookmarks() contain the following information:
Bookmark Object Properties
- title: The display name of the bookmark
- page: The zero-based page index the bookmark references
- y: The Y coordinate position on the page
- children: Array of child bookmarks (for nested bookmarks)
- destination: The navigation destination details
Example Bookmark Data Structure
[
{
title: "Chapter 1",
page: 0,
y: 150,
children: [
{
title: "Section 1.1",
page: 2,
y: 200,
children: []
},
{
title: "Section 1.2",
page: 5,
y: 100,
children: []
}
]
},
{
title: "Chapter 2",
page: 10,
y: 50,
children: []
}
]---
Open/close bookmark pane programmatically
Approach 1: Use IsBookmarkPanelOpen property on PDF Viewer instance. Setting it to true opens the bookmark panel. Using it during initialization opens the bookmark panel on load
@Html.EJS().PdfViewer("pdfviewer").IsBookmarkPanelOpen(true);
<script>
var pdfviewer = document.getElementById('pdfViewer').ej2_instances[0];
function toggleBookmark(isOpen) {
if (isOpen) {
pdfviewer.isBookmarkPanelOpen = true;
}
else {
pdfviewer.isBookmarkPanelOpen = false;
}
}
</script>
Approach 2: Use openBookmarkPane() of bookmark module to open bookmark panel and use closeBookmarkPane() of bookmark module to close bookmark panel.
@Html.EJS().PdfViewer("pdfviewer").IsBookmarkPanelOpen(true);
<script>
var pdfviewer = document.getElementById('pdfViewer').ej2_instances[0];
function toggleBookmark(isOpen) {
if (isOpen) {
pdfviewer.bookmark.openBookmarkPane();
}
else {
pdfviewer.bookmark.closeBookmarkPane();
}
}
</script>
Best Practices
1. Always check for valid references before calling bookmark methods:
var pdfViewer = document.getElementById('pdfViewer').ej2_instances[0];
pdfViewer && pdfViewer.bookmark.goToBookmark(pageIndex, yCoordinate);2. Handle errors gracefully when navigating to bookmarks:
try {
var pdfViewer = document.getElementById('pdfViewer').ej2_instances[0];
pdfViewer.bookmark.goToBookmark(pageIndex, yCoordinate);
} catch (error) {
console.error('Bookmark navigation failed:', error);
}3. Cache bookmark data if accessing frequently:
var cachedBookmarks = null;
function getAllBookmarks() {
if (!cachedBookmarks) {
var pdfViewer = document.getElementById('pdfViewer').ej2_instances[0];
cachedBookmarks = pdfViewer && pdfViewer.bookmark.getBookmarks();
}
return cachedBookmarks;
}---
Integration Example
Complete example showing bookmark navigation with a bookmark list:
<div style="display: flex; height: 100vh;">
<div style="width: 200px; overflowY: 'auto'; borderRight: '1px solid #ccc';">
<h3>Bookmarks</h3>
<ul id="bookmarkList"></ul>
</div>
<div style="flex: 1;">
@Html.EJS().PdfViewer("pdfviewer").EnableBookmark(true).IsBookmarkPanelOpen(true);
</div>
</div>
<script>
function populateBookmarks() {
var pdfViewer = document.getElementById('pdfViewer').ej2_instances[0];
var allBookmarks = pdfViewer && pdfViewer.bookmark.getBookmarks();
var bookmarkList = document.getElementById('bookmarkList');
bookmarkList.innerHTML = '';
if (allBookmarks && allBookmarks.length > 0) {
allBookmarks.forEach(function(bookmark, index) {
var li = document.createElement('li');
li.textContent = bookmark.title;
li.onclick = function() {
handleBookmarkClick(bookmark);
};
bookmarkList.appendChild(li);
});
}
}
function handleBookmarkClick(bookmark) {
var pdfViewer = document.getElementById('pdfViewer').ej2_instances[0];
if (pdfViewer) {
pdfViewer.bookmark.goToBookmark(bookmark.page, bookmark.y);
}
}
// Populate bookmarks when document loads
function onDocumentLoad () {
populateBookmarks();
}
</script>Note: The complete setup and component structure is available in the getting-started.md file.
---
Context Menu
Brief: The ASP.NET MVC PDF Viewer provides a context-aware context menu that dynamically updates based on the right-clicked element. It supports built-in menu items for text, annotations, and form fields, with extensive customization options to add custom items, handle click events, and dynamically show or hide items.
Understanding the Context Menu
The context menu is designed to be context-aware, meaning it dynamically updates its items based on the target element. Right-clicking on different document areas reveals different options suited to the specific element.
MVC Capabilities
The context menu supports:
- Default Behavior: Provides standard actions such as cut, copy, and annotation management.
- Customization: Allows adding new menu items, removing default ones, or reordering them.
- Granular Control: Developers can fully disable the menu or replace it with custom logic.
- Client-side Interaction: Availability and behavior are governed by client-side logic, independent of server-side configurations.
---
Context Menu Component Properties
These properties are available directly on the PdfViewerComponent to control context menu-related functionality:
| Property Name | Description | Type | Default Value |
|---|---|---|---|
| contextMenuSettings | Configure context menu appearance and behavior. | ContextMenuSettings | null |
| disableContextMenuItems | Disable specific context menu items by specifying their IDs. | [ContextMenuItem[]](#contextmenuitem) | null |
---
Built-in Context Menu Items
The context menu displays different default items based on the element being right-clicked.
Text Menu Items
When right-clicking on selected text, the following items appear:
| Item | Description |
|---|---|
| Copy | Copies selected text to the clipboard. |
| Highlight | Highlights selected text using the default highlight color. |
| Underline | Applies an underline to the selected text. |
| Strikethrough | Applies a strikethrough to the selected text. |
| Squiggly | Applies a squiggly underline to the selected text. |
| Redact Text | Redacts the selected text. |
Annotation Menu Items
When interacting with annotations, these items are available:
| Item | Description |
|---|---|
| Copy | Copies the selected annotation for pasting within the same page. |
| Cut | Removes the selected annotation and copies it to the clipboard. |
| Paste | Pastes a previously copied or cut annotation. |
| Delete | Permanently removes the selected annotation. |
| Comments | Opens the comment panel to manage discussions on the annotation. |
Form Field Menu Items
When the viewer is in designer mode and a form field is selected:
| Item | Description |
|---|---|
| Copy | Copies the selected form field for duplication. |
| Cut | Removes the selected form field for relocation. |
| Paste | Pastes a copied or cut form field. |
| Delete | Removes the selected form field from the document. |
| Properties | Launches the properties dialog for the specific form field. |
Empty Space Menu Items
When right-clicking on empty space in the document:
| Item | Description |
|---|---|
| Paste | Pastes a previously copied annotation or form field. |
---
Add Custom Context Menu Items
Method
addCustomMenu(menuItems, hideDefaultMenu?, addAtBottom?)
Adds custom options to the context menu using the addCustomMenu() method, typically called during the documentLoad event.
Parameters
- menuItems: Array of custom menu item objects
- hideDefaultMenu (optional): Boolean to hide default menu items (default: false)
- addAtBottom (optional): Boolean to add custom items at the bottom of the menu (default: false)
Menu Item Object Structure
Each menu item should have the following properties:
{
text: string; // Display text for the menu item
id: string; // Unique identifier for the menu item
iconCss?: string; // CSS class for the icon (e.g., 'e-icons e-search')
}Usage
<script>
var menuItems = [
{
text: 'Search In Google',
id: 'search_in_google',
iconCss: 'e-icons e-search'
},
{
text: 'Lock Annotation',
iconCss: 'e-icons e-lock',
id: 'lock_annotation'
},
{
text: 'Unlock Annotation',
iconCss: 'e-icons e-unlock',
id: 'unlock_annotation'
}
];
function documentLoad(args) {
var pdfViewer = document.getElementById('pdfViewer').ej2_instances[0];
if (pdfViewer) {
pdfViewer.addCustomMenu(menuItems, false);
}
}
</script>Note: The complete setup and component structure is available in the getting-started.md file.
---
Handle Click Events for Custom Menu Items
Event Method
customContextMenuSelect(args)
Defines actions for custom menu items when they are clicked.
Parameters
- args.id: The unique identifier of the clicked menu item
- args.cancel: Set to false to allow the default action
Usage
<script>
var pdfViewer = document.getElementById('pdfViewer').ej2_instances[0];
function customContextMenuSelect(args) {
switch (args.id) {
case 'search_in_google':
if (pdfViewer.textSelectionModule && pdfViewer.textSelectionModule.isTextSelection) {
for (var i = 0; i < pdfViewer.textSelectionModule.selectionRangeArray.length; i++) {
var content = pdfViewer.textSelectionModule.selectionRangeArray[i].textContent;
if (/\S/.test(content)) {
window.open('http://google.com/search?q=' + content);
}
}
}
break;
case 'lock_annotation':
lockAnnotations(args);
break;
case 'unlock_annotation':
unlockAnnotations(args);
break;
default:
break;
}
}
function lockAnnotations(args) {
for (var i = 0; i < pdfViewer.annotationCollection.length; i++) {
if (pdfViewer.annotationCollection[i].uniqueKey === pdfViewer.selectedItems.annotations[0].id) {
pdfViewer.annotationCollection[i].annotationSettings.isLock = true;
pdfViewer.annotationCollection[i].isCommentLock = true;
pdfViewer.annotation.editAnnotation(pdfViewer.annotationCollection[i]);
args.cancel = false;
}
}
}
function unlockAnnotations(args) {
for (var i = 0; i < pdfViewer.annotationCollection.length; i++) {
if (pdfViewer.annotationCollection[i].uniqueKey === pdfViewer.selectedItems.annotations[0].id) {
pdfViewer.annotationCollection[i].annotationSettings.isLock = false;
pdfViewer.annotationCollection[i].isCommentLock = false;
pdfViewer.annotation.editAnnotation(pdfViewer.annotationCollection[i]);
args.cancel = false;
}
}
}
</script>---
Dynamic Context Menu Customization
Event Method
customContextMenuBeforeOpen(args)
Allows for dynamic showing or hiding of menu items based on selection or document state before the context menu is displayed.
Parameters
- args.ids: Array of menu item IDs that are about to be displayed
- args: Event arguments containing menu state information
Usage
<script>
function customContextMenuBeforeOpen(args) {
var pdfViewer = document.getElementById('pdfViewer').ej2_instances[0];
for (var i = 0; i < args.ids.length; i++) {
var menuElement = document.getElementById(args.ids[i]);
if (menuElement) {
menuElement.style.display = 'none';
if (args.ids[i] === 'search_in_google' && pdfViewer.textSelectionModule
&& pdfViewer.textSelectionModule.isTextSelection) {
menuElement.style.display = 'block';
}
else if (args.ids[i] === "lock_annotation" || args.ids[i] === "unlock_annotation") {
var isLockOption = args.ids[i] === "lock_annotation";
for (var j = 0; j < pdfViewer.selectedItems.annotations.length; j++) {
var selectedAnnotation = pdfViewer.selectedItems.annotations[j];
if (selectedAnnotation && selectedAnnotation.annotationSettings) {
var shouldDisplay = (isLockOption && !selectedAnnotation.annotationSettings.isLock) ||
(!isLockOption && selectedAnnotation.annotationSettings.isLock);
menuElement.style.display = shouldDisplay ? 'block' : 'none';
}
}
}
}
}
}
</script>---
Disable the Context Menu
Property
contextMenuOption
Disables the context menu entirely by setting this property to None.
Usage
@Html.EJS().PdfViewer("pdfviewer").ContextMenuOption("None");Note: The complete setup and component structure is available in the getting-started.md file.
---
Properties and Enums
ContextMenuSettings
| Name | Description | Data Type |
|---|---|---|
| contextMenuAction | Defines the context menu action. | `ContextMenuAction` |
| contextMenuItems | Defines the context menu items should be visible in the PDF Viewer. | `ContextMenuItem` |
ContextMenuAction
- None
- MouseUp
- RightClick
ContextMenuItem
- Comment
- Copy
- Cut
- Delete
- Highlight
- Paste
- Properties
- ScaleRatio
- Squiggly
- Strikethrough
- TextRedact
- Underline
Important Notes
- Icon Classes: Use Syncfusion EJ2 icon classes (e.g.,
e-icons e-search,e-icons e-lock,e-icons e-unlock) for custom menu items. - Event Order: The
documentLoadevent is the recommended place to calladdCustomMenu()to ensure the viewer is fully initialized.
Enable Properties in ASP.NET MVC Syncfusion PDFViewer Component
The ASP.NET MVC PDFViewer component provides a comprehensive set of enable properties to control and customize various features and functionalities of the PDF viewer. These boolean properties allow you to enable or disable specific capabilities such as annotations, form design, navigation, printing, and more.
How to Use the Enable Properties in PDF Viewer
EnableToolbar(true)
EnableNavigation(true)
EnableAnnotation(true)
EnableFormDesigner(true)
EnablePrint(true)
EnableTextSearch(true)
EnableThumbnail(true)
EnableDownload(true)Note: The complete setup and component structure is available in the getting-started.md file.
List of Enable Properties
| Property Name | Description | Data Type |
|---|---|---|
| enableAccessibilityTags | Enables or disables accessibility tags in the PDF document for improved accessibility support. | boolean |
| enableAnnotation | Enables or disables the annotation feature, allowing users to add comments, highlights, and markup annotations to PDF documents. | boolean |
| enableAnnotationToolbar | Enables or disables the annotation toolbar, which provides quick access to annotation tools like highlight, underline, and strikethrough. | boolean |
| enableAutoComplete | Enables or disables the auto-complete functionality for form fields in the PDF viewer. | boolean |
| enableBookmark | Enables or disables the bookmark feature, allowing users to navigate using document bookmarks. | boolean |
| enableBookmarkStyles | Enables or disables bookmark styling options in the PDF viewer. | boolean |
| enableCommentPanel | Enables or disables the comment panel, which displays comments and annotations added to the PDF document. | boolean |
| enableDesktopMode | Enables or disables desktop mode for optimized viewing experience on desktop devices. | boolean |
| enableDownload | Enables or disables the download functionality, allowing users to download the PDF document. | boolean |
| enableFormDesigner | Enables or disables the form designer feature, which allows users to create and edit form fields in PDF documents. | boolean |
| enableFormDesignerToolbar | Enables or disables the form designer toolbar with form field creation and editing tools. | boolean |
| enableFormFields | Enables or disables the form fields feature, allowing users to interact with fillable form fields in PDFs. | boolean |
| enableFormFieldsValidation | Enables or disables validation for form fields in the PDF viewer. | boolean |
| enableFreeText | Enables or disables the free text annotation feature for adding text comments directly on the PDF. | boolean |
| enableHandwrittenSignature | Enables or disables the handwritten signature feature for signing PDF documents. | boolean |
| enableHyperlink | Enables or disables hyperlink functionality in PDF documents. | boolean |
| enableImportAnnotationMeasurement | Enables or disables the import functionality for annotation measurements. | boolean |
| enableInkAnnotation | Enables or disables ink annotation feature for freehand drawing and annotations on the PDF. | boolean |
| enableLocalStorage | Enables or disables local storage to persist PDF viewer state and data locally. | boolean |
| enableMagnification | Enables or disables the magnification feature, allowing users to zoom in and out of the PDF document. | boolean |
| enableMeasureAnnotation | Enables or disables the measure annotation feature for measuring distances and areas in PDFs. | boolean |
| enableMultiLineOverlap | Enables or disables multi-line overlap handling in text markup annotations. | boolean |
| enableMultiPageAnnotation | Enables or disables annotations across multiple pages in the PDF document. | boolean |
| enableNavigation | Enables or disables the navigation feature, allowing users to move between pages in the PDF document. | boolean |
| enableNavigationToolbar | Enables or disables the navigation toolbar with page navigation and control buttons. | boolean |
| enablePageOrganizer | Enables or disables the page organizer feature for reordering, inserting, and deleting pages. | boolean |
| enablePersistence | Enables or disables persistence to save and restore the PDF viewer state across sessions. | boolean |
| enablePinchZoom | Enables or disables pinch zoom functionality for touch devices and mobile views. | boolean |
| enablePrint | Enables or disables the print functionality, allowing users to print the PDF document. | boolean |
| enablePrintRotation | Enables or disables page rotation during print operations. | boolean |
| enableRedactionToolbar | Enables or disables the redaction toolbar for redacting sensitive information from PDFs. | boolean |
| enableRtl | Enables or disables right-to-left (RTL) language support for proper rendering of RTL text. | boolean |
| enableShapeAnnotation | Enables or disables shape annotation features for drawing rectangles, circles, lines, and polygons. | boolean |
| enableShapeLabel | Enables or disables labels on shape annotations in the PDF viewer. | boolean |
| enableStampAnnotations | Enables or disables stamp annotations for adding pre-defined stamps like "Approved" or "Rejected". | boolean |
| enableStickyNotesAnnotation | Enables or disables sticky notes (comment) annotations for adding notes to the PDF. | boolean |
| enableTextMarkupAnnotation | Enables or disables text markup annotations including highlight, underline, and strikethrough. | boolean |
| enableTextMarkupResizer | Enables or disables the resizer for text markup annotations to adjust their size and position. | boolean |
| enableTextSearch | Enables or disables the text search feature, allowing users to search for text within the PDF document. | boolean |
| enableTextSelection | Enables or disables text selection in the PDF document for copying and highlighting. | boolean |
| enableThumbnail | Enables or disables the thumbnail panel for quick navigation and page preview. | boolean |
| enableToolbar | Enables or disables the main toolbar containing various action buttons and controls. | boolean |
| enableZoomOptimization | Enables or disables zoom optimization for better rendering performance at different zoom levels. | boolean |
Usage Example with Multiple Enable Properties
// Set multiple enable properties on <ejs-pdfviewer>:
@Html.EJS().PdfViewer("pdfviewer").EnableToolbar(true).EnableNavigation(true).EnableAnnotation(true).EnableAnnotationToolbar(true).EnableBookmark(true).EnableCommentPanel(true).EnableFormDesigner(true).EnableFormDesignerToolbar(true).EnableFormFields(true).EnableFormFieldsValidation(true).EnableDownload(true).EnablePrint(true).EnableTextSearch(true).EnableTextSelection(true).EnableThumbnail(true).EnableMagnification(true).EnablePinchZoom(true).EnablePageOrganizer(true).EnableRedactionToolbar(true).EnableHandwrittenSignature(true).EnableZoomOptimization(true).Render()
Important: If a property is assigned a value that is the same as its default value, do not include that property in the output.
Notes
- All enable properties accept boolean values (
trueorfalse) - These properties can be set during component initialization or modified dynamically
- Disabling certain features can improve performance for specific use cases
- Some features may depend on others (e.g., enabling
enableAnnotationToolbarrequiresenableAnnotationto be enabled)
Form Field Validation
Built-in validation ensures required form fields are completed before critical actions (print, download).
Enable Form Field Validation
@Html.EJS().PdfViewer("pdfviewer").EnableFormFieldsValidation(true).Render()
<script>
pdfviewer.validateFormFields = function(args) {
// Triggered when user attempts print/download with validation enabled
if (args && args.formField && args.formField.length > 0) {
// Handle validation failure
alert('Please fill all required fields. Missing: ' + args.formField[0].name);
args.isFormSubmitCancelled = true; // Cancel print/download
}
};
</script>Mark Fields as Required
// Method 1: When creating field
pdfviewer.formDesignerModule.addFormField('Textbox', {
name: 'Email',
isRequired: true // This field must be filled
});
// Method 2: Set default for field type
pdfviewer.textFieldSettings = { isRequired: true };
// Method 3: Update existing field
var field = pdfviewer.formFieldCollections.find(f => f.name === 'Email');
if (field) {
pdfviewer.formDesignerModule.updateFormField(field, { isRequired: true });
}Validation Flow
User clicks Print/Download
↓
System checks enableFormFieldsValidation
↓ (if enabled)
Validation event triggered with empty required fields list
↓
Custom code can:
- Cancel action (args.isFormSubmitCancelled = true)
- Show error message
- Focus invalid field
- Apply custom validation logic
↓
If not cancelled → Action proceedsCustom Validation Examples
// Example 1: Email format validation
pdfviewer.validateFormFields = function(args) {
var fields = pdfviewer.retrieveFormFields();
var emailField = fields.find(f => f.name === 'Email');
if (emailField && emailField.value) {
var isValidEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(emailField.value);
if (!isValidEmail) {
alert('Invalid email format');
args.isFormSubmitCancelled = true;
}
}
};
// Example 2: At least one checkbox selected
pdfviewer.validateFormFields = function(args) {
var fields = pdfviewer.retrieveFormFields();
var checkboxes = fields.filter(f => f.fieldType === 'CheckBox');
var anyChecked = checkboxes.some(f => f.isChecked);
if (!anyChecked) {
alert('Please select at least one option');
args.isFormSubmitCancelled = true;
}
};Form Fields Properties and flags
Form Field Properties
Common Properties (All Field Types)
| Property | Type | Description |
|---|---|---|
name | string | Unique identifier for field |
value | varies | Current/default value |
tooltip | string | Help text displayed on hover |
isReadOnly | boolean | Prevent user modification via UI |
isRequired | boolean | Mark field as mandatory (triggers validation) |
isPrint | boolean | Include in printed output |
pageNumber | number | 1-based page index |
bounds | object | Position/size {X, Y, Width, Height} |
fontName | string | Font for text display |
fontSize | number | Font size in points |
borderColor | string | Border color (hex, rgb, name) |
borderWidth | number | Border thickness |
backgroundColor | string | Field background color |
textAlign | string | Text alignment (left, center, right) |
visibility | string | Field visibility (visible, hidden, noView) |
Type-Specific Properties
Textbox/Password:
maxLength: Maximum characters allowed
CheckBox/RadioButton:
isChecked: Current checked state
Dropdown/ListBox:
options: Array of {itemName, itemValue} objects
Signature/Initial:
- Supports draw, type, upload signature methods
---
Form Field Flags and Constraints
Form field flags control how users interact with fields and how they behave during validation and printing.
isReadOnly Flag
Prevents UI modification while allowing API updates. Useful for displaying computed or system-generated values.
pdfviewer.formDesignerModule.addFormField('Textbox', {
name: 'EmployeeId',
bounds: { X: 146, Y: 229, Width: 150, Height: 24 },
isReadOnly: true,
value: 'EMP-0001' // User cannot change this
});Read-only Field Behavior:
- User cannot edit through UI
- Field is grayed out or visually disabled
- API can still update value programmatically
- Ideal for display-only fields with backend values
---
isRequired Flag
Marks field as mandatory. When validation is enabled, required empty fields block print/download.
pdfviewer.formDesignerModule.addFormField('Textbox', {
name: 'Email',
bounds: { X: 146, Y: 260, Width: 220, Height: 24 },
isRequired: true,
tooltip: 'Email is required'
});Validation Behavior:
- Only applies if
enableFormFieldsValidation = true - Triggers validation on print/download
- Empty required fields are listed in validation event
- Can prevent action or show error message
---
isPrint Flag
Controls whether field appears in printed PDF output.
// Signature not included in print
pdfviewer.formDesignerModule.addFormField('SignatureField', {
name: 'ApplicantSign',
bounds: { X: 57, Y: 923, Width: 200, Height: 43 },
isPrint: false // Will not appear when printed
});
// Checkbox appears in print
pdfviewer.formDesignerModule.addFormField('CheckBox', {
name: 'ConsentCheckbox',
bounds: { X: 100, Y: 300, Width: 18, Height: 18 },
isPrint: true // Will appear when printed
});---
Set Default Constraints for Field Type
Configure default constraints so new fields inherit them from toolbar.
// All textboxes will be required and editable
pdfviewer.textFieldSettings = {
isReadOnly: false,
isRequired: true,
isPrint: true,
tooltip: 'Required field'
};
// All signature fields will be optional and not printed
pdfviewer.signatureFieldSettings = {
isReadOnly: false,
isRequired: false,
isPrint: false,
tooltip: 'Sign if applicable'
};
// All checkbox fields will be printed
pdfviewer.checkBoxFieldSettings = {
isPrint: true
};---
Common Form Operations
Retrieve All Form Fields
Get all form fields from current document.
var allFields = pdfviewer.retrieveFormFields();
console.log('Total fields:', allFields.length);
allFields.forEach(field => {
console.log(`Field: ${field.name}, Type: ${field.fieldType}, Value: ${field.value}`);
});---
Update Single Field Value
Modify field value programmatically after document is loaded.
pdfviewer.updateFormFieldsValue({
name: 'FirstName',
value: 'Jane',
pageNumber: 1
});---
Update Field Properties
Change field properties like read-only, required, visibility.
var field = pdfviewer.formFieldCollections.find(f => f.name === 'Email');
if (field) {
pdfviewer.formDesignerModule.updateFormField(field, {
isRequired: true,
isReadOnly: false,
tooltip: 'Email is now required'
});
}---
Move and Resize Fields
Adjust field position and size programmatically.
var field = pdfviewer.formFieldCollections.find(f => f.name === 'FirstName');
if (field) {
pdfviewer.formDesignerModule.updateFormField(field, {
bounds: { X: 200, Y: 300, Width: 250, Height: 30 }
});
}---
Delete Form Field
Remove field from document completely.
// Delete via Form Designer
var field = pdfviewer.formFieldCollections.find(f => f.name === 'OldField');
if (field) {
pdfviewer.formDesignerModule.removeFormField(field);
}---
Group Related Fields
Group multiple fields logically for tab order and organization.
var fields = [
pdfviewer.formFieldCollections.find(f => f.name === 'FirstName'),
pdfviewer.formFieldCollections.find(f => f.name === 'LastName'),
pdfviewer.formFieldCollections.find(f => f.name === 'Email')
];
if (fields.every(f => f)) {
pdfviewer.formDesignerModule.groupFormFields(fields);
}---
Add Custom Data to Form Field
Attach custom metadata to form field for application use.
pdfviewer.formDesignerModule.addFormField('Textbox', {
name: 'Department',
bounds: { X: 100, Y: 150, Width: 200, Height: 24 },
value: 'Engineering',
customData: {
department_id: 'DEPT-123',
region: 'North America',
manager: 'john@company.com'
}
});
// Retrieve custom data
var field = pdfviewer.formFieldCollections.find(f => f.name === 'Department');
console.log(field.customData); // { department_id: 'DEPT-123', ... }