@mescius/dspdfviewer
Version:
Document Solutions PDF Viewer
1,181 lines (1,180 loc) • 157 kB
TypeScript
/// <reference path="vendor/i18next.d.ts" />
//@ts-ignore
import { i18n } from 'i18next';
//@ts-ignore
import { ViewerStatus, ViewMode, Toolbar, ToolbarLayout, ZoomMode } from '@grapecity/viewer-core';
import PdfReportPlugin from './plugin';
import { GenericButton } from './Toolbar/ToolbarItems';
import { SignToolSettings, ViewerOptions } from './ViewerOptions';
//@ts-ignore
import React from 'react';
//@ts-ignore
import * as ReactDOM from 'react-dom';
//@ts-ignore
import { ReportViewer, LoadResult, EventFan } from '@grapecity/viewer-core';
import { SvgIconKey } from './Styles/pdfSvgIcons';
import { ISupportApi } from './SupportApi/ISupportApi';
import { PdfToolbarLayout } from './Toolbar/PdfToolbarLayout';
import { AnnotationBase, AnnotationTypeCode, CopyBufferData, FileAttachmentAnnotation, WidgetAnnotation, SignatureInformation } from './Annotations/AnnotationTypes';
import { EditMode, LayoutMode } from './Annotations/types';
import { GcSelectionPoint, IGcRect } from './Models/GcMeasurementTypes';
import { GcRightSidebarState } from './RightSidebar/types';
import { GcRightSidebar } from './RightSidebar/GcRightSidebar';
import { LogLevel, ModificationsState, SharedDocumentInfo, UndoChangeName } from './SharedDocuments/types';
import { SharedRef } from './Utils/SharedRef';
/// <reference path="vendor/moment.d.ts" />
//@ts-ignore
import moment = require('moment');
import { GcPdfSearcher } from './Search/GcPdfSearcher';
//@ts-ignore
import { PanelHandle } from '@grapecity/viewer-core/types/api/PluginModel';
import { DataStorage } from './DataStorage/DataStorage';
import { GcMeasurement } from './Utils/GcMeasurement';
import { SignToolStorage } from './SignTool/SignToolStorage';
import { LeftSidebar } from './LeftSidebar';
import { DocumentSecuritySummary } from './Security/DocumentSecuritySummary';
import { DocumentInformation } from './Properties/DocumentInformation';
import { OpenParameters, OptionalContentConfig, PageViewport, SaveSettings, StructTreeNode, ViewerFeatureName, ViewerPreferences, IGCEventBus, DocumentListItem, SubmitFormOptions, ScrollPageIntoViewOptions, IGcPageView, FontFormat, ReplaceTextModel, IAutoScrollHelper } from './Models/ViewerTypes';
import { AddStampDropdown } from './Toolbar/controls/AddStampDropdown';
import { SecondToolbar } from './Toolbar/SecondToolbar/SecondToolbar';
import { SecondToolbarLayout, SecondToolbarLayoutMode } from './Toolbar/SecondToolbar/types';
import { SearchPanel } from './Search/SearchPanel';
import { AsyncLock, PromiseQueue } from './Utils/PromiseUtils';
import { utf8ToBase64 } from './Utils/EncodingUtils';
import { ErrorEventArgs, BeforeOpenEventArgs, AfterOpenEventArgs, ThemeChangedEventArgs, EventName, EventArgs, BeforeAddAnnotationEventArgs, AfterAddAnnotationEventArgs, AfterUpdateAnnotationEventArgs, BeforeRemoveAnnotationEventArgs, AfterRemoveAnnotationEventArgs, BeforeUpdateAnnotationEventArgs } from './Models/EventArgs';
import { XfaApiImpl } from './XFA/XfaApiImpl';
import { PdfOrganizerDialog } from './PdfOrganizer/PdfOrganizerDialog';
import { ConfirmButton } from './Dialogs/Types';
import { OpenDocumentInfo } from './SupportApi/types';
import { PaintedBoxInfo, Rect, TextPartsQuadPoints } from './Search/types';
import { PageDisplayDropdown } from './Toolbar/controls/PageDisplayDropdown';
import { PageDisplayType } from './Toolbar/controls/types';
import { SaveAsDropdown } from './Toolbar/controls/SaveAsDropdown';
import { HighlightArgs, HighlightBehaviorArgs, ITextHighlightManager } from './HighlightManager/types';
import { IUndoStorage } from './Undo/IUndoStorage';
import { XFDFAnnotationHandler } from './XFDF/XFDFAnnotationHandler';
import { IPageRegionSelector, PageRegionSelectedCallback } from './Utils/PageRegionSelector';
import { TableDataExtractor } from './TableDataExtraction/TableDataExtractor';
/**
* Document Solutions PDF Viewer (DsPdfViewer) is a fast JavaScript based client-side PDF Viewer that runs in all major browsers.
* <p>Note that DsPdfViewer is the new name for GcPdfViewer, with the same API.</p>
* <p>During this transition period we are publishing both versions, but it is recommended that you switch to using DsPdfViewer when possible.</p>
**/
export declare class GcPdfViewer extends ReportViewer {
private static _i18n;
static _instanceCounter: number;
private _disposed;
private _plugin;
private _isUpdating;
private _toolbarLayout;
private _secondToolbarLayout;
private _viewerInstanceId;
/**
* @ignore exclude from doc
**/
readonly in17n: i18n;
private _fileStorage;
addStampDropdown: AddStampDropdown | null;
private _secondToolbar;
private _editorLastValues;
private _xfa;
pageDisplayDropdown: PageDisplayDropdown | null;
saveAsDropdown: SaveAsDropdown | null;
private _pageDisplay?;
private _highlightManager;
private _AnnotationXFDFHandler;
private _pageRegionSelector;
private _tableDataExtractor;
/**
* Document Solutions PDF Viewer constructor.
* @param element root container element or selector pattern used to select the root container element.
* @param options Viewer options. See {@link ViewerOptions} for further information.
*/
constructor(element: HTMLElement | string, options?: Partial<ViewerOptions>);
/**
* Gets the auto-scroll helper instance.
* @ignore exclude from docs.
*
* @returns {IAutoScrollHelper | undefined} The auto-scroll helper if available, otherwise `undefined`.
*/
get autoScrollHelper(): IAutoScrollHelper | undefined;
/**
* In some specific cases, users may need to override or add new JavaScript formatting functions.
* Use the jsFormatFunctions property to achieve this.
* @example
* ```javascript
* // Below is an example of how to add a new custom formatting function that appends a postfix to a field value
* viewer.jsFormatFunctions.customUserFormat = function(strValue, postfix){
* return strValue + postfix;
* }
* ```
*/
get jsFormatFunctions(): any;
/**
* pdf.js library instance.
* @ignore exclude from docs.
**/
get pdfjsLib(): any;
/**
* pdf.js document proxy.
* @ignore exclude from docs.
**/
get pdfDocument(): any;
/**
* Provides an instance of `TableDataExtractor` for extracting table data from the document.
* If the instance does not exist, it is created and cached.
*
* @returns {TableDataExtractor} The `TableDataExtractor` instance associated with this document.
*/
get tableDataExtractor(): TableDataExtractor;
/**
* Gets initial viewer preferences.
**/
get viewerPreferences(): Promise<ViewerPreferences>;
/**
* Resolve page index using PDF page reference.
* @example
* ```javascript
* const openAction = (await viewer.viewerPreferences).openAction;
* if(openAction && openAction.dest) {
* const pageRef = openAction.dest[0];
* const targetPageIndex = await viewer.resolvePageIndex(pageRef);
* }
*```
**/
resolvePageIndex(pageRef: any | {
gen: number;
num: number;
}): Promise<number | null>;
get hasAttachments(): boolean;
get attachments(): FileAttachmentAnnotation[];
/**
* The ID of the viewer instance.
* Used to get access to the public UI API.
* @example
* ```javascript
* // Add new panel:
* const panelHandle = viewer.addArticlesPanel();
* // Get menu API:
* const menuApi = API.of(viewer.instanceId).menu;
* // Pin newly added panel:
* menuApi.panels.pin(panelHandle.id);
*```
* @ignore
**/
get instanceId(): string;
set instanceId(id: string);
/**
* Returns true if the active edit mode is sticked by the user.
* Indicates that the stickyBehavior for the active edit button is enabled and the button is checked.
* See the toolbarLayout.stickyBehavior property for details.
**/
get isEditModeSticked(): boolean;
/**
* Indicates whether the active PDF document is an XFA form.
* @ignore exclude from docs.
**/
get isPureXfa(): boolean;
/**
* Get information about signature used in document.
* @example
* ```javascript
* // Example: check if the current document is signed and show information about signature:
* var viewer = DsPdfViewer.findControl("#root");
* const signatureInfo = await viewer.getSignatureInfo();
* if(signatureInfo.signed) {
* const signatureValue = signatureInfo.signedByFields[0].signatureValue;
* const signerName = signatureValue.name;
* const location = signatureValue.location;
* const signDate = viewer.pdfStringToDate(signatureValue.modificationDate);
* alert("The document was signed using digital signature. Signed by: " + signerName + ", location: " + location + ", sign date: " + signDate.toString());
* } else {
* alert("The document is not signed.");
* }
* ```
**/
getSignatureInfo(): Promise<SignatureInformation>;
/**
* Convert a PDF date string to a JavaScript `Date` object.
* The PDF date string format is described in section 7.9.4 of the official
* PDF 32000-1:2008 specification. The function handles optional apostrophes
* and time zone offsets.
*
* @param {string} [input] - The PDF date string to convert.
* @return {Date|null} - The corresponding JavaScript `Date` object, or `null` if the input is invalid.
*
* @example
* ```javascript
* const pdfDateString = 'D:20230919123045Z'; // A PDF date string in UTC
* const date = viewer.pdfStringToDate(pdfDateString);
* console.log(date); // Outputs: Tue Sep 19 2023 12:30:45 GMT+0000 (Coordinated Universal Time)
* ```
*/
pdfStringToDate(input?: string | Date): Date | null;
/**
* Convert a JavaScript `Date` object, string, Moment object, or timestamp to a PDF date string.
* The PDF date string format is described in section 7.9.4 of the official
* PDF 32000-1:2008 specification. The output includes optional time zone information.
*
* @param {Date | string | moment.Moment | number} input - The date to convert, which can be a `Date` object, date string, Moment object, or timestamp.
* @return {string|null} - The formatted PDF date string, or `null` if the input is invalid.
*
* @example
* ```javascript
* // Convert a Date object to a PDF date string
* const date = new Date();
* const pdfDateString = viewer.dateToPdfString(date);
* console.log(pdfDateString); // Outputs: 'D:20240924045508Z'
*
* // Convert a timestamp to a PDF date string
* const timestamp = Date.now();
* const pdfDateStringFromTimestamp = viewer.dateToPdfString(timestamp);
* console.log(pdfDateStringFromTimestamp); // Outputs: 'D:20240924045508Z'
* ```
*/
dateToPdfString(input: Date | string | moment.Moment | number): string | null;
/**
* Page display mode.
*/
get pageDisplay(): PageDisplayType;
set pageDisplay(pageDisplay: PageDisplayType);
/**
* The property is used for development purposes.
* @ignore exclude from docs.
**/
get sharedRef(): SharedRef;
/**
* PDF document meta data loader. Used by some sidebar panels.
**/
get dataLoader(): import("./Core/GcPdfViewerDataLoader").GcPdfViewerDataLoader;
/**
* Internal event bus. Available event names are: outlineloaded, attachmentsloaded, namedaction, pagemode, fileattachmentannotation, pagerendered,
* pagecancelled, scalechange, pagesinit, pagesloaded, documentchanged, rotationchanging, updateviewarea, undostorechanged,
* show-custom-layout, hide-custom-layout, annotationeditstarted, unselectannotation, annotation-bounds-change, pagechange,
* mousemodechange, request-answer, textlayerready, textselectionchanged, viewersizechanged, articlebeadnavigate, error, open, pagelabels, documentload.
* @example
* ```javascript
* // Example: listen annotation selected/unselected event.
* var viewer = DsPdfViewer.findControl("#root");
* viewer.eventBus.on("annotationeditstarted", (args)=> {
* console.log("Annotation selected, annotation id: " + args.annotationId);
* });
* viewer.eventBus.on("unselectannotation", (args)=> {
* console.log("Annotation unselected, annotation id: " + args.annotationId);
* });
* ```
**/
get eventBus(): IGCEventBus;
/**
* Last editor property values.
* @ignore exclude from docs
**/
get editorLastValues(): any;
/**
* @ignore exclude from docs, used for tests.
**/
get formStateHelper(): any;
/**
* @ignore exclude from docs, used for tests.
**/
get annotationStateHelper(): any;
getEditorLastValue(annotation: AnnotationBase, propertyName: string): any;
saveToEditorLastValues(annotation: AnnotationBase): Promise<void>;
private _filterLastValues;
/**
* Gets the required SupportApi version that is compatible with the current version of the DsPdfViewer.
**/
get requiredSupportApiVersion(): string;
/**
* Gets the connected version of the SupportApi, if available.
**/
get supportApiVersion(): string;
/**
* Gets the GcPdf library version used by the SupportApi, if available.
**/
get gcPdfVersion(): string;
/**
* Internal service provider.
* @ignore exclude from docs
**/
get serviceProvider(): any;
/**
* Product license key.
* @example
* ```
*<script>
* // Add your license
* DsPdfViewer.LicenseKey = 'XXX';
* // Add your code
* const viewer = new DsPdfViewer("#viewer");
* viewer.addDefaultPanels();
*</script>
*```
**/
static LicenseKey: string;
/**
* Indicates whether the open document can be edited using SupportApi.
* Requires SupportApi.
* @example
* ```javascript
* if(viewer.canEditDocument) {
* alert("Document editing features enabled.");
* } else {
* alert("Document editing features disabled.");
* }
* ```
* */
get canEditDocument(): boolean;
/**
* Specifies the current user name.
* The property is used by Annotation Editor as default value for 'author' field.
* @example
* ```javascript
* viewer.currentUserName = "John";
* ```
* @example
* ```javascript
* alert("The current user name is " + viewer.currentUserName);
* ```
* */
get currentUserName(): string;
/**
* Specifies the current user name.
* The property is used by Annotation Editor as default value for 'author' field.
* Note, current user name is saved in the browser's local storage and it will be used
* on the next page reload if userName option is not set.
* @example
* ```javascript
* viewer.currentUserName = "John";
* ```
* @example
* ```javascript
* alert("The current user name is " + viewer.currentUserName);
* ```
**/
set currentUserName(userName: string);
/**
* @ignore exclude from docs.
**/
get disableFeaturesHash(): {
[key in ViewerFeatureName]?: boolean;
};
/**
* Indicates the selected editing tool for the Annotation editor or Form editor.
* Requires SupportApi.
* @example
* ```javascript
* // Set the layout mode to "Annotation editor"
* viewer.layoutMode = 1;
* // Set the edit mode to "Square".
* viewer.editMode = 4;
* ```
* */
get editMode(): EditMode;
/**
* Indicates the selected editing tool for the Annotation editor or Form editor.
* Requires SupportApi.
* @example
* ```javascript
* // Set the layout mode to "Annotation editor"
* viewer.layoutMode = 1;
* // Set the edit mode to "Square".
* viewer.editMode = 4;
* ```
* */
set editMode(mode: EditMode);
/**
* Activate edit mode.
* @ignore exclude from docs.
* @param mode
* @param args
*/
activateEditMode(mode: EditMode, args?: {
editMode: EditMode;
imageUrl: string;
imageDpi: number;
w: number;
h: number;
imageDataKey?: string;
} | null): void;
/**
*
* @ignore exclude from docs.
*/
activateReplaceTextFeature(): void;
/**
* Gets the file data. Available when keepFileData option is set to true.
* @example
* ```javascript
* var viewer = new DsPdfViewer('#root', { keepFileData: true });
* viewer.open('Test.pdf');
* viewer.onAfterOpen.register(function() {
* var pdfFileData = viewer.fileData;
* });
* ```
**/
get fileData(): Uint8Array | null;
/**
* Gets the file name that was used to open the document.
* The file name is determined as follows:
* - if a local file was opened using the "Open File" dialog, returns the local file name;
* - else, if a new file was created using the "newDocument" method, returns the argument passed to that method;
* - else, if options.friendlyFileName is not empty, returns its value;
* - else, returns the name generated from the URL passed to the "open" method.
* @example
* ```javascript
* var viewer = new DsPdfViewer('#root');
* viewer.onAfterOpen.register(function() {
* alert("The document is opened, the fileName is " + viewer.fileName);
* });
* viewer.open('MyDocuments/Test.pdf');
* ```
**/
get fileName(): string;
/**
* Gets the PDF document file size in bytes.
* @example
* ```javascript
* const fileSizeBytes = await viewer.fileSize;
* ```
**/
get fileSize(): Promise<number>;
/**
* Gets the URL that was used to open the document.
* Returns an empty string when the document was opened from binary data.
* @example
* ```javascript
* var viewer = new DsPdfViewer('#root');
* viewer.onAfterOpen.register(function() {
* alert("The document is opened, the fileUrl is " + viewer.fileUrl);
* });
* viewer.open('MyDocuments/Test.pdf');
* ```
**/
get fileUrl(): string;
/**
* Gets a value indicating whether the editor mode is currently active.
* @example
* ```javascript
* let isInEditorMode = viewer.isInEditorMode;
* ```
* @example
* ```javascript
* // Detect the start/end of edit mode
* var isEdit = false;
* viewer.onViewerStateChange.register(function () {
* if (viewer.isInEditorMode !== isEdit) {
* isEdit = viewer.isInEditorMode;
* console.log(isEdit ? "Editor Mode activated." : "Editor Mode deactivated.");
* }
* });
* ```
**/
get isInEditorMode(): boolean;
/**
* Activated editor mode name.
**/
get activatedEditorMode(): "SecondBar" | "FormEditor" | "AnnotationEdtor" | "Any" | "" | undefined;
/**
* Left sidebar API.
* @example
* ```javascript
* viewer.leftSidebar.hide();
* ```
**/
get leftSidebar(): LeftSidebar;
/**
* Toggles the visibility of a panel. If no handle is provided, it toggles the currently active sidebar panel.
* If a handle is provided, it expands the panel if it is collapsed or collapses it if it is active.
*
* @param {PanelHandle | string} [handle] - The panel handle or panel ID to toggle.
*/
togglePanel(handle?: PanelHandle | string): void;
/**
* Data storage for the active document.
* @example
* ```javascript
* const fileData = viewer.storage.getItem(annotation.fileId);
* ```
* @example
* ```javascript
* viewer.storage.setItem(fileId, bytes);
* ```
* @example
* Add Stamp annotation programatically using storage API
* ```javascript
* viewer.newDocument().then(function() {
* var xhr = new XMLHttpRequest();
* xhr.open('GET', 'http://localhost/sample.jpg', true);
* xhr.responseType = 'arraybuffer';
* xhr.onload = function(e) {
* var arrayBuffer = this.response;
* if (arrayBuffer) {
* // Add Stamp annotation programatically:
* viewer.storage.setItem("sample_file_id_1", new Uint8Array(arrayBuffer));
* var pageSize = viewer.getPageSize(0);
* viewer.addAnnotation(0, {annotationType: 13, fileId: "sample_file_id_1", rect: [0, pageSize.height - 144, 144, pageSize.height]});
* }
* };
* xhr.send();
* });
* ```
**/
get storage(): DataStorage;
/**
* Returns data storage which can be used to store and retrieve current signature tool settings and images.
* Please, note, the storage data depends on current user name, see {@link currentUserName} property
**/
get signToolStorage(): SignToolStorage;
/**
* Indicates whether the document has been modified by the user.
* @example
* ```javascript
* if(viewer.hasChanges) {
* alert("The document has been changed.");
* }
* ```
* */
get hasChanges(): boolean;
get changesVersion(): number;
/**
* Indicates whether the copy buffer contains any data.
* @example
* ```javascript
* if(viewer.hasCopyData) {
* viewer.execPasteAction();
* }
* ```
**/
get hasCopyData(): boolean;
/**
* Indicates whether the document is loaded into view.
* @example
* ```javascript
* if(!viewer.hasDocument) {
* viewer.open("sample.pdf");
* }
* ```
**/
get hasDocument(): boolean;
/**
* Determines whether the annotation layer is hidden.
* @example
* ```javascript
* // Hide annotations:
* viewer.hideAnnotations = true;
* ```
**/
get hideAnnotations(): boolean;
/**
* Determines whether the annotation layer is hidden.
* @example
* ```javascript
* // Hide annotations:
* viewer.hideAnnotations = true;
* ```
**/
set hideAnnotations(hide: boolean);
/**
* Gets or sets the layout mode (0 - Viewer, 1 - AnnotationEditor or 2 - FormEditor).
* @default 0
* @example
* ```javascript
* // Set the layout mode to "Form editor"
* viewer.layoutMode = 2;
* ```
**/
get layoutMode(): LayoutMode;
/**
* Gets or sets the layout mode (0 - Viewer, 1 - AnnotationEditor or 2 - FormEditor).
* @default 0
* @example
* ```javascript
* // Set the layout mode to "Form editor"
* viewer.layoutMode = 2;
* ```
**/
set layoutMode(mode: LayoutMode);
/**
* Gets current log level. Available log levels are: 'None', 'Critical', 'Error', 'Warning', 'Information', 'Debug', 'Trace'. Default level is 'None'.
**/
get logLevel(): LogLevel;
/**
* Sets current log level. Available log levels are: 'None', 'Critical', 'Error', 'Warning', 'Information', 'Debug', 'Trace'. Default level is 'None'.
**/
set logLevel(logLvel: LogLevel);
/**
* Gets modifications state for active document. Requires SupportApi.
* @example
* ```javascript
* var modificationsState = viewer.modificationsState;
* console.log(modificationsState);
* ```
* */
get modificationsState(): ModificationsState;
/**
* Default optional content config.
* An optional content is a collection of graphics that can be made visible or invisible dynamically.
* @example
* ```javascript
* // Use the optionalContentConfig property to print information about all available layers
* const config = await viewer.optionalContentConfig;
* console.table(config.getGroups());
* ```
* @example
* ```javascript
* const config = await viewer.optionalContentConfig;
* // Turn off optional content group with id "13R":
* config.setVisibility("13R", false);
* // Repaint visible pages:
* viewer.repaint();
* ```
**/
get optionalContentConfig(): Promise<OptionalContentConfig>;
/**
* Structure tree data.
* @example
* ```javascript
* const viewer = new DsPdfViewer(selector);
* await viewer.open("sample.pdf");
* const structureTree = await viewer.structureTree;
* if(structureTree) {
* console.log(structureTree);
* }
* ```
* @returns {Promise<StructTreeNode>} A promise that is resolved with a
* {@link StructTreeNode[]} objects that represents the page's structure tree,
* or `null` when no structure tree is present for the page.
**/
get structureTree(): Promise<StructTreeNode[] | null>;
/**
*
* @ignore exclude from docs
* @param pageIndex
* @param id
*/
scrollMarkedTextIntoView(pageIndex: number, id: string): Promise<void>;
/**
* The viewer options.
* @example
* ```javascript
* viewer.options.zoomByMouseWheel = { always: true };
* viewer.applyOptions();
* ```
**/
get options(): Partial<ViewerOptions>;
/**
* PDF viewer options.
* */
set options(options: Partial<ViewerOptions>);
/**
* Get type by type name.
* @ignore exclude from docs
* @param typeName
* @example
* ```javascript
* // Get TextAnnotation class:
* var TextAnnotation = viewer.getType('TextAnnotation');
* // Create instance of TextAnnotation class:
* var annot1 = new TextAnnotation()
* // Result annot1 object:
* // { annotationFlags: 0, annotationType: 1, borderStyle: {width: 0, style: 1, horizontalCornerRadius: 0, verticalCornerRadius: 0},
* // name: "Note", open: false, subtype: "Text", useCustomAppearance: true }
* ```
* @example
* ```javascript
* // Get AnnotationTypeCode enumeration:
* var AnnotationTypeCode = viewer.getType('AnnotationTypeCode');
* // Print line annotation type code:
* console.log(AnnotationTypeCode.LINE)
* ```
*/
getType(typeName: string): typeof React | typeof AnnotationBase | typeof GcPdfViewer | typeof ReactDOM | typeof AsyncLock | typeof PdfReportPlugin | typeof AnnotationTypeCode | typeof ViewMode | typeof ZoomMode | typeof utf8ToBase64 | typeof PromiseQueue | typeof EditMode | typeof GenericButton | typeof ViewerStatus | typeof ViewerOptions | typeof LayoutMode | typeof Toolbar | typeof GcMeasurement | typeof GcPdfSearcher | typeof GcRightSidebar | null;
/**
* Gets the PDF plug-in.
* @ignore exclude from docs
**/
get plugin(): PdfReportPlugin;
/**
* Specifies the rotation in degrees.
* @example
* ```javascript
* var viewer = new DsPdfViewer('#root');
* // Register an onAfterOpen event handler:
* viewer.onAfterOpen.register(function() {
* // Apply 90 degree clockwise rotation:
* viewer.rotation = 90;
* });
* // Open document:
* viewer.open('Test.pdf');
* ```
* */
get rotation(): number;
/**
* Specifies the rotation in degrees.
* @example
* ```javascript
* var viewer = new DsPdfViewer('#root');
* // Register an onAfterOpen event handler:
* viewer.onAfterOpen.register(function() {
* // Apply 90 degree clockwise rotation:
* viewer.rotation = 90;
* });
* // Open document:
* viewer.open('Test.pdf');
* ```
* */
set rotation(degrees: number);
/**
* Document search worker instance.
* Searches currently opened document for a text.
* @example
* ```javascript
* // Highlight all search results without opening SearchPanel.
* const searchIterator = viewer.searcher.search({ Text: "test", MatchCase: true, HighlightAll: true });
* searchIterator.next();
* searcher.applyHighlight();
* ```
* @example
* ```javascript
* // Iterate all search results
* const searcher = viewer.searcher;
* var searchResults = [];
* const searchIterator = searcher.search({ Text: textToSearch, MatchCase: true });
* var searchResult = await searchIterator.next();
* if (searchResult.value)
* searcher.highlight(searchResult.value)
* while (searchResult.value && !searchResult.done) {
* const searchResultValue = searchResult.value;
* searchResults.push(`index: ${searchResultValue.ItemIndex}, text: ${searchResultValue.DisplayText}, pageIndex: ${searchResultValue.PageIndex}`);
* searchResult = await searchIterator.next();
* }
* console.log("Search results: " + (searchResults.length ? searchResults.join("; ") : "No search results"));
* ```
* @example
* ```javascript
* // Open the document, find the text 'wildlife' and highlight the first result:
* async function loadPdfViewer(selector) {
* var viewer = new DsPdfViewer(selector, { restoreViewStateOnLoad: false });
* viewer.addDefaultPanels();
* var afterOpenPromise = new Promise((resolve)=>{ viewer.onAfterOpen.register(()=>{ resolve(); }); });
* await viewer.open('wetlands.pdf');
* await afterOpenPromise;
* var findOptions = { Text: 'wildlife' };
* var searchIterator = await viewer.searcher.search(findOptions);
* var searchResult = await searchIterator.next();
* viewer.searcher.cancel();
* viewer.searcher.highlight(searchResult.value);
* }
* loadPdfViewer('#root');
* ```
* @example
* // Open the document, find the text 'wildlife' and print search results to the console:
* ```javascript
* async function loadPdfViewer(selector) {
* var viewer = new DsPdfViewer(selector);
* viewer.addDefaultPanels();
* await viewer.open('wetlands.pdf');
* await (new Promise((resolve)=>{
* viewer.onAfterOpen.register(()=>{
* resolve();
* });
* }));
* var findOptions = {
* Text: 'wildlife',
* MatchCase: true,
* WholeWord: true,
* StartsWith: false,
* EndsWith: false,
* Wildcards: false,
* Proximity: false,
* SearchBackward: false,
* HighlightAll: true
* };
* var searcher = viewer.searcher;
* var searchIterator = await searcher.search(findOptions);
* var resultsCount = 0;
* var searchResult;
* do {
* searchResult = await searchIterator.next();
* if (searchResult.value) {
* // this could be either result or progress message (ItemIndex < 0)
* if(searchResult.value.ItemIndex >= 0) {
* console.log('next search result:');
* console.log(searchResult.value);
* resultsCount++;
* } else {
* const pageCount = _doc.pageCount.totalPageCount || _doc.pageCount.renderedSoFar;
* console.log('search progress, page index is ' + searchResult.value.PageIndex);
* }
* }
* else {
* console.log("Search completed");
* break;
* }
* }
* while(!searchResult.done);
* console.log('Total results count is ' + resultsCount);
* }
* ```
*/
get searcher(): GcPdfSearcher;
/**
* Gets the search panel handle if the search panel has been added to the user interface.
* @ignore Exclude from docs until first v5 hotfix
* @example
* ```javascript
* // Close search panel:
* viewer.leftSidebar.menu.panels.close(viewer.searchPanelHandle.id);
* ```
**/
get searchPanelHandle(): PanelHandle | undefined;
get isSearchPanelExpanded(): boolean;
get isFloatingSearchBarExpanded(): boolean;
/**
* Toggles the visibility of the Search UI, which includes both the search bar and search panel.
* Allows switching between Search and Replace modes, and optionally expanding or collapsing the UI.
*
* @param {boolean} [expand=true] - Whether to expand (true) or collapse (false) the Search UI. Default is true.
* @param {boolean} [replaceMode=false] - Whether to enable Replace mode in the Search UI. Default is false.
*
* @example
* ```javascript
* // Example 1: Default behavior (expand the Search UI and disable Replace mode)
* viewer.toggleSearchUI();
* // The Search UI expands and displays in Search mode.
* ```
*
* @example
* ```javascript
* // Example 2: Expand the Search UI and enable Replace mode
* viewer.toggleSearchUI(true, true);
* // The Search UI expands and displays the Replace mode.
* ```
*
* @example
* ```javascript
* // Example 3: Collapse the Search UI
* viewer.toggleSearchUI(false);
* // The Search UI collapses, hiding the search components.
* ```
*
* @example
* ```javascript
* // Example 4: Expand the Search UI without enabling Replace mode
* viewer.toggleSearchUI(true, false);
* // The Search UI expands but remains in Search mode.
* ```
*/
toggleSearchUI(expand?: boolean, replaceMode?: boolean): void;
closeSearchPanel(): void;
closeFloatingSearchBar(): void;
/**
* Gets the search panel component if the search panel is rendered to the user interface.
* @ignore Exclude from docs until first v5 hotfix
* @example
* ```javascript
* // Open search panel:
* viewer.leftSidebar.menu.panels.open(viewer.searchPanelHandle.id);
* // Perform new search:
* viewer.searchPanel.beginSearch({Text: "Hello", MatchCase: true});
* ```
**/
get searchPanel(): SearchPanel | undefined;
/**
* Gets the SupportApi client.
* Requires SupportApi.
* @example
* ```javascript
* var viewer = new DsPdfViewer('#root', { supportApi: 'api/pdf-viewer' } );
* // Contact server and get Support API version.
* viewer.serverVersion.then(function(ver) {
* alert("The SupportApi version is " + ver);
* });
* ```
* */
get supportApi(): ISupportApi | null;
/**
* Defines the layout of the toolbar for different viewer modes:
* viewer, annotationEditor, formEditor.
* @description
* The full list of the *viewer* specific toolbar items:
* ```javascript
* 'open', '$navigation', '$split', 'text-selection', 'pan', 'zoom', '$fullscreen', '$split', 'text-tools', 'draw-tools', 'attachment-tools',
* 'form-tools', 'page-tools', '$split', 'rotate', 'search', 'page-display', 'theme-change', 'print', 'save-as', 'hide-annotations', 'form-filler',
* 'doc-title', 'doc-properties', 'about', 'share', 'single-page', 'continuous-view', 'page-display', '$history', '$mousemode', 'show-edit-tools', 'show-form-editor'
* ```
* The full list of the *annotationEditor* specific toolbar items:
* ```javascript
* 'edit-select', 'save-as', 'share', 'edit-text', 'edit-free-text', 'edit-ink', 'edit-square',
* 'edit-circle', 'edit-line', 'edit-polyline', 'edit-polygon', 'edit-stamp', 'edit-file-attachment', 'edit-richmedia', 'edit-sound', 'edit-link', 'edit-highlight', 'edit-underline', 'edit-squiggly', 'edit-strike-out'.
* 'edit-redact', 'edit-redact-apply', 'edit-erase', 'edit-undo', 'edit-redo', 'new-document', 'new-page', 'delete-page', '$split', 'pdf-organizer'
* ```
* The full list of the *formEditor* specific toolbar items:
* ```javascript
* 'edit-select-field', 'save-as', 'share',
* 'edit-widget-tx-field', 'edit-widget-tx-password', 'edit-widget-tx-text-area', 'edit-widget-btn-checkbox', 'edit-widget-btn-radio',
* 'edit-widget-btn-push', 'edit-widget-ch-combo', 'edit-widget-ch-list-box', 'edit-widget-tx-comb', 'edit-widget-btn-submit', 'edit-widget-btn-reset',
* 'edit-erase-field', 'edit-undo', 'edit-redo', 'new-document', 'new-page', 'delete-page', '$split', 'pdf-organizer'
* ```
* @example
* ```javascript
* // Customize the toolbar layout:
* viewer.toolbarLayout.viewer.default = ["open", "save", "share"];
* viewer.toolbarLayout.annotationEditor.default = ["open", "save", "share", "$split", "new-document", "edit-ink", "edit-text"];
* viewer.toolbarLayout.formEditor.default = ["open", "save", "share", "$split", "edit-widget-tx-field", "edit-widget-tx-password"];
* viewer.applyToolbarLayout();
* ```
* @example
* ```javascript
* // Show only Open and Redact buttons:
* var viewer = new DsPdfViewer('#root', { supportApi: 'api/pdf-viewer' });
* // Add annotation editor panel:
* viewer.addAnnotationEditorPanel();
* // Change toolbar layout:
* viewer.toolbarLayout = { viewer: { default: ["open", 'show-edit-tools']},
* annotationEditor: { default: ["open", 'edit-redact', 'edit-redact-apply']} };
* // Activate 'Annotation Editor' layout mode:
* viewer.layoutMode = 1;
* ```
* @example
* ```javascript
* // Make square, circle and line buttons sticky:
* viewer.toolbarLayout.stickyBehavior = ["edit-square", "edit-circle", "edit-line"];
* viewer.applyToolbarLayout();
* ```
**/
get toolbarLayout(): PdfToolbarLayout;
/**
* Defines the layout of the toolbar for different viewer modes:
* viewer, annotationEditor, formEditor.
* @description
* The full list of the *viewer* specific toolbar items:
* ```javascript
* 'text-selection', 'pan', 'open', 'save-as', 'share', 'print', 'rotate', 'theme-change', 'doc-title', 'page-display', 'single-page', 'continuous-view',
* '$navigation' '$refresh', '$history', '$mousemode', 'zoom', '$fullscreen', '$split', 'show-edit-tools', 'show-form-editor'
* ```
* The full list of the *annotationEditor* specific toolbar items:
* ```javascript
* 'edit-select', 'save-as', 'share', 'edit-text', 'edit-free-text', 'edit-ink', 'edit-square',
* 'edit-circle', 'edit-line', 'edit-polyline', 'edit-polygon', 'edit-stamp', 'edit-file-attachment', 'edit-richmedia', 'edit-sound', 'edit-link', 'edit-highlight', 'edit-underline', 'edit-squiggly', 'edit-strike-out'.
* 'edit-redact', 'edit-redact-apply', 'edit-erase', 'edit-undo', 'edit-redo', 'new-document', 'new-page', 'delete-page', '$split', 'pdf-organizer'
* ```
* The full list of the *formEditor* specific toolbar items:
* ```javascript
* 'edit-select-field', 'save-as', 'share',
* 'edit-widget-tx-field', 'edit-widget-tx-password', 'edit-widget-tx-text-area', 'edit-widget-btn-checkbox', 'edit-widget-btn-radio',
* 'edit-widget-btn-push', 'edit-widget-ch-combo', 'edit-widget-ch-list-box', 'edit-widget-tx-comb', 'edit-widget-btn-submit', 'edit-widget-btn-reset',
* 'edit-erase-field', 'edit-undo', 'edit-redo', 'new-document', 'new-page', 'delete-page', '$split', 'pdf-organizer'
* ```
* @example
* ```javascript
* // Customize the toolbar layout:
* viewer.toolbarLayout.viewer.default = ["open", "save", "share"];
* viewer.toolbarLayout.annotationEditor.default = ["open", "save", "share", "$split", "new-document", "edit-ink", "edit-text"];
* viewer.toolbarLayout.formEditor.default = ["open", "save", "share", "$split", "edit-widget-tx-field", "edit-widget-tx-password"];
* viewer.applyToolbarLayout();
* ```
* @example
* ```javascript
* // Show only Open and Redact buttons:
* var viewer = new DsPdfViewer('#root', { supportApi: 'api/pdf-viewer' });
* // Add annotation editor panel:
* viewer.addAnnotationEditorPanel();
* // Change toolbar layout:
* viewer.toolbarLayout = { viewer: { default: ["open", 'show-edit-tools']},
* annotationEditor: { default: ["open", 'edit-redact', 'edit-redact-apply']} };
* // Activate 'Annotation Editor' layout mode:
* viewer.layoutMode = 1;
* ```
**/
set toolbarLayout(toolbarLayout: PdfToolbarLayout);
/**
* Second toolbar layout.
* Use the secondToolbarLayout property to configure available tools.
* @default {
* "text-tools": ['edit-text', 'edit-free-text', 'edit-ink', '$split', 'edit-highlight', 'edit-underline', 'edit-squiggly', 'edit-strike-out', '$split', 'edit-undo', 'edit-redo', 'edit-erase', '$split', 'edit-redact', 'edit-redact-apply'],
* "draw-tools": ['edit-square', 'edit-circle', 'edit-line', 'edit-polyline', 'edit-polygon', '$split', 'edit-undo', 'edit-redo', 'edit-erase', '$split', 'edit-redact', 'edit-redact-apply'],
* "attachment-tools": ['edit-stamp', 'edit-file-attachment', 'edit-richmedia', 'edit-sign-tool', 'edit-sound', '$split', 'edit-undo', 'edit-redo', 'edit-erase', '$split', 'edit-redact', 'edit-redact-apply'],
* "form-tools": ['edit-widget-tx-field', 'edit-widget-tx-password', 'edit-widget-tx-text-area', 'edit-widget-btn-checkbox', 'edit-widget-btn-radio', 'edit-widget-btn-push', 'edit-widget-ch-combo', 'edit-widget-ch-list-box', 'edit-widget-tx-comb', 'edit-widget-btn-submit', 'edit-widget-btn-reset', '$split', 'edit-undo', 'edit-redo', 'edit-erase', '$split', 'edit-redact', 'edit-redact-apply'],
* "page-tools": ['new-document', 'new-page', 'delete-page', '$split', 'edit-undo', 'edit-redo', '$split', 'pdf-organizer']
* }
**/
get secondToolbarLayout(): SecondToolbarLayout;
/**
* Second toolbar layout.
* Use the secondToolbarLayout property to configure available tools.
* @default {
* "text-tools": ['edit-text', 'edit-free-text', 'edit-ink', '$split', 'edit-undo', 'edit-redo', 'edit-erase', '$split', 'edit-redact', 'edit-redact-apply'],
* "draw-tools": ['edit-square', 'edit-circle', 'edit-line', 'edit-polyline', 'edit-polygon', '$split', 'edit-undo', 'edit-redo', 'edit-erase', '$split', 'edit-redact', 'edit-redact-apply'],
* "attachment-tools": ['edit-stamp', 'edit-file-attachment', 'edit-richmedia', 'edit-sign-tool', 'edit-sound', '$split', 'edit-undo', 'edit-redo', 'edit-erase', '$split', 'edit-redact', 'edit-redact-apply'],
* "form-tools": ['edit-widget-tx-field', 'edit-widget-tx-password', 'edit-widget-tx-text-area', 'edit-widget-btn-checkbox', 'edit-widget-btn-radio', 'edit-widget-btn-push', 'edit-widget-ch-combo', 'edit-widget-ch-list-box', 'edit-widget-tx-comb', 'edit-widget-btn-submit', 'edit-widget-btn-reset', '$split', 'edit-undo', 'edit-redo', 'edit-erase', '$split', 'edit-redact', 'edit-redact-apply'],
* "page-tools": ['new-document', 'new-page', 'delete-page', '$split', 'edit-undo', 'edit-redo', '$split', 'pdf-organizer']
* }
**/
set secondToolbarLayout(layout: SecondToolbarLayout);
/**
* Returns the current version of the GcDocs PDF viewer.
* @example
* ```javascript
* alert("The DsPdfViewer version is " + viewer.version);
* ```
* */
get version(): string;
/**
* Indicates whether the Reply Tool has been added.
* @example
* ```javascript
* var viewer = new DsPdfViewer('#root');
* if(viewer.hasReplyTool) {
* alert("The Reply Tool has not been added to the viewer.");
* } else {
* alert("The Reply Tool has been added to the viewer.");
* }
* viewer.open('Test.pdf');
* ```
**/
get hasReplyTool(): boolean;
/**
* Gets right sidebar object.
* Use this object if you want to manipulate the right sidebar.
* @example
* ```javascript
* viewer.rightSidebar.show('expanded', 'reply-tool');
* viewer.rightSidebar.toggle();
* viewer.rightSidebar.hide();
* viewer.rightSidebar.expand();
* viewer.rightSidebar.collapse();
* ```
* */
get rightSidebar(): GcRightSidebar;
/**
* An unique document identifier.
* @example
* ```javascript
* var viewer = new DsPdfViewer('#root');
* viewer.onAfterOpen.register(function() {
* alert("The document opened, an unique document identifier is "+ viewer.fingerprint);
* });
* viewer.open('Test.pdf');
* ```
**/
get fingerprint(): string;
/**
* Gets i18next instance which can be used to add viewer translations.
* See https://www.i18next.com for details about i18next framework.
* @example
* ```javascript
* function loadPdfViewer(selector) {
* // You can load translations from any source (see en-pdf-viewer.json for an example):
* var myTranslations = {
* "toolbar": {
* "open-document": "Open MY document",
* "pan": "My Pan tool",
* }
* };
* // Initialize translations:
* DsPdfViewer.i18n.init({
* resources: { myLang: { viewer: myTranslations } },
* defaultNS: 'viewer'
* }).then(function(t) {
* // New translations initialized and ready to go!
* // Now create PDF viewer:
* var viewer = new DsPdfViewer(selector, { language: 'myLang' });
* viewer.addDefaultPanels();
* //viewer.open("sample.pdf");
* });
* }
* loadPdfViewer('#root');
* ```
**/
static get i18n(): i18n;
/**
* Retrieves all annotations in the document, organized by page.
*
* This property returns a promise that resolves to an array of objects, where each object represents a page in the document.
* Each object contains the page index and an array of annotations present on that page.
*
* @returns {Promise<{ pageIndex: number, annotations: AnnotationBase[] }[]>} A promise that resolves with annotations grouped by page.
*
* @example Basic usage:
* ```javascript
* var viewer = new DsPdfViewer('#root');
* viewer.addDefaultPanels();
* viewer.onAfterOpen.register(function() {
* viewer.annotations.then(function(data) {
* data.forEach(pageData => {
* console.log(`Page ${pageData.pageIndex} has ${pageData.annotations.length} annotation(s)`);
* });
* });
* });
* viewer.open('Test.pdf');
* ```
*
* @example Filtering annotations by type:
* ```javascript
* viewer.annotations.then(function(data) {
* data.forEach(pageData => {
* const highlightAnnotations = pageData.annotations.filter(ann => ann.annotationType === 9);
* console.log(`Page ${pageData.pageIndex} has ${highlightAnnotations.length} highlight annotation(s)`);
* });
* });
* ```
*
* @example Accessing specific annotation properties:
* ```javascript
* viewer.annotations.then(function(data) {
* data.forEach(pageData => {
* pageData.annotations.forEach(annotation => {
* console.log(`Annotation ID: ${annotation.id}, Type: ${annotation.subtype}, Contents: ${annotation.contents}`);
* });
* });
* });
* ```
*
* @example Error handling:
* ```javascript
* viewer.annotations
* .then(data => {
* console.log(`Retrieved annotations for ${data.length} pages`);
* })
* .catch(error => {
* console.error('Failed to retrieve annotations:', error);
* });
* ```
*/
get annotations(): Promise<{
pageIndex: number;
annotations: AnnotationBase[];
}[]>;
/**
* Provides access to the XFDF manager, which handles importing and exporting annotation data in XFDF format.
*
* @returns {AnnotationXFDFHandler} The instance of AnnotationXFDFHandler.
*/
get xfdfManager(): XFDFAnnotationHandler;
/**
* Ask the user if he want to leave the page when document is modified.
* Requires SupportApi.
* @example
* ```javascript
* var viewer = new DsPdfViewer('#root', { supportApi: 'api/pdf-viewer' } );
* viewer.addDefaultPanels();
* viewer.addAnnotationEditorPanel();
* viewer.addFormEditorPanel();
* viewer.beforeUnloadConfirmation = true;
* ```
**/
get beforeUnloadConfirmation(): boolean;
/**
* Ask the user if he want to leave the page when document is modified.
* Requires SupportApi.
* @example
* ```javascript
* var viewer = new DsPdfViewer('#root', { supportApi: 'api/pdf-viewer' } );
* viewer.addDefaultPanels();
* viewer.addAnnotationEditorPanel();
* viewer.addFormEditorPanel();
* viewer.beforeUnloadConfirmation = true;
* ```
**/
set beforeUnloadConfirmation(enable: boolea