/*! * @compdfkit_pdf_sdk/webviewer type definitions * (c) ComPDFKit */ /** * Core.Math: geometry types (Point / Rect / Quad / Matrix). * Rect uses x1, y1, x2, y2, not x, y, width, height. * Conventions: Matrix uses column vectors (p' = M · p; toTransform gives [a b c d e f], x' = a·x + c·y + e); * translate / rotate / scale / transform / normalize modify in place and return nothing; add / subtract and similar return new objects. */ /** A matrix of numbers, 3×3 by default, used for 2D affine transforms on column vectors (p' = M · p). */ declare class Matrix { /** Number of rows. */ readonly rows: number; /** Number of columns. */ readonly columns: number; /** A new 3×3 identity matrix. */ static get Identity(): Matrix; /** * Multiplies a list of transforms in order into one, optionally around a point (default 0, 0: move the point to the origin, apply the transforms, then move it back). */ static createTransformWithRespectTo(transforms: Matrix[], origin?: Point): Matrix; /** Canvas DOMMatrix (a b c d e f) to matrix: [a c e; b d f; 0 0 1]. */ static fromDOMMatrix(dom: { /** Row 0, column 0 (horizontal scale). */ a: number; /** Row 1, column 0. */ b: number; /** Row 0, column 1. */ c: number; /** Row 1, column 1 (vertical scale). */ d: number; /** Row 0, column 2 (horizontal translation). */ e: number; /** Row 1, column 2 (vertical translation). */ f: number; }): Matrix; /** * Multiplies two matrices. Each entry is rounded to 6 decimals. * @param left Left operand. * @param right Right operand; its row count must equal the column count of `left`. * @returns A new matrix `left · right`. * @throws RangeError when the sizes do not match. */ static multiply(left: Matrix, right: Matrix): Matrix; private values; /** Defaults to the 3×3 identity matrix; non-square matrices are all zeros. */ constructor( /** Number of rows. */ rows?: number, /** Number of columns. */ columns?: number); /** Number of rows. */ get Rows(): number; /** Number of columns. */ get Columns(): number; /** * Returns one entry. * @param row Row index (0-based). * @param column Column index (0-based). * @returns The value at that position. */ get(row: number, column: number): number; /** * Sets one entry. * @param row Row index (0-based). * @param column Column index (0-based). * @param value The new value. */ set(row: number, column: number, value: number): void; /** * Sets the horizontal and vertical scale entries. * @param sx Horizontal scale. * @param sy Vertical scale. */ setScale(sx: number, sy: number): void; /** * Sets the horizontal scale entry (row 0, column 0). * @param sx Horizontal scale. */ setScaleX(sx: number): void; /** * Sets the vertical scale entry (row 1, column 1). * @param sy Vertical scale. */ setScaleY(sy: number): void; /** * Sets the translation entries. * @param tx Horizontal translation. * @param ty Vertical translation. */ setTranslate(tx: number, ty: number): void; /** * Sets the horizontal translation entry (row 0, column 2). * @param tx Horizontal translation. */ setTranslateX(tx: number): void; /** * Sets the vertical translation entry (row 1, column 2). * @param ty Vertical translation. */ setTranslateY(ty: number): void; /** * Sets the skew entries. * @param kx Horizontal skew factor. * @param ky Vertical skew factor. */ setSkew(kx: number, ky: number): void; /** * Sets the horizontal skew entry (row 0, column 1). * @param kx Horizontal skew factor. */ setSkewX(kx: number): void; /** * Sets the vertical skew entry (row 1, column 0). * @param ky Vertical skew factor. */ setSkewY(ky: number): void; /** Overwrites the top-left 2×2 with a rotation; counterclockwise when the y axis points up. */ setRotation(angle: number, isRadians?: boolean): void; /** this · m */ multiply(m: Matrix): Matrix; /** Transposes in place (square matrices). */ transpose(): void; /** * Returns the affine part of a 3×3 matrix in canvas order. * @returns `[a, b, c, d, e, f]`, where x' = a·x + c·y + e and y' = b·x + d·y + f. */ toTransform(): [a: number, b: number, c: number, d: number, e: number, f: number]; /** * Copies the matrix. * @returns A new matrix with the same size and values. */ clone(): Matrix; /** * Computes the determinant of a 3×3 matrix. * @returns The determinant. * @throws RangeError when the matrix is not 3×3. */ determinant(): number; /** Gauss-Jordan elimination; returns null for a singular matrix. */ inverse(): Matrix | null; } /** A 2D point or vector. */ declare class Point { /** A new point at (0, 0). */ static get Origin(): Point; /** Horizontal coordinate. */ x: number; /** Vertical coordinate. */ y: number; /** * Creates a point. Strings are parsed as numbers. * @param x Horizontal coordinate. Defaults to 0. * @param y Vertical coordinate. Defaults to 0. */ constructor(x?: number | string, y?: number | string); /** Horizontal coordinate; same as `x`. */ get X(): number; set X(v: number); /** Vertical coordinate; same as `y`. */ get Y(): number; set Y(v: number); /** Distance from the origin, rounded to 6 decimals. */ get Length(): number; /** * Returns the horizontal coordinate. * @returns The x value. */ getX(): number; /** * Returns the vertical coordinate. * @returns The y value. */ getY(): number; /** * Adds another point as a vector. * @param p The point to add. * @returns A new point. */ add(p: Point): Point; /** * Subtracts another point as a vector. * @param p The point to subtract. * @returns A new point `this - p`. */ subtract(p: Point): Point; /** * Computes the dot product. * @param p The other vector. * @returns The dot product, rounded to 6 decimals. */ dot(p: Point): number; /** Cross product using homogeneous coordinates (x, y, 1). */ cross(p: Point): { /** X component. */ X: number; /** Y component. */ Y: number; /** Z component. */ Z: number; }; /** * Computes the distance to another point. * @param p The other point. * @returns The distance, rounded to 6 decimals. */ distance(p: Point): number; /** Angle between two vectors; in degrees by default. */ angle(p: Point, inRadians?: boolean): number; /** * Returns the unit vector in the same direction. * @returns A new point of length 1, or (0, 0) for the zero vector. */ normalize(): Point; /** * Returns the opposite vector. * @returns A new point (-x, -y). */ reverse(): Point; /** * Returns a perpendicular vector. * @returns A new point (y, -x). */ perpendicular(): Point; /** * Moves the point in place. * @param dx Horizontal offset. * @param dy Vertical offset. */ translate(dx: number, dy: number): void; /** Rotates around center; in degrees by default. */ rotate(angle: number, isRadians?: boolean, center?: Point): void; /** * Scales both coordinates in place. * @param factor Scale factor. */ scale(factor: number): void; /** 3×(n+1) matrix: the first column is this point, followed by the homogeneous coordinates of each point. */ toMatrix(...points: Point[]): Matrix; /** * Applies a 3×3 transform matrix in place. * @param m The transform. */ transform(m: Matrix): void; /** * Compares with another point, allowing a difference below 0.00001 on each axis. * @param p The other point. * @returns true when the points are equal within that tolerance. */ equals(p: Point): boolean; /** * Same as equals. * @param p The other point. * @returns true when the points are equal within 0.00001 on each axis. */ equalTo(p: Point): boolean; /** * Checks whether two vectors point in the same direction. * @param p The other vector. * @returns true when their unit vectors are equal. */ isParallelTo(p: Point): boolean; /** * Copies the point. * @returns A new point with the same coordinates. */ clone(): Point; /** * Returns a readable description. * @returns A string such as '[Point: x=1 y=2]'. */ toString(): string; /** * Returns a plain object for JSON serialization. * @returns `{ x, y }`. */ toJSON(): { /** Horizontal coordinate. */ x: number; /** Vertical coordinate. */ y: number; }; } interface RectLike { x1: number; y1: number; x2: number; y2: number; } /** A rectangle given by two corners (x1, y1) and (x2, y2). In page coordinates (top-left origin, y down) x1/y1 is the top-left corner once normalized. */ declare class Rect { /** Touching edges count as intersecting. */ static intersects(a: Rect, b: Rect): boolean; /** b lies entirely inside a. */ static contains(a: Rect, b: Rect): boolean; /** * Creates a rectangle from a corner and a size. * @param x Left edge. * @param y Top edge. * @param width Width. * @param height Height. * @returns A new rectangle (x, y, x + width, y + height). */ static createFromDimensions(x: number, y: number, width: number, height: number): Rect; /** Smallest rectangle that encloses these annotations; undefined for an empty array. */ static createEncapsulatingBoundingBox(annotations: Array<{ /** Returns the annotation rectangle. */ getRect: () => Rect; }>): Rect | undefined; /** Smallest rectangle that encloses all rectangles; undefined for an empty array. */ static combineRects(rects: Rect[]): Rect | undefined; /** x of the first corner (left edge when normalized). */ x1: number; /** y of the first corner (top edge when normalized). */ y1: number; /** x of the second corner (right edge when normalized). */ x2: number; /** y of the second corner (bottom edge when normalized). */ y2: number; /** Also accepts a Rect, [x1, y1, x2, y2] or { x1, y1, x2, y2 }. */ constructor(x1?: number | RectLike | number[], y1?: number, x2?: number, y2?: number); /** * Returns x1. * @returns The x of the first corner. */ getX(): number; /** * Returns y1. * @returns The y of the first corner. */ getY(): number; /** * Returns the left edge (x1). * @returns x1. */ getLeft(): number; /** * Returns the right edge (x2). * @returns x2. */ getRight(): number; /** * Returns the top edge (y1). * @returns y1. */ getTop(): number; /** * Returns the bottom edge (y2). * @returns y2. */ getBottom(): number; /** Signed; may be negative before normalize. */ getWidth(): number; /** * Returns the height; signed, may be negative before normalize. * @returns y2 - y1. */ getHeight(): number; /** * Returns the top-left corner. * @returns A new point (x1, y1). */ getTopLeft(): Point; /** * Returns the top-right corner. * @returns A new point (x2, y1). */ getTopRight(): Point; /** * Returns the bottom-left corner. * @returns A new point (x1, y2). */ getBottomLeft(): Point; /** * Returns the bottom-right corner. * @returns A new point (x2, y2). */ getBottomRight(): Point; /** * Returns the center. * @returns A new point at the middle of the rectangle. */ getCenter(): Point; /** * Moves the rectangle in place. * @param dx Horizontal offset. * @param dy Vertical offset. */ translate(dx: number, dy: number): void; /** Moves the rectangle inside container (only along axes where it fits). */ fitTo(container: Rect): void; /** Makes x1 ≤ x2 and y1 ≤ y2. */ /** Bounding rectangle of the two rectangles (y uses both rectangles' y values). */ join(other: Rect): Rect; /** Swaps corners in place so that x1 ≤ x2 and y1 ≤ y2. */ normalize(): void; /** For PDF export: x1 ≤ x2 and y1 ≥ y2 (PDF y points up). */ exportNormalize(): void; /** * Checks whether this rectangle intersects another; touching edges count. * @param r The other rectangle. * @returns true when they intersect. */ intersects(r: Rect): boolean; /** * Checks whether another rectangle lies entirely inside this one. * @param r The other rectangle. * @returns true when `r` is inside. */ contains(r: Rect): boolean; /** Transforms the two opposite corners and returns their bounding box. */ transform(m: Matrix): void; /** Order: bottom-left, bottom-right, top-right, top-left. */ toQuad(): Quad; /** * Checks whether all four coordinates are exactly equal. * @param r The other rectangle. * @returns true when equal. */ equalTo(r: Rect): boolean; } /** Quadrilateral of 8 numbers: x1,y1 … x4,y4 (same order as Rect.toQuad: bottom-left, bottom-right, top-right, top-left). */ declare class Quad { /** x of point 1 (bottom-left). */ x1: number; /** y of point 1 (bottom-left). */ y1: number; /** x of point 2 (bottom-right). */ x2: number; /** y of point 2 (bottom-right). */ y2: number; /** x of point 3 (top-right). */ x3: number; /** y of point 3 (top-right). */ y3: number; /** x of point 4 (top-left). */ x4: number; /** y of point 4 (top-left). */ y4: number; /** * Creates a quad from four corner points. * @param x1 x of point 1 (bottom-left). * @param y1 y of point 1. * @param x2 x of point 2 (bottom-right). * @param y2 y of point 2. * @param x3 x of point 3 (top-right). * @param y3 y of point 3. * @param x4 x of point 4 (top-left). * @param y4 y of point 4. */ constructor( /** x of point 1 (bottom-left). */ x1?: number, /** y of point 1 (bottom-left). */ y1?: number, /** x of point 2 (bottom-right). */ x2?: number, /** y of point 2 (bottom-right). */ y2?: number, /** x of point 3 (top-right). */ x3?: number, /** y of point 3 (top-right). */ y3?: number, /** x of point 4 (top-left). */ x4?: number, /** y of point 4 (top-left). */ y4?: number); /** Uses point 4 (top-left) and point 2 (bottom-right). */ toRect(): Rect; /** The 8 numbers by name: { x1, y1, … x4, y4 } (used to turn redaction search results into annotation Quads). */ getPoints(): { /** x of point 1. */ x1: number; /** y of point 1. */ y1: number; /** x of point 2. */ x2: number; /** y of point 2. */ y2: number; /** x of point 3. */ x3: number; /** y of point 3. */ y3: number; /** x of point 4. */ x4: number; /** y of point 4. */ y4: number; }; } /** * Core.Math.TransformationBuilder: records transforms in call order and multiplies them in order in getFinalTransform. * Indexes follow insertion order (getAt(0) is the first added and first applied; the internal array is stored reversed). */ declare class TransformationBuilder { /** The recorded matrices, most recently added first. */ queue: Matrix[]; /** * Creates a builder. * @param queue Initial matrices, most recently added first. */ constructor(queue?: Matrix[]); /** Number of recorded matrices. */ get length(): number; /** * Returns a recorded matrix. * @param index Position in insertion order (0 is the first added). * @returns The matrix at that position. */ getAt(index: number): Matrix; /** * Replaces a recorded matrix. * @param index Position in insertion order (0 is the first added). * @param matrix The new matrix. * @returns This builder, for chaining. */ setAt(index: number, matrix: Matrix): this; /** * Inserts a matrix. * @param index Position in insertion order (0 is the first added). * @param matrix The matrix to insert. * @returns This builder, for chaining. */ insertAt(index: number, matrix: Matrix): this; /** Removes the matrix at this position (counted from the last added, same as getAt). */ removeAt(index: number): this; /** * Adds a matrix after all others; it is applied last. * @param matrix The matrix to add. * @returns This builder, for chaining. */ push(matrix: Matrix): this; /** * Removes the most recently added matrix. * @returns This builder, for chaining. */ pop(): this; /** * Adds a translation. * @param x Horizontal offset. Defaults to 0. * @param y Vertical offset. Defaults to 0. * @returns This builder, for chaining. */ translate(x?: number, y?: number): this; /** Translates by (x2 − x1, y2 − y1). */ translateTo(x1: number, y1: number, x2: number, y2: number): this; /** * Adds a scale. * @param sx Horizontal scale. Defaults to 1. * @param sy Vertical scale. Defaults to `sx`. * @returns This builder, for chaining. */ scale(sx?: number | null, sy?: number | null): this; /** * Adds a skew. * @param kx Horizontal skew factor. * @param ky Vertical skew factor. * @returns This builder, for chaining. */ skew(kx: number, ky: number): this; /** * Adds a rotation. * @param angle Rotation angle; in degrees unless `isRadians` is true. * @param isRadians Whether `angle` is in radians. Defaults to false. * @returns This builder, for chaining. */ rotate(angle: number, isRadians?: boolean): this; /** * Combines the recorded matrices into one; the first added is applied first. * @returns The combined transform, or the identity matrix when nothing is recorded. */ getFinalTransform(): Matrix; /** * Removes all recorded matrices. * @returns This builder, for chaining. */ clear(): this; } /** * CanvasManager: page bitmap cache, a Core-level singleton (Core.getCanvasManager()). * Key (docId, page, zoomBucket, rotation, dpr[, rect]); byte-budget LRU. Pages use pageId (stable id, so cached pages stay valid after pages move / are added or removed) plus * the page render version and variant (with annotations / transparent background / print / layer set version / separation, etc.); without pageId the page number is used (callers using this class directly). * The zoomBucket of page renders is a level (render/zoom-tiers.ts), not an arbitrary zoom. * Page renders store ImageBitmaps: eviction, releasePage, clearData and replacement under the same key all call close() to really free them; * when the browser has no createImageBitmap (or the self-check fails) ImageData is stored instead, which has no close and is collected by GC. * Its Worker counterpart is BitmapPool (reuses wasm heap buffers). */ interface PageBitmapKey { docId: string; pageNumber: number; zoomBucket: number; rotation: number; dpr: number; /** Area identifier when only part of the page was rendered; the whole page by default. */ rect?: string; } /** A cached bitmap: ImageBitmap / ImageData / canvas; bytes counted as width × height × 4. */ interface CachedBitmap { width: number; height: number; close?: () => void; } /** Least-recently-used cache of rendered page bitmaps, limited by a memory budget set with the caching level. */ declare class CanvasManager { /** While zooming, the nearest level is stretched for display; renders use the smallest level ≥ zoom. */ static zoomBucket(zoom: number): number; /** Called once when usage crosses 90% of the budget; called again after it drops and crosses again. */ private readonly pressureListeners; private underPressure; /** Map keeps insertion order: the first entry is the least recently used. */ private readonly entries; /** Secondary index: group key → entries of that group. */ private readonly groups; private used; private budget; /** * Creates the cache. * @param options Cache options. * @param options.budgetBytes Memory budget in bytes. Defaults to 128 MB (caching level 2). */ constructor(options?: { budgetBytes?: number; }); /** A hit becomes most recently used. */ peek(key: PageBitmapKey): CachedBitmap | undefined; /** * Stores a bitmap under a key, replacing any bitmap with the same key, and evicts least recently used bitmaps when over budget. The new bitmap itself is never evicted. * @param key Cache key. * @param bitmap The rendered bitmap. */ put(key: PageBitmapKey, bitmap: CachedBitmap): void; /** Releases a whole page when it leaves the viewport or the structure changes; with rect, only that area (such as 'thumbnail'). Pages are identified by page number, so this only matters for keys without pageId. */ releasePage(docId: string, pageNumber: number, rect?: string): void; /** Clears the bitmaps of one document; clears everything when none is given. */ clearData(docId?: string): void; /** 0–3 → 32 / 64 / 128 / 256 MB */ setCachingLevel(level: number): void; /** keep is the new bitmap replacing one under the same key and must not be closed. */ private remove; /** * When over budget, evicts from the least recently used, retained bitmaps after all ordinary ones; the just-added bitmap (keep) is never evicted, even when it alone exceeds the budget: * the caller is about to draw it (if retained bitmaps fill the budget and it were evicted and closed in the first round, the following drawImage would throw and count as a render failure). */ private evict; private checkPressure; } /** Machine-readable code carried by every ComPDFKitError. */ type ErrorCode = 'NOT_INITIALIZED' | 'ALREADY_DESTROYED' | 'NOT_IMPLEMENTED' | 'INVALID_HANDLE' | 'INVALID_LICENSE' | 'INVALID_SOURCE' | 'PASSWORD_REQUIRED' | 'UNSUPPORTED_FORMAT' | 'LOAD_FAILED' | 'WORKER_CRASHED' | 'WASM_OOM' | 'TIMEOUT' | 'CANCELLED' | 'CONFLICT' | 'PERMISSION_DENIED' | 'INTERNAL'; /** Error thrown by the SDK. Check `code` to tell failure kinds apart. */ declare class ComPDFKitError extends Error { /** Failure kind. */ readonly code: ErrorCode; /** The underlying cause, when there is one. */ readonly reason?: unknown | undefined; /** Error name, always 'ComPDFKitError'. */ name: string; /** * Creates an SDK error. * @param message Human-readable description. * @param code Failure kind. Defaults to 'INTERNAL'. * @param reason The underlying cause, such as an error from the Worker. */ constructor(message: string, /** Failure kind. */ code?: ErrorCode, /** The underlying cause, when there is one. */ reason?: unknown | undefined); } /** * Cross-thread protocol. The single source of types shared by the main thread and the Worker, * and the home of the data contracts shared by same-named classes. * Stable ids appear only here and in the Worker; the public API uses 1-based pageNumber. */ type PageId = string; type AnnotId = string; /** Result of page.render.init: width × height RGBA, rows tightly packed. */ /** Render result; ms is the render time in the Worker (excluding queueing); heapBytes is this Worker's wasm heap size after rendering (it only grows; the render pool recycles Workers by it). */ interface RenderResult { width: number; height: number; pixels: ArrayBuffer; ms?: number; heapBytes?: number; } /** * Serializable annotation data. Coordinates are in **unrotated page space** (top-left origin, y down, pt); * colors are 0–1 RGB; missing (null) means the PDF has no such color key. type is the engine annotation type number. */ interface AnnotationProps { /** Annotation rectangle (page coordinates). For annotations rotated as a box (rectangle, ellipse, stamp, free text without callout), this is the unrotated box; the rotation angle is in Rotation. */ Rect: [x1: number, y1: number, x2: number, y2: number]; /** Rotation of annotations rotated as a box (degrees, counterclockwise). The Worker has the engine build the appearance from the unrotated box, then rotates the appearance, replaces the rectangle with the bounding box and writes /Rotate. */ Rotation?: number; Author: string; Contents: string; Subject: string; Icon: string; /** PDF date string (D:YYYYMMDDHHmmSS...); an empty string means none. */ DateCreated: string; DateModified: string; /** /F flags. */ Flags: number; StrokeColor: [number, number, number] | null; FillColor: [number, number, number] | null; Opacity: number; StrokeThickness: number; /** Text markup: 8 numbers per quadrilateral, in Quad point order (bottom-left, bottom-right, top-right, top-left). */ Quads?: number[][]; /** Ink: [x, y] points of each path. */ Paths?: Array>; /** Line: start point and end point. */ Line?: [x1: number, y1: number, x2: number, y2: number]; /** Polygon / polyline vertices. */ Vertices?: Array<[number, number]>; /** Free text: padding of the text box inside the annotation rectangle [left, top, right, bottom] (/RD; with a callout the callout lies inside the padding). */ Padding?: [number, number, number, number]; /** Id of the parent annotation of a reply / group; an empty string when none. Replies are written to /IRT (the engine only supports notes); groups are written to the custom key /CPDFGroup. */ InReplyTo?: string; /** 'group' means a group; otherwise a reply. */ ReplyType?: 'group' | null; /** Review state of a note (Accepted, Marked...) and its state model (Review / Marked); an empty string when none. */ State?: string; StateModel?: string; /** Line ending styles of lines / polylines (LineEndType names: None, OpenArrow, ClosedArrow...). */ StartStyle?: string; EndStyle?: string; /** Fill opacity (FillColor.A; SetAnnotFilledTransparency / GetAnnotFilledTransparency): rectangle, ellipse, polygon, free text; only when there is a fill color. */ FillOpacity?: number; /** Cloudy border intensity (BorderEffect); 0 for none. */ CloudIntensity?: number; /** Dash lengths of a dashed border (/BS /S /D and /D, SetAnnotBorderStyle / GetAnnotBorderStyle); null for solid. Line, rectangle, ellipse, polygon, polyline, arc, free text. */ Dashes?: number[] | null; /** Free text: font name, font size (pt), text color (0–1), alignment, intent (FreeText / FreeTextCallout / FreeTextTypewriter). */ Font?: string; FontSize?: number; TextColor?: [number, number, number]; TextAlign?: 'left' | 'center' | 'right'; /** Redaction: overlay text drawn over the redacted area when applied (font, size, color and alignment use Font / FontSize / TextColor / TextAlign above). */ OverlayText?: string; /** Ink intent (/IT; InkHighlight is a highlighter pen; an empty string means none). */ Intent?: string; /** Measurement annotations: kind (distance / perimeter / area / angle / count / arc), scale string, precision; value / text are read-only (computed by the engine). */ Measure?: { type: string; scale: string; precision: number; value?: number; text?: string; } | null; /** Which items the measurement result text shows (JSON of MeasurementDisplayOptions; empty for the defaults); kept in memory only, not written to the file. */ MeasurementDisplay?: string; /** * Write-only: result text of an area measurement; not drawn in the appearance when enabled is false. x, y is the text center (page coordinates). The engine centers the text in the bounding box; * after building the appearance the Worker moves the text there and grows the shape's bounding box bounds [x1, y1, x2, y2] to include it (using the actual text width in the appearance, file-appearances.ts); * size is the font size (not moved when less than one line height from the engine's position). Always sent when an area measurement changes. */ MeasureCaption?: { enabled: boolean; x: number; y: number; size: number; bounds: [number, number, number, number]; }; /** * Position of a measurement line's result text along the line (LineAnnotation.setCaptionSnapPosition): for start / end, after building the appearance the Worker moves the text outside the start / end point, * grows the rectangle to include it and writes /CO (file-appearances.ts). Sent on change when not center (the engine puts it back in the middle every time it rebuilds the appearance). */ CaptionSnap?: 'start' | 'center' | 'end'; /** Link border style: underline is /BS /S /U (only a bottom line); anything else is solid (Link.StrokeStyle). */ LinkStyle?: 'solid' | 'underline'; /** Leader lines of a measurement line: [length, offset from the end point, extension past the line] (pt). */ Leader?: [length: number, offset: number, extension: number]; /** Write-only: pixels (RGBA) of an image stamp; sent with the diff only when version changes. */ StampImage?: { version: number; width: number; height: number; pixels: ArrayBuffer; }; /** /RC of free text (rich text style XHTML); null when none. */ RichText?: string | null; /** Write-only: RGBA of the text laid out with rich text styles (text box size, transparent background); the Worker replaces the text drawn by the engine in the appearance (it only honors the first span's color). null keeps it. */ RichTextImage?: { version: number; width: number; height: number; pixels: ArrayBuffer; } | null; /** RGBA of custom drawing written as the appearance (Annotations.setCustomDrawHandler with generateAppearance): the Worker writes it as the annotation's /AP (image); null restores the engine-generated appearance. version changes every time. */ CustomAppearance?: { version: number; width: number; height: number; pixels: ArrayBuffer; } | null; /** Write-only: the file to attach to a file attachment annotation (type 17); sent with the diff only when version changes. After this batch of commands the Worker appends an incremental update that attaches /FS and reopens. */ Attachment?: { version: number; name: string; mimeType: string; bytes: ArrayBuffer; }; /** * Form widgets (type 20): WidgetType is the engine widget type (0 button, 1 check box, 2 radio, 3 text, 4 combo box, 5 list, 6 signature) and decides what to create; * FieldName is the field name (/T), FieldFlags the field flags (/Ff); FieldValue is the text / option value, or ExportValue when a check box / radio is checked and 'Off' when not; * FieldOptions are combo box / list options; a DateFormat value (including empty) marks a date field, and the format is read-only. */ WidgetType?: number; /** Widget rotation /MK /R (degrees; read from the file bytes, read-only). */ WidgetRotation?: number; FieldName?: string; FieldFlags?: number; /** Default value /DV (text string; text fields and combo boxes / lists) and tooltip /TU (all widgets). */ DefaultValue?: string; Tooltip?: string; /** Form field indicator, saved as /trn-form-field-indicator ('true' / 'false') and /trn-form-field-indicator-text. */ ShowIndicator?: boolean; IndicatorText?: string; FieldValue?: string; /** Selected values of a combo box / list (multiple for multi-select lists; an empty array means nothing selected). The engine only supports single selection; multiple selection and clearing are written to /V and /I on save. */ FieldValues?: string[]; ExportValue?: string; FieldOptions?: Array<{ value: string; displayValue: string; }>; DateFormat?: string; /** Maximum length /MaxLen of a text field (GetMaxLength; 0 = unlimited; read-only). Together with the Comb flag it decides a comb field. */ MaxLen?: number; /** Text alignment /Q of text fields / combo boxes / lists (0 left, 1 center, 2 right; Get/SetWidgetTextJustification). */ Quadding?: number; /** Button caption (Get/SetButtonTitle); for check boxes / radios, the ZapfDingbats character of the check style (6 kinds of Get/SetWidgetCheckStyle). */ Caption?: string; /** Custom data (Annotation.setCustomData), stored as JSON in a private key of the annotation dictionary. */ CustomData?: Record; /** Text stamp (SetTextStamp): two lines of text (the second is usually a date), shape 0 rectangle / 1 left arrow / 2 right arrow / 3 no border, color 0 white / 1 red / 2 green / 3 blue. */ TextStamp?: { text: string; date: string; shape: number; color: number; } | null; /** Read-only: engine stamp type GetStampType (0 unknown / 1 standard / 2 image / 3 text / 4 digital signature), given on read. */ StampType?: number; /** Read-only: the line ends have no /LE in the file (the engine reads None), given on read. */ LineEndsUnset?: [boolean, boolean]; /** Read-only: the sound annotation has audio data (HasSoundSource). */ HasSound?: boolean; /** * Write-only: audio to attach to a sound annotation (type 18) (the the engine drops on XFDF import); sent with the diff only when version changes. * bytes are the decoded , zlib-compressed when flate is true. After this batch of commands the Worker appends an incremental update that writes /Sound and reopens. */ Sound?: { version: number; rate: number; channels: number; bits: number; encoding: string; bytes: ArrayBuffer; flate: boolean; }; /** * Actions of links and widgets by trigger name ('U' is /A, others are /AA keys). On write, a link with a single URI uses SetLinkUri; * everything else is saved after the commands and written to /A and /AA by an appended incremental update, then reopened (worker/document/file-actions.ts). */ Actions?: Record; /** * Write-only: hand-drawn / image signature appearance of a signature field (RGBA, sent with the diff only when version changes); null removes it. Signature fields with a written appearance are no longer UpdateFormAp'd (it would overwrite it). */ SignatureAppearance?: { version: number; width: number; height: number; pixels: ArrayBuffer; } | null; /** Read-only: the signature field's appearance is a hand-drawn / image signature (written by SignatureAppearance). */ VisualSignature?: boolean; /** Read-only: the signature field already has a digital signature (IsSigned). */ Signed?: boolean; /** Read-only: the file uses dashes, cloudy borders, line ending styles, or it is a measurement annotation. Vector types (rectangles including cloudy, circles, lines, polylines, polygons, ink, etc.) ignore it and are always drawn on the main thread. */ UseAppearance?: boolean; } interface AnnotationData { id: AnnotId; pageId: PageId; type: number; version: number; props: AnnotationProps; } /** Import result: added or replaced annotations (with the Worker's new versions), and the ids deleted by commands. */ interface XfdfImportResult { data: AnnotationData[]; deleted: AnnotId[]; } /** * Layout parameters of a digital signature appearance (getSignature of the old core; the engine's UpdateApWithDigitalSigConfig): * content is the content lines (separated by newlines), text the typed name; logo / image are encoded images (PNG / JPEG); image is the drawn or uploaded signature. * When isContentAlignLeft is true the content is on the left half. With isDrawOnlyContent only the content is drawn, filling the whole box; with only image (no content, text or logo), image fills the box as the logo. */ interface DigitalSignaturePreviewOptions { width: number; height: number; content?: string; text?: string; isContentAlignLeft?: boolean; isDrawOnlyContent?: boolean; isDrawLogo?: boolean; logo?: ArrayBuffer; image?: ArrayBuffer; } /** Certificate summary: common subject and issuer attributes (CN, O, OU, C ...), serial number (hex), validity (millisecond timestamps). */ /** * Certificate summary and details (for the certificate viewer). Name attributes CN O OU C ST L E; serial number, key identifiers, public key and fingerprints are lowercase hex. * Extensions that cannot be read or are missing: empty arrays, null objects. */ interface CertificateData { der: ArrayBuffer; /** Subject name attributes (CN, O, OU, C, ...). */ subject: Record; /** Issuer name attributes (CN, O, OU, C, ...). */ issuer: Record; /** Serial number in lowercase hex. */ serialNumber: string; notBefore: number; notAfter: number; /** X.509 version (1–3). */ version: number; /** Algorithm the issuer used to sign this certificate: dotted OID and name (sha256WithRSAEncryption, ecdsa-with-SHA384, etc.; empty when unknown). */ signatureAlgorithm: { /** Dotted OID. */ oid: string; /** Algorithm name; empty when unknown. */ name: string; }; /** Public key: algorithm (RSA, EC, otherwise a dotted OID), bit size (RSA modulus, EC curve size), EC curve, public key value. */ publicKey: { /** Key algorithm: RSA, EC, or a dotted OID. */ algorithm: string; /** Key size in bits. */ bits: number; /** EC curve name. */ curve?: string; /** Public key value in lowercase hex. */ value: string; }; /** Key usage (RFC 5280 names: digitalSignature nonRepudiation keyEncipherment dataEncipherment keyAgreement keyCertSign cRLSign encipherOnly decipherOnly). */ keyUsage: string[]; /** Basic constraints: whether CA, path length. */ basicConstraints: { /** Whether the certificate is a CA. */ ca: boolean; /** Maximum path length, when set. */ pathLength?: number; } | null; /** Subject key identifier in lowercase hex; null when missing. */ subjectKeyIdentifier: string | null; /** Authority key identifier in lowercase hex; null when missing. */ authorityKeyIdentifier: string | null; /** Certificate policies (dotted OIDs). */ certificatePolicies: string[]; /** CRL distribution points (URIs). */ crlDistributionPoints: string[]; /** Authority information access: method (OCSP, caIssuers, otherwise a dotted OID) and location. */ authorityInfoAccess: Array<{ /** Access method: OCSP, caIssuers, or a dotted OID. */ method: string; /** Access location. */ location: string; }>; /** Fingerprints of the certificate DER. */ sha1: string; /** MD5 fingerprint in lowercase hex. */ md5: string; } /** A change after signing: object number, kind, whether allowed. */ /** An object changed after signing: kind, whether allowed; form changes carry the full field name. */ interface SignatureChangeData { objectNumber: number; kind: 'signature' | 'form' | 'annotation' | 'page' | 'page_content' | 'pages' | 'catalog' | 'other'; allowed: boolean; fieldName?: string; } /** * Verification result of one signature: * digest: the signed content and signature value; document: ByteRange and the structure of the signature container; trust: whether the certificate chain reaches a trusted certificate and is within its validity period; * permissions: whether changes after signing are allowed (DocMDP certification signatures tighten them by P). */ interface SignatureVerificationData { /** Full name of the signature field. */ fieldName: string; /** Page index (0-based); -1 when not found. */ pageIndex: number; /** Overall result: true when the signature is valid. */ verificationStatus: boolean; /** Result of checking the signed content against the signature value. */ digestStatus: 'digest_verified' | 'weak_digest_algorithm_but_digest_verifiable' | 'digest_invalid' | 'unsupported_encoding' | 'no_digest_status'; /** Result of checking the ByteRange and the signature container structure. */ documentStatus: 'no_error' | 'unsigned' | 'bad_byteranges' | 'corrupt_cryptographic_contents'; /** Whether the certificate chain reaches a trusted certificate and is within its validity period. */ trustStatus: 'trust_verified' | 'untrusted' | 'no_trust_status'; /** Reasons the chain is not trusted; empty when trusted. */ trustProblems: Array<'no_trusted_root' | 'incomplete_chain' | 'expired' | 'not_yet_valid' | 'revoked'>; /** Whether changes made after signing are allowed. */ permissionsStatus: 'unmodified' | 'has_allowed_changes' | 'invalidated_by_disallowed_changes' | 'no_permissions_status'; /** Objects changed after signing. */ changes: SignatureChangeData[]; /** DocMDP P (1 no changes, 2 form filling and signing, 3 also annotations); 0 for ordinary (approval) signatures. */ docMDPPermissions: 0 | 1 | 2 | 3; /** Signature encoding (/SubFilter), such as a detached PKCS#7 signature. */ subFilter: string; /** Digest algorithm name; null when unknown. */ digestAlgorithm: string | null; /** Name of the signer. */ signerName: string; signingTime: number | null; /** Where signingTime came from: a timestamp token, a signed attribute or the signature dictionary; null when there is no signing time. */ signingTimeSource: 'timestamp' | 'signed_attribute' | 'signature_dictionary' | null; timestamp: { time: number; valid: boolean; } | null; /** Reason for signing; empty when not given. */ reason: string; /** Signing location; empty when not given. */ location: string; /** Signer contact information; empty when not given. */ contactInfo: string; signer: CertificateData | null; certificateChain: CertificateData[]; /** The signature's ByteRange (offset and length of the two signed parts); null when missing. */ byteRange: [number, number, number, number] | null; /** The signature covers up to the end of the file (no revisions appended afterwards). */ coversWholeDocument: boolean; /** * Offline revocation check (OCSP responses and CRLs in the document DSS): the result for each certificate in the chain except the root; * revoked if any is revoked, good if all are valid, unknown if some cannot be checked, not_checked when there is no data or checking is off. */ revocation: { status: 'good' | 'revoked' | 'unknown' | 'not_checked'; certificates: Array<{ subject: string; status: 'good' | 'revoked' | 'unknown'; source?: 'ocsp' | 'crl'; revokedAt?: number; }>; }; } /** Action: type is ActionType (1 GoTo, 2 GoToR, 6 URI, 9 Hide, 10 Named, 11 SubmitForm, 12 ResetForm, 14 JavaScript...); dest is in page coordinates (top-left origin). */ interface ActionData { type: number; dest?: { pageId: PageId; /** Destination type (read from the file by the Worker; XYZ when missing). */ fit?: string; left?: number; top?: number; zoom?: number; }; uri?: string; name?: string; /** Target fields of Hide; fields of ResetForm / SubmitForm. */ fields?: string[]; hide?: boolean; /** ResetForm: fields are the ones not to reset. */ exclude?: boolean; /** JavaScript script. */ javascript?: string; /** SubmitForm address and /Flags. */ url?: string; flags?: number; /** GoToR: target file name, open in a new window (undefined when not written). */ filename?: string; newWindow?: boolean; /** GoToR position in the target file: page numbers start at 1; coordinates are the raw PDF coordinates of that file (its page height is unknown, so they are not flipped). */ remoteDest?: { page: number; fit: string; left?: number; top?: number; zoom?: number; }; } interface BookmarkData { title: string; action?: ActionData; children: BookmarkData[]; objNum?: number; color?: [number, number, number]; /** /S of /A in the file (GoTo when only /Dest; an empty string when no action); missing when the file info cannot be read. */ actionType?: string; /** Raw value of the engine's GetOutlineDestination [PosX, PosY] (PDF coordinates, -1 when the dimension is missing); present even when the target page does not exist. */ destPosition?: [number, number]; } /** Content editing box: text or image (object); the rectangle is in unrotated page space. */ interface ContentBoxData { id: string; pageId: PageId; kind: 'text' | 'object'; rect: [number, number, number, number]; /** Authoritative text snapshot for synchronous public selection reads. */ text?: string; } /** * Result of a content editing operation: all boxes of the page afterwards and the native undo state; value is the result of a read operation, steps is how many native undo steps this added, * changed means the page content changed (live drags that are not recorded for undo count too). */ interface ContentEditResult { boxes: ContentBoxData[]; canUndo: boolean; canRedo: boolean; value?: unknown; steps?: number; changed?: boolean; /** Box changed by undo / redo (index into boxes). */ touched?: number; } interface OptimizeDefaultsData { flags: number; imageQuality: number; ppi: { color: [upper: number, target: number]; gray: [upper: number, target: number]; mono: [upper: number, target: number]; }; } /** * Normalizes document sources: URL / Blob / File / ArrayBuffer / Uint8Array / Base64 / data URL all become one ArrayBuffer; * whether it is a PDF is decided by the file content, and the file name is determined. Linearized / Range downloads are deferred. */ /** A document given as Base64 text. */ interface Base64Source { /** Source kind marker, always 'base64'. */ type: 'base64'; /** Raw Base64 or a data URL with a `;base64,` payload. */ data: string; } /** Anything a document can be loaded from: a URL (string or URL object), raw bytes, a Blob or File, or Base64 text. */ type DocumentSource = string | URL | ArrayBuffer | Uint8Array | Blob | File | Base64Source; /** A document source after it has been read into memory. */ interface ResolvedSource { /** The file content. */ bytes: ArrayBuffer; /** Including the extension; '' when the source does not provide one. */ filename: string; } /** Download progress: loaded is the bytes received; total is 0 when unknown or the response is compressed; reported once more as (loaded, loaded) on completion. */ type DownloadProgress = (loaded: number, total: number) => void; /** Only files with these extensions can be opened (stored lowercase); an empty array means no limit. */ declare function setAllowedFileExtensions(extensions: string[]): void; /** * Returns the extensions set by setAllowedFileExtensions. * @returns Lowercase extensions without the dot; an empty array means any extension is allowed. */ declare function getAllowedFileExtensions(): string[]; /** * AppearanceManager: appearance bitmap cache, a Core-level singleton (Core.getAppearanceManager()). * The engine's RenderAnnot only produces bitmaps, cannot be sliced and has no clip, so it needs levels + a budget + a state machine. * Its Worker counterpart is AppearanceRenderer (calls RenderAnnot); this class never talks to the Worker directly, the render function is given by the caller. */ interface AppearanceKey { docId: string; pageNumber: number; annotId: string; /** Internal annotation version; invalidated whenever a property changes. */ contentVersion: number; /** Bitmap resolution level (level of zoom × dpr). */ zoomBucket: number; } type AppearanceState = 'ready' | 'oversize'; /** A bitmap that can be passed to drawImage: a canvas (browser / OffscreenCanvas). */ type AppearanceBitmap = CanvasImageSource & { width: number; height: number; }; interface AppearanceEntry { key: AppearanceKey; state: AppearanceState; bitmap?: AppearanceBitmap; bytes: number; } /** Worker render result (RGBA). */ interface AppearancePixels { width: number; height: number; pixels: ArrayBuffer; } /** Least-recently-used cache of annotation appearance bitmaps, limited by a memory budget. */ declare class AppearanceManager { /** Map keeps insertion order: the first entry is the least recently used. */ private readonly entries; private readonly loading; private used; private readonly budget; /** Document generation: incremented by clearData; if the generation at load completion differs from the start, the document was unloaded and the bitmap is not cached. '' is the generation of a full clearData(). */ private readonly generation; private generationOf; /** * Creates the cache. * @param options Cache options. * @param options.budgetBytes Memory budget in bytes. Defaults to 64 MB. */ constructor(options?: { budgetBytes?: number; }); /** Synchronous cache lookup; returns undefined on a miss without starting a request; a hit becomes most recently used. */ peek(key: AppearanceKey): AppearanceEntry | undefined; /** Asynchronous request; renders only once per key at a time; larger than 4096² is recorded as oversize without rendering. */ request(key: AppearanceKey, size: { /** Bitmap width in pixels. */ width: number; /** Bitmap height in pixels. */ height: number; }, load: (width: number, height: number) => Promise): Promise; /** The latest-version bitmap of this annotation (any zoom level), standing in while a new version loads; undefined when none. */ latest(docId: string, annotId: string): AppearanceEntry | undefined; /** Invalidates this annotation's bitmaps older than beforeVersion; without a version, invalidates all. */ invalidate(docId: string, annotId: string, beforeVersion?: number): void; /** * Drops the cached bitmaps of every annotation on a page. * @param docId Document id. * @param pageNumber Page number (1-based). */ releasePage(docId: string, pageNumber: number): void; /** Clears the bitmaps of one document; clears everything when none is given. */ clearData(docId?: string): void; /** Whether this type (elementName) needs an appearance bitmap (rectangles / lines / polygons and the like are drawn by the main thread). */ needsBitmap(annotType: string): boolean; private drop; private remove; private evict; } /** * Sets the folder that the Worker script and wasm file are loaded from. Clears the cached Worker script and compiled module. * @param path Folder URL or path. */ declare function setWorkerPath$1(path: string): void; /** * Returns the folder that the Worker script and wasm file are loaded from. * @returns The path set by setWorkerPath, or the default. */ declare function getWorkerPath$1(): string; /** * Returns the SDK version. * @returns The version string. */ declare function getVersion(): string; /** Build identifier (Base64 of the version number). */ declare function getBuild(): string; /** Turns warning logs off / on (only warnings; errors are always printed). */ declare function disableLogs(disable?: boolean): void; /** * Third configuration channel for iframes; only reads location and never touches the DOM. * Splits on & and the first =, then decodeURIComponent: '+' is kept as is (URLSearchParams cannot be used because it turns '+' into a space and corrupts base64 licenses). * When the default is a boolean, 'true' / '1' / 'false' / '0' become booleans. */ declare function getHashParameter(name: string, defaultValue?: T): string | T; /** Turned off when the page CSP does not allow blob: Workers (worker-src); Workers are then created from the URL (each Worker requests the script once). */ declare function disableObjectURLBlobs(disable: boolean): void; /** * Returns whether Workers are created from a Blob URL of the worker script. * @returns false after disableObjectURLBlobs(true); true by default. */ declare function areObjectURLBlobsEnabled(): boolean; /** * Sets custom fonts: * - A font file (TTF / OTF / TTC): fallback font used for appearances and rendering of glyphs missing from the standard 14 fonts (such as CJK text). * - A directory ending with /: reads `${url}fonts.json` ([{ family, filePath }]) and passes the whole font group to the engine. An annotation font is selected only when its name is the font's PostScript name * (the fonts.json family should match it and must not contain spaces); names the engine does not know use the first font of the group. The UI layer builds the font dropdown from fonts.json. * One of each kind is kept (a later one of the same kind replaces the earlier). Downloaded once on the main thread and passed to the main Worker and every render pool Worker; sent immediately when the Worker is already running (preloadPDFWorker waits for it to load). * Passing null stops giving either kind to Workers created afterwards; already loaded fonts are kept. */ declare function setCustomFontURL(url: string | null): void; /** * Starts the Worker and wasm early; idempotent. With licenseKey, also initializes the license (it can also be passed as l / licenseKey to loadDocument). * After a failure the next call retries. */ declare function preloadPDFWorker(options?: { /** License key to initialize together with the Worker. */ licenseKey?: string; }): Promise; /** PostScript names of the font group loaded by the engine; null when there is no font group. No document needs to be open. */ declare function getWebFontNameList(): Promise; /** Terminates the Worker and releases the wasm heap; pending requests end with CANCELLED. preloadPDFWorker recreates it afterwards. */ declare function resetWorker(): void; /** Headless use: gets a Document directly without a viewer (LoadDocumentByStream). */ declare function createDocument(src: DocumentSource, options?: LoadDocumentOptions): Promise; /** = time_slice_ms of InitProgressiveRenderWithMatrix. */ declare function setProgressiveTime(ms: number): void; /** Bitmap dpr multiplier; defaults to devicePixelRatio. */ declare function setCanvasMultiplier(multiplier: number): void; /** Removes the multiplier set by setCanvasMultiplier and follows devicePixelRatio again. */ declare function unsetCanvasMultiplier(): void; /** * Returns the multiplier applied to page bitmaps. * @returns The value set by setCanvasMultiplier, or devicePixelRatio when none is set. */ declare function getCanvasMultiplier(): number; /** Page bitmap budget level → CanvasManager. */ /** Page bitmap budget level 0–3 → CanvasManager 32 / 64 / 128 / 256 MB. */ declare function setCachingLevel(level: number): void; /** Prefetch window → range of neighboring page pre-rendering and page text prefetch. */ declare function setPreRenderLevel(level: number): void; /** Page bitmap cache, a Core-level singleton. */ declare function getCanvasManager(): CanvasManager; /** Appearance bitmap cache, a Core-level singleton. */ declare function getAppearanceManager(): AppearanceManager; /** Exposed as Core.Actions.GoTo.Dest. Maps to the engine's GetDestination / SetDestination(page_index, x, y, zoom). */ type DestFit = 'XYZ' | 'Fit' | 'FitH' | 'FitV' | 'FitR' | 'FitB' | 'FitBH' | 'FitBV'; interface DestInit { page?: number; fit?: DestFit; left?: number; top?: number; zoom?: number; } declare class Dest { page: number; fit: DestFit; left: number | null; top: number | null; zoom: number | null; constructor(init?: DestInit); set(init?: DestInit): void; } type EventMap = { [K in keyof E]: unknown[]; }; /** Base class for objects that fire named events. Listener arguments are passed by position. */ declare class EventHandler = Record> { /** Event name → (function passed by the caller → function actually run); they differ for once, and removal by the original function still works. */ private readonly listeners; /** * Adds a listener for an event. Adding the same function twice for one event has no effect. * @param name Event name. * @param fn Listener, called with the event arguments. * @param options Listener options. * @param options.once When true, the listener is removed after it runs once. */ addEventListener(name: K, fn: (...args: E[K]) => void, options?: { once?: boolean; }): void; /** * Removes a listener, or every listener of the event when `fn` is omitted. * @param name Event name. * @param fn The function that was passed to addEventListener. */ removeEventListener(name: K, fn?: (...args: E[K]) => void): void; /** Removes every listener of every event. */ removeAllEventListeners(): void; /** A listener that throws does not affect the others; the error is reported through logger.error. */ trigger(name: K, args?: E[K]): void; /** Like trigger, but awaits the Promise returned by each listener in turn; a failing listener does not affect the others. */ triggerAsync(name: K, args?: E[K]): Promise; } /** Internal base class; not exported from Core.Actions. */ declare class Action { elementName: string; /** Executes the action. Unsupported types only log a warning. */ onTriggered(_target: Annotation$1 | null, _event: Event | null, _viewer: DocumentViewer): void; } /** An outline (bookmark) item of the document. Positions are in unrotated page coordinates (top-left origin, PDF points). */ declare class Bookmark { readonly data: BookmarkData; readonly parent: Bookmark | null; private readonly index; private children; private pageNumber; /** * Creates a bookmark; bookmarks are normally obtained from Document.getBookmarks. * @param data Outline data read by the Worker. * @param parent Parent bookmark, or null for a top-level item. * @param index Index among sibling bookmarks (0-based). */ constructor(data: BookmarkData, parent?: Bookmark | null, index?: number); /** * Returns the title. * @returns The bookmark title. */ getName(): string; /** * Returns the child bookmarks. * @returns A new array of the children, in order. */ getChildren(): Bookmark[]; /** * Returns the parent bookmark. * @returns The parent, or null for a top-level item. */ getParent(): Bookmark | null; /** Index among sibling bookmarks (0-based) */ getIndex(): number; /** Target page (1-based); 0 without an in-document target (such as a link) */ getPageNumber(): number; /** Address of a link bookmark; an empty string for others */ getURL(): string; /** Action of the target: GoTo for in-document targets, URI for links */ getActions(): Action[]; /** x of the target position (page coordinates, pt) */ getHorizontalPosition(): number; /** y of the target position (page coordinates, top-left origin, pt) */ getVerticalPosition(): number; /** Has an in-document target or a link address */ isValid(): boolean; /** Color of the outline item (/C, 0–1); undefined when missing or black (all 0) */ getColor(): { /** Red, 0 to 1. */ r: number; /** Green, 0 to 1. */ g: number; /** Blue, 0 to 1. */ b: number; } | undefined; /** Object number of the outline item in the file (undefined when it cannot be read for encrypted documents) */ getObjNum(): number | undefined; /** * Action type: /S of /A in the file (GoTo, GoToR, Launch, Named, URI, JavaScript and so on, as is); GoTo for items with only /Dest (including named destinations); * an empty string without an action. When the file info cannot be read, by the engine type: GoTo for in-document targets, URI for links, an empty string otherwise (the engine reports all other actions as none) */ getActionType(): string; /** * The target position read by the engine, in PDF coordinates (bottom-left origin, not converted); given even when the target page no longer exists. * null without an in-document target; a dimension is null when missing (/Fit and similar types, or null) */ getDestinationPosition(): { /** Horizontal position in PDF coordinates; null when missing. */ x: number | null; /** Vertical position in PDF coordinates; null when missing. */ y: number | null; } | null; } interface PageHistoryManagerEvents { undoRedoStatusChanged: [status: { canUndo: boolean; canRedo: boolean; }]; } /** Undo and redo history of page operations (insert, delete, move, rotate, merge). Obtain it with `document.getPageHistoryManager()`. */ declare class PageHistoryManager extends EventHandler { private undoStack; private redoStack; private readonly aliases; /** undo / redo run one after another (each step waits for the Worker to finish the page table) */ private queue; /** * Checks whether there is a step to undo. * @returns true when undo is available. */ canUndo(): boolean; /** * Checks whether there is a step to redo. * @returns true when redo is available. */ canRedo(): boolean; /** Undoes the latest step; does nothing when there is nothing to undo. On error the page state is uncertain, so history is cleared and the error thrown */ undo(): Promise; /** Redoes the latest undone step; does nothing when there is none. On error the history is cleared and the error is thrown. */ redo(): Promise; /** Removes all steps. Fires undoRedoStatusChanged when availability changes. */ clear(): void; private run; private status; private notify; } /** * Core.PageInfo: a page's size, matrix, rotation, id and page number; setFromPageData fills it from page data, clone makes a copy. * Document.getPageInfo returns a plain object with only width / height; this class is for assembling page info yourself */ interface PageInfoData { width: number; height: number; matrix?: unknown; rotation?: number; id?: string; pageNum?: number | string; } /** Size, matrix, rotation, id and number of a page, for assembling page information yourself. */ declare class PageInfo$1 { width: number; height: number; /** Page text; null when not set. */ text: string | null; /** Links on the page; empty by default. */ links: unknown[]; /** Page matrix; null when not set. */ matrix: unknown; /** Page rotation. Defaults to 0. */ rotation: number; /** Page id. */ id?: string; /** Page number. */ pageNum?: number | string; /** * Creates page information. * @param width Page width in PDF points. * @param height Page height in PDF points. */ constructor(width: number, height: number); /** * Replaces size, matrix, rotation, id and page number with the given data. Missing matrix becomes null and missing rotation 0. * @param data The page data. */ setFromPageData(data: PageInfoData): void; /** * Copies the page information. * @returns A new object with the same values; `links` is shared. */ clone(): PageInfo$1; } /** * Core.Document: the main thread side holds only metadata, page geometry and the pageNumber ↔ PageId table; * the content and authoritative objects are in the Worker-side Document of the same name. Page structure changes, password permissions, optimized saving and overlay comparison all live here. */ /** Save flags for getFileData. */ declare enum SaveOptions { /** Appends changes to the end of the original file instead of rewriting it. */ INCREMENTAL = 1 } /** Page rotation in steps of 90 degrees clockwise. */ declare enum PageRotation { /** No rotation. */ E_0 = 0, /** 90 degrees clockwise. */ E_90 = 1, /** 180 degrees. */ E_180 = 2, /** 270 degrees clockwise. */ E_270 = 3 } /** Text extraction processing options (setTextExtractorProcessingFlags; a plain object without reverse mapping) */ declare const TextExtractorProcessingFlags: { /** Do not expand ligatures. */ readonly NO_LIGATURE_EXP: 1; /** Do not remove duplicated text. */ readonly NO_DUP_REMOVE: 2; /** Break words at punctuation. */ readonly PUNCT_BREAK: 4; /** Remove hidden text. */ readonly REMOVE_HIDDEN_TEXT: 8; /** Ignore invisible text. */ readonly NO_INVISIBLE_TEXT: 16; /** Ignore watermark text. */ readonly NO_WATERMARKS: 128; /** Extract text in drawing order. */ readonly EXTRACT_USING_ZORDER: 256; }; type TextExtractorProcessingFlags = typeof TextExtractorProcessingFlags[keyof typeof TextExtractorProcessingFlags]; /** Overprint preview (setOverprintPreviewMode) */ declare const OverprintPreviewMode: { /** Overprint preview off. */ readonly OFF: 0; /** Overprint preview on. */ readonly ON: 1; /** Overprint preview on for PDF/X documents only. */ readonly PDFX_ON: 2; }; type OverprintPreviewMode = typeof OverprintPreviewMode[keyof typeof OverprintPreviewMode]; /** Writing direction of page text. */ declare enum TextDirection { /** Direction not determined. */ Unprocessed = "unprocessed", /** Left to right. */ LeftToRight = "ltr", /** Right to left. */ RightToLeft = "rtl" } /** Events fired by Document, with their listener arguments. */ interface DocumentEvents { /** The page table has been fully read. */ documentComplete: []; /** * The page structure changed (added, removed, moved, rotated, cropped); page numbers are after the change, removed ones before it * @example * ```js * const { documentViewer } = instance.Core; * documentViewer.getDocument().addEventListener('pagesUpdated', (changes) => { * console.log('Added', changes.added, 'removed', changes.removed, 'moved', changes.moved); * }); * ``` */ pagesUpdated: [changes: PageChanges]; /** PageId ↔ pageNumber mapping updated after the page order changed: old page number → new page number, only pages whose number changed */ changePageIds: [map: Record]; /** The layer tree or layer visibility changed. */ layersUpdated: []; /** enableColorSeparations found a new ink */ colorSeparationAdded: [separation: ColorSeparation]; /** Bookmark page numbers may have changed because pages were added, removed or moved. */ bookmarksUpdated: []; } interface PageInfo { width: number; height: number; } /** One page structure change: added are new pages (new numbers), removed are deleted pages (old numbers), moved maps old → new numbers, rotationChanged / contentChanged are rotated / cropped pages (new numbers) */ interface PageChanges { /** Page numbers of added pages, after the change. */ added: number[]; /** Page numbers of removed pages, before the change. */ removed: number[]; /** Old page number to new page number for moved pages. */ moved: Record; /** Page numbers of rotated pages, after the change. */ rotationChanged: number[]; /** Page numbers of pages whose content or crop box changed, after the change. */ contentChanged: number[]; /** refreshAll fires 'refresh' (pages are only redrawn, the structure did not change) */ source?: 'refresh'; } /** Document information dictionary entries. Only non-empty entries are present. */ interface Metadata { /** Document title. */ title?: string; /** Author. */ author?: string; /** Subject. */ subject?: string; /** Keywords. */ keywords?: string; /** Application that created the original document. */ creator?: string; /** Application that produced the PDF. */ producer?: string; /** Creation date, as stored in the file. */ creationDate?: string; /** Last modification date, as stored in the file. */ modDate?: string; } /** Document optimization (OptimizeDocumentByStream / SetOptimizeOptionPPI) */ /** Optimized saving (OptimizeDocumentByStream) */ interface OptimizeOptions { /** Image recompression quality 0–1 (0.4 by default) */ imageQuality?: number; /** Font subsetting (true by default) */ fontSubset?: boolean; /** * Combination of OptimizeFlag bits (pso/optimize/flags.h); by default only lossless cleanup: removing unused / empty objects, invalid links and bookmarks, compressing images, * Flate for uncompressed streams, LZW to Flate, optimizing page content (the engine's own default also removes embedded fonts and bookmarks, not used here) */ flags?: number; /** Image resolution limits as [upper, target] pixels per inch: images above `upper` are downsampled to `target`. Defaults: color and gray [225, 150], mono [450, 300]. */ ppi?: { /** Limits for color images. */ color?: [upper: number, target: number]; /** Limits for grayscale images. */ gray?: [upper: number, target: number]; /** Limits for monochrome images. */ mono?: [upper: number, target: number]; }; } /** The engine's current optimization defaults, which can be passed directly to getFileData({ optimize }). */ type OptimizeDefaults = OptimizeDefaultsData; /** Options for getFileData. Options run on a copy, leaving the open document unchanged. */ interface GetFileDataOptions { /** XFDF whose annotations replace the annotations in the saved file. */ xfdfString?: string; /** Burns annotations, including form fields, into page content. */ flatten?: boolean; /** When false, the saved file contains no annotations. */ includeAnnotations?: boolean; /** Output format; only 'pdf' is supported. */ downloadType?: 'pdf'; /** Save flags, such as SaveOptions.INCREMENTAL. */ flags?: SaveOptions; /** Takes the optimized saving path */ optimize?: OptimizeOptions; } /** Options for loadCanvas. */ interface LoadCanvasOptions { /** Page number (1-based). */ pageNumber: number; /** Zoom level; 1 renders at 72 pixels per inch before the multiplier. */ zoom?: number; /** View rotation on top of the page's own /Rotate */ pageRotation?: PageRotation; /** Renders only this region: display-orientation page space (top-left origin, pt) */ renderRect?: { /** Left edge. */ x1: number; /** Top edge. */ y1: number; /** Right edge. */ x2: number; /** Bottom edge. */ y2: number; }; /** Bitmap multiplier, Core.getCanvasMultiplier() by default */ multiplier?: number; /** With width and / or height, scales proportionally to fit within this box (CSS px, then times multiplier), overriding zoom (for thumbnails). With only one, scales by that side only */ width?: number; /** Height of the box to fit in, in CSS pixels; see `width`. */ height?: number; /** Draws annotations and form widgets (by their appearance in the PDF, as loadThumbnail); false by default, page bitmaps do not include annotations (the viewer's annotation layer draws them). For copy documents without a viewer that need to show annotations */ renderAnnotations?: boolean; /** Called with the rendered canvas and the page number. */ drawComplete: (canvas: HTMLCanvasElement, pageNumber: number) => void; /** Layer usage: 'print' chooses layers by their print usage (always / never / only when visible), for printing; by the current display by default */ layerUsage?: 'view' | 'print'; } /** A color (ink) of separations: the four CMYK colors first, then spot colors; those with enabled false are not drawn */ interface ColorSeparation { /** Ink name, such as 'Cyan' or a spot color name. */ name: string; /** Display color; the engine gives 0,0,0 for spot colors */ rgb: [number, number, number]; /** Whether the ink is drawn. */ enabled: boolean; /** Only with checkIfBaseColorsUsed: whether it is one of the four CMYK colors */ isBaseColor?: boolean; /** Only with checkIfBaseColorsUsed: whether the four CMYK colors are used in the document; null for non-CMYK colors */ isBaseColorUsedInDocument?: boolean | null; } /** The six header / footer positions (numbered 0–5 by the engine in this order) */ type HeaderFooterPosition = 'topLeft' | 'topCenter' | 'topRight' | 'bottomLeft' | 'bottomCenter' | 'bottomRight'; /** Header / footer / Bates: text at each position (a string, or with font, size and color '#rrggbb'); margin in pt (36 by default); pages are page numbers (all by default) */ interface HeaderFooterOptions { /** Text at each position: a string, or an object with the text and its font name, size and color ('#rrggbb'). */ texts: Partial>; /** Margins in PDF points. Default 36 on each side. */ margins?: { /** Top margin. */ top?: number; /** Bottom margin. */ bottom?: number; /** Left margin. */ left?: number; /** Right margin. */ right?: number; }; /** Page numbers (1-based) to apply to; all pages by default. */ pages?: number[]; } /** Background: either color ('#rrggbb') or image (RGBA pixels, ImageData works); rotation in degrees, offset in pt; pages are page numbers (all by default) */ interface BackgroundOptions { /** Background color '#rrggbb'. Give either this or `image`. */ color?: string; /** Background image as RGBA pixels (an ImageData works). Give either this or `color`. */ image?: { /** Image width in pixels. */ width: number; /** Image height in pixels. */ height: number; /** RGBA pixel data, 4 bytes per pixel. */ data: ArrayLike; }; /** Opacity from 0 to 1. Defaults to 1. */ opacity?: number; /** Scale factor. Defaults to 1. */ scale?: number; /** Rotation in degrees. Defaults to 0. */ rotation?: number; /** Horizontal alignment on the page. Defaults to 'center'. */ horizontalAlign?: 'left' | 'center' | 'right'; /** Vertical alignment on the page. Defaults to 'center'. */ verticalAlign?: 'top' | 'center' | 'bottom'; /** Horizontal offset in PDF points. Defaults to 0. */ horizontalOffset?: number; /** Vertical offset in PDF points. Defaults to 0. */ verticalOffset?: number; /** Page numbers (1-based) to apply to; all pages by default. */ pages?: number[]; /** Whether the background is shown on screen. Defaults to true. */ view?: boolean; /** Whether the background is printed. Defaults to true. */ print?: boolean; } /** * Watermark written to the file: either text or image (RGBA pixels, ImageData works); color '#rrggbb' (gray by default), opacity 0–1 (0.5 by default), * rotation in degrees (45 by default); front true by default (over the content); with tiling, tiled over the whole page; pages are page numbers (all by default) */ interface DocumentWatermarkOptions { /** Watermark text. Give either this or `image`. */ text?: string; /** Watermark image as RGBA pixels (an ImageData works). Give either this or `text`. */ image?: { /** Image width in pixels. */ width: number; /** Image height in pixels. */ height: number; /** RGBA pixel data, 4 bytes per pixel. */ data: ArrayLike; }; /** Font name. Defaults to 'Helvetica'. */ fontName?: string; /** Font size in points. Defaults to 48. */ fontSize?: number; /** Text color '#rrggbb'. Defaults to gray '#808080'. */ color?: string; /** Opacity from 0 to 1. Defaults to 0.5. */ opacity?: number; /** Rotation in degrees. Defaults to 45. */ rotation?: number; /** Scale factor. Defaults to 1. */ scale?: number; /** Horizontal alignment on the page. Defaults to 'center'. */ horizontalAlign?: 'left' | 'center' | 'right'; /** Vertical alignment on the page. Defaults to 'center'. */ verticalAlign?: 'top' | 'center' | 'bottom'; /** Horizontal offset in PDF points. Defaults to 0. */ horizontalOffset?: number; /** Vertical offset in PDF points. Defaults to 0. */ verticalOffset?: number; /** Page numbers (1-based) to apply to; all pages by default. */ pages?: number[]; /** Whether the watermark is drawn over the page content. Defaults to true. */ front?: boolean; /** Tiles the watermark over the whole page with this spacing in PDF points. */ tiling?: { /** Horizontal space between tiles. */ horizontalSpacing: number; /** Vertical space between tiles. */ verticalSpacing: number; }; } /** Document attachment (embedded file) */ interface FileAttachment { /** Index (0-based) among the attachments. */ index: number; /** File name. */ name: string; /** Description; empty when none. */ description: string; /** MIME type; empty when unknown. */ mimeType: string; /** Size in bytes. */ size: number; } /** Standards that can be converted to */ type StandardType = 'PDF/A-1a' | 'PDF/A-1b' | 'PDF/A-2a' | 'PDF/A-2b' | 'PDF/A-2u' | 'PDF/A-3a' | 'PDF/A-3b' | 'PDF/A-3u' | 'PDF/UA-1'; /** In-flight renders merged by key: several loadCanvas calls wait on the same Worker render, each drawImage onto its own canvas */ type LayerUsage = 'always' | 'never' | 'visible'; /** Layer (OCG), corresponding to getLayerTree / setLayerNodeDict */ interface Layer { /** Layer name, or the text of a label row. */ name: string; /** Label rows (string labels in /Order, text only) have no visible or obj (labels are recognized by having neither) */ visible?: boolean; /** Whether the layer is locked, meaning users should not change its visibility. */ locked?: boolean; /** Child layers. */ children?: Layer[]; /** Default visibility in the file (visible is the current display state, changing it does not write the file) */ defaultVisible?: boolean; /** Print / export usage: always / never / only when visible (written to the file when changed) */ printState?: LayerUsage; /** Export usage: always, never, or only when visible (written to the file when changed). */ exportState?: LayerUsage; /** Unique identifier of the layer in the file; not set when the entry is only a label. */ obj?: string; /** Child layers are a radio group (/RBGroups in the file): only one can be on */ RBGroup?: boolean; } /** Permission bits (input of setPassword / setPermissions, result of getPermissions) */ interface DocumentPermissions { /** Printing is allowed. */ printing: boolean; /** High-quality printing is allowed. */ highQualityPrinting: boolean; /** Copying text and graphics is allowed. */ copying: boolean; /** Changing the document is allowed. */ documentChanges: boolean; /** Inserting, deleting and rotating pages is allowed. */ documentAssembly: boolean; /** Adding and changing annotations is allowed. */ commenting: boolean; /** Filling in form fields is allowed. */ formFilling: boolean; } interface CompareContentOptions { /** Compare text, true by default */ compareText?: boolean; /** Compare images, true by default; when neither text nor images are compared, only annotations are */ compareImages?: boolean; /** Colors of the three kinds of differences ('#rrggbb'); by default replace #93B9FD, insert #C0FFEC, delete #FBBDBF */ colors?: { replace?: string; insert?: string; delete?: string; }; /** Opacity of difference annotations 0–1, 0.5 by default */ opacity?: number; } /** * A set of 1-based page numbers. Each item is a page number or a range string such as `'3-5'`; * a single string such as `'1,3-5'` lists several items separated by commas. */ type PageList = ReadonlyArray | string; /** Options of {@link Document.extractPages}. */ interface ExtractPagesOptions { /** When true, each page is saved as a separate PDF and an array with one file per page (in page order) is returned. */ separateFile?: boolean; } declare const BLEND_MODE: Readonly<{ /** The top drawing covers the bottom one. */ readonly NORMAL: "normal"; /** Multiplies the colors. */ readonly MULTIPLY: "multiply"; /** Screens the colors. */ readonly SCREEN: "screen"; /** Overlays the colors. */ readonly OVERLAY: "overlay"; /** Keeps the darker color. */ readonly DARKEN: "darken"; /** Keeps the lighter color. */ readonly LIGHTEN: "lighten"; /** Color dodge. */ readonly COLOR_DODGE: "colorDodge"; /** Color burn. */ readonly COLOR_BURN: "colorBurn"; /** Hard light. */ readonly HARD_LIGHT: "hardLight"; /** Soft light. */ readonly SOFT_LIGHT: "softLight"; /** Difference of the colors. */ readonly DIFFERENCE: "difference"; /** Exclusion. */ readonly EXCLUSION: "exclusion"; /** Hue of the top color with saturation and luminosity of the bottom. */ readonly HUE: "hue"; /** Saturation of the top color with hue and luminosity of the bottom. */ readonly SATURATION: "saturation"; /** Hue and saturation of the top color with luminosity of the bottom. */ readonly COLOR: "color"; /** Luminosity of the top color with hue and saturation of the bottom. */ readonly LUMINOSITY: "luminosity"; }>; /** How the two drawings mix where they overlap in {@link Document.compareDrawings} (values of `Document.BlendMode`). */ type BlendMode = typeof BLEND_MODE[keyof typeof BLEND_MODE]; interface CompareContentResult { /** Copy of this one, with difference annotations */ base: Document; /** Copy of the other one, with difference annotations */ other: Document; /** Combined report: a PDF with both side by side */ merged: Document; } interface CompareDrawingsOptions { /** Pages to compare, such as '1-3,5'; all by default */ pageRange?: string; otherPageRange?: string; /** Colors of both ('#rrggbb'); red for this one and blue for the other by default */ colors?: { base: string; other: string; }; /** 0–1; baseAlpha / otherAlpha take precedence when given */ fillAlpha?: number; strokeAlpha?: number; /** Opacity 0–1 of this / the other one (replacing the shared fillAlpha / strokeAlpha) */ baseAlpha?: number; otherAlpha?: number; /** * How the two drawings mix where they overlap: a `Document.BlendMode` value such as `'multiply'`. Defaults to `'normal'`. * The numbers 0–15 are also accepted, in the order of `Document.BlendMode`. */ blendMode?: BlendMode | number; /** Draw only lines without fill; true by default (overlay comparison is always true); pass false to turn it off */ noFill?: boolean; } declare class Document extends EventHandler { /** Names of the events this class triggers. */ static readonly Events: { /** 'documentComplete': the page table has been fully read. */ readonly DOCUMENT_COMPLETE: "documentComplete"; /** 'pagesUpdated': pages were added, removed, moved, rotated or changed. */ readonly PAGES_UPDATED: "pagesUpdated"; /** 'changePageIds': page numbers changed after pages were reordered. */ readonly CHANGE_PAGE_IDS: "changePageIds"; /** 'layersUpdated': the layer tree or layer visibility changed. */ readonly LAYERS_UPDATED: "layersUpdated"; /** 'colorSeparationAdded': color separation found a new ink. */ readonly COLOR_SEPARATION_ADDED: "colorSeparationAdded"; /** 'bookmarksUpdated': bookmark page numbers may have changed. */ readonly BOOKMARKS_UPDATED: "bookmarksUpdated"; }; /** Blend modes for the `blendMode` option of {@link Document.compareDrawings}. */ static readonly BlendMode: Readonly<{ /** The top drawing covers the bottom one. */ readonly NORMAL: "normal"; /** Multiplies the colors. */ readonly MULTIPLY: "multiply"; /** Screens the colors. */ readonly SCREEN: "screen"; /** Overlays the colors. */ readonly OVERLAY: "overlay"; /** Keeps the darker color. */ readonly DARKEN: "darken"; /** Keeps the lighter color. */ readonly LIGHTEN: "lighten"; /** Color dodge. */ readonly COLOR_DODGE: "colorDodge"; /** Color burn. */ readonly COLOR_BURN: "colorBurn"; /** Hard light. */ readonly HARD_LIGHT: "hardLight"; /** Soft light. */ readonly SOFT_LIGHT: "softLight"; /** Difference of the colors. */ readonly DIFFERENCE: "difference"; /** Exclusion. */ readonly EXCLUSION: "exclusion"; /** Hue of the top color with saturation and luminosity of the bottom. */ readonly HUE: "hue"; /** Saturation of the top color with hue and luminosity of the bottom. */ readonly SATURATION: "saturation"; /** Hue and saturation of the top color with luminosity of the bottom. */ readonly COLOR: "color"; /** Luminosity of the top color with hue and saturation of the bottom. */ readonly LUMINOSITY: "luminosity"; }>; private filename; private readonly fileSize; private pages; private readonly metadata; private readonly worker; private readonly canvasManager; private readonly settings; private readonly renderPool; private readonly renderScheduler; private ownScheduler?; private readonly password; private readonly documentId; /** Client of render requests: cache lookup / borrowing → merging → global queue → cached and shown (render/render-client.ts) */ private readonly render; /** loadCanvas / loadThumbnail in progress: id → cancel and scheduling keys */ /** In-flight renders (merged by key): cache key + scheduling key → task; removed from here once cached, when the cache is invalidated, and when no one waits */ /** Which Worker last rendered each page (affinity: re-rendering the page prefers it, using its already parsed page and decoded resources, and avoiding several Workers each decoding a copy) */ private readonly renderAffinity; /** Cold / warm render times of each page and "decode-bound" pinning (keyed by stable page id) */ private readonly pageHeat; /** Source bytes for render pool copies: given to the render pool to open copies as soon as the document opens (not asking the main Worker after the first screen renders), released once all copies are open */ private sourceBlob; private readonly maxReplicas; private readonly complete; private readonly openDocument?; private readonly pageHistory; /** * Undo / redo of page operations (insert, blank page, merge, delete, move, rotate), see PageHistoryManager * @returns The page history manager of this document (the same instance on every call). */ getPageHistoryManager(): PageHistoryManager; /** Fills in the page table in batches (P3, not competing with visible page rendering), fires documentComplete when done; stops after the document closes */ private loadRemainingPages; private pageNumbers?; private beforeSave?; /** Pages with annotation changes: render pool copies do not know them, so renders with annotation appearances (thumbnails) go to the main Worker */ private readonly annotationDirtyPages; private annotationOrder?; /** Pages with content changes: render pool copies do not know them, so all these pages are rendered by the main Worker */ private readonly contentDirtyPages; /** Pages with an open edit session (changes in the session are written back to the page only at EndEdit, and copies are not synced meanwhile) */ private readonly contentEditing; private markContentChanged; /** Version copies should have: 0 at open, plus one for each sync */ private replicaVersion; /** Page structure or the content of all pages changed and copies are not synced yet: all pages are rendered by the main Worker */ private replicasBehind; /** Change counter: if changes happen while a sync snapshot is taken, the snapshot is discarded */ private changeCount; private syncTimer; /** The snapshot just synced; each Worker takes a copy when opening the new version, released once all are open */ private syncSnapshot; private disposed; /** Page structure or the content of all pages changed: rendered by the main Worker from now on, copies synced after things quiet down */ private markReplicasBehind; /** * Page structure changed: when the copies can replay it (not inserting pages from another document, no other pending changes), it is replayed on each copy and rendering returns to the render pool right away; * otherwise rendered by the main Worker and synced with a snapshot after things quiet down */ private updateReplicas; /** Syncs after REPLICA_SYNC_DELAY_MS of quiet (not needed without a render pool) */ private scheduleReplicaSync; /** * The main Worker saves the current state (P4), and if no new changes happened meanwhile it is swapped in: version plus one, changed pages no longer tracked, each Worker opens a new copy at the new version * (rendered by the main Worker until then). Not synced with a content edit session open, layer visibility changed, or separations on (those always render on the main Worker) */ private syncReplicas; /** * XFDF of form widgets exported in the engine's native style (one element per widget under ). * Only form widgets, no annotations; uncommitted changes are committed first (as on save) * @returns A Promise that resolves to the XFDF string of the form widgets. */ exportWidgetsXfdf(): Promise; /** * Exports the document's annotations as XFDF. Annotation changes not yet saved to the document (properties set directly on annotation objects) are committed first, as on save. * @param ids Ids of the annotations to export; all annotations when omitted. * @param pageIds Internal page ids that limit the export to those pages; all pages when omitted. * @returns A Promise that resolves to the XFDF string. */ exportAnnotations(ids?: string[], pageIds?: PageId[]): Promise; /** * Imports plain or command XFDF into the document. * @param xfdf The XFDF text. * @param replaceAll When true, every annotation in the document is deleted before importing. Defaults to false. * @returns A Promise that resolves to the data of the imported or changed annotations and the ids of deleted ones. */ importAnnotations(xfdf: string, replaceAll?: boolean): Promise; /** * Snaps a point to the nearest page geometry (see DocumentViewer.snapToNearest). * @param pageNumber Page number (1-based). * @param x Horizontal position in page coordinates. * @param y Vertical position in page coordinates. * @param mode Snap modes to try, as SnapMode bit flags. * @param radius Search radius in page units (points). * @returns A Promise that resolves to the snapped point; when nothing is in range the point is returned unchanged and `mode` is absent. */ snapToNearest(pageNumber: number, x: number, y: number, mode: number, radius: number): Promise<{ /** Horizontal position of the snapped point. */ x: number; /** Vertical position of the snapped point. */ y: number; /** The snap mode that matched, when a point was snapped. */ mode?: number; }>; /** * Returns the documentId passed to loadDocument, or the SDK-generated id when none was passed. * @returns The document id. */ getDocumentId(): string; /** * Closes the document: stops its rendering, frees its cached page images and releases it in the engine. * Call it for documents made with Core.createDocument once they are no longer needed; the viewer closes the documents it loads itself. * @returns Resolves once the document is released. */ close(): Promise; private page; /** * Returns the number of pages. * @returns The page count. * @example * ```js * const { documentViewer } = instance.Core; * const doc = documentViewer.getDocument(); * for (let pageNumber = 1; pageNumber <= doc.getPageCount(); pageNumber++) * console.log(pageNumber, doc.getPageInfo(pageNumber)); * ``` */ getPageCount(): number; /** * Size including the page's own /Rotate (PDF points) * @param pageNumber Page number (1-based). Throws a RangeError when out of range. * @returns The page width and height in PDF points, after applying the page's own /Rotate. * @example * ```js * const { documentViewer } = instance.Core; * const doc = documentViewer.getDocument(); * const { width, height } = doc.getPageInfo(1); // in PDF points (1/72 inch) * console.log(`Page 1 is ${width / 72} x ${height / 72} inches`); * ``` */ getPageInfo(pageNumber: number): PageInfo; /** * One Core.PageInfo per page: size including /Rotate, /Rotate (degrees), the getPageMatrix matrix, page id and page number (created anew each time) * @returns A new array with one PageInfo per page, in page order. */ getPages(): PageInfo$1[]; /** * The page's own /Rotate in degrees (0 / 90 / 180 / 270) * @param pageNumber Page number (1-based). Throws a RangeError when out of range. * @returns The rotation in degrees: 0, 90, 180 or 270. */ getPageRotation(pageNumber: number): number; /** * PDF coordinates (bottom-left origin, y upward) → page coordinates (top-left origin, y downward): flip y, then translate by the unrotated page height * @param pageNumber Page number (1-based). Throws a RangeError when out of range. * @returns A new matrix mapping PDF coordinates to page coordinates. */ getPageMatrix(pageNumber: number): Matrix; /** * Returns the document information entries read when the document was opened; only non-empty entries are present. * @returns A Promise that resolves to a copy of the metadata. */ getMetadata(): Promise; /** * Returns the file name. * @returns The file name, including the extension. */ getFilename(): string; /** * Changes the file name reported by getFilename. * @param name The new file name. */ setFilename(name: string): void; /** * Original file size in bytes * @returns The size in bytes of the file as it was loaded. */ getFileSize(): number; /** * Returns the document type. * @returns Always 'pdf'. */ getType(): 'pdf'; /** * The file is linearized (checked from the linearization dictionary at the start of the file at open) * @returns True when the loaded file is linearized. */ isLinearized(): boolean; private readonly linearized; /** The page table is fully read (only the first batch is read at open, the rest filled in in the background) */ getDocumentCompletePromise(): Promise; /** * The page structure changed (added, removed, moved, rotated, cropped) * @returns True once any page has been added, removed, moved, rotated or cropped since the document was opened. */ arePagesAltered(): boolean; /** The page structure changed (arePagesAltered) */ private pagesAltered; /** * Page coordinates (unrotated page, top-left origin, y downward) → PDF coordinates (bottom-left origin, y upward). * ponytail: assumes the page box origin is (0, 0); for annotations to land exactly in files with an offset MediaBox, PageData would need the box origin * @param pageNumber Page number (1-based). * @param x Horizontal position in page coordinates. * @param y Vertical position in page coordinates. * @returns The point in PDF coordinates. */ getPDFCoordinates(pageNumber: number, x: number, y: number): { /** Horizontal position. */ x: number; /** Vertical position. */ y: number; }; /** * Converts PDF coordinates (bottom-left origin, y up) to page coordinates (unrotated page, top-left origin, y down). * @param pageNumber Page number (1-based). * @param x Horizontal position in PDF coordinates. * @param y Vertical position in PDF coordinates. * @returns The point in page coordinates. */ getViewerCoordinates(pageNumber: number, x: number, y: number): { /** Horizontal position. */ x: number; /** Vertical position. */ y: number; }; private unrotatedHeight; /** * Second item of the PDF trailer /ID (without angle brackets), an empty string when missing; unrelated to getDocumentId used for loading. * @returns A Promise that resolves to the identifier, or an empty string when the file has none. */ getFileIdentifier(): Promise; /** * Sets the second item of the PDF trailer /ID; requires 32 hex characters, returns false when invalid, persisted on save when successful. * @param id The new identifier: 32 hexadecimal characters. * @returns A Promise that resolves to true when the identifier was set, or false when it is invalid. */ setFileIdentifier(id: string): Promise; /** * Whether the engine considers it an image document (scanned PDF). * @returns A Promise that resolves to true for an image-only document. */ isImageDocument(): Promise; /** * The engine's optimization defaults: quality 0–1, PPI as [upper, target]. * @returns A Promise that resolves to the default optimization settings. */ getOptimizeDefaults(): Promise; /** * Saves to bytes (after committing uncommitted annotation changes). With xfdfString the annotations in the exported file are replaced by it; with includeAnnotations false no annotations are included, * flatten burns annotations (including forms) into page content, optimize takes the optimized saving path; these options run on a copy, leaving the open document unchanged * @param options Save options: `xfdfString` replaces the annotations in the output, `includeAnnotations: false` leaves annotations out, `flatten` burns annotations into page content, `flags` are SaveOptions flags and `optimize` enables optimized saving. All optional. * @returns A Promise that resolves to the bytes of the saved PDF. * @example * ```js * // Download the document, including its annotations and form data * const { documentViewer } = instance.Core; * const data = await documentViewer.getDocument().getFileData(); * const url = URL.createObjectURL(new Blob([data], { type: 'application/pdf' })); * const link = document.createElement('a'); * link.href = url; * link.download = 'document.pdf'; * link.click(); * URL.revokeObjectURL(url); * * // A copy with annotations burned into the page content * const flattened = await documentViewer.getDocument().getFileData({ flatten: true }); * ``` */ getFileData(options?: GetFileDataOptions): Promise; /** * XFDF of the document's annotations, only these pages when page numbers (1-based) are given. Annotation changes not yet saved to the document are committed first, as on save. * @param pageNumbers Page numbers (1-based) to export; all pages when omitted. * @returns A Promise that resolves to the exported page numbers and the XFDF string. */ extractXFDF(pageNumbers?: number[]): Promise<{ /** The page numbers (1-based) exported. */ pages: number[]; /** The XFDF text. */ xfdfString: string; }>; /** * Renders a page (or the renderRect part) to a new canvas, then calls drawComplete; on a CanvasManager hit the callback comes in the next microtask. * Older queued requests for the same region of the same page are replaced by the new one. * @param options Render options: `pageNumber` (1-based), `zoom` or a `width` / `height` box in CSS pixels, `pageRotation`, `renderRect`, `multiplier`, `renderAnnotations`, `layerUsage`, and the `drawComplete` callback. * @returns A request id that can be passed to cancelLoadCanvas, pauseLoadCanvas or resumeLoadCanvas. */ loadCanvas(options: LoadCanvasOptions): number; /** Zoom of loadCanvas: with width / height, fits the display size (including view rotation and renderRect) into the box, otherwise uses zoom */ private fitZoom; /** Scheduling key an in-flight request queues under: one per single request; one per dispatch for tile batches (cells merged into another render use that render's key). Also updates the priority recorded for renders not yet dispatched */ private renderKeys; /** * Cancels a render started by loadCanvas or loadThumbnail. The shared render is aborted only when no other request is waiting for it. * @param id The id returned by loadCanvas. */ cancelLoadCanvas(id: number): void; /** The content of the whole document changed (headers / footers, background, watermark, standard conversion, applied redactions): render versions of all pages change together */ private contentEpoch; /** The content of one page changed (content editing, page rotation / cropping): this page's render version */ private readonly pageVersions; /** Annotations of one page changed: only affects variants with annotation appearances */ private readonly annotationVersions; /** Number of times layer visibility changed: part of the variant key of layer-set rendering, changes for all pages together */ private layerEpoch; /** Number of times separations were turned on (results differ when the ICC changes); the on/off state of each ink is counted in the variant separately */ private sepEpoch; /** Bitmap cache key of a page in the current state. zoomBucket is the tier (page rendering) or the thumbnail scale; rect holds only the region, the variant is separate */ /** This document is a copy of source: for each page, its pageId in the source and the render versions of both sides at that time (if either side changes, this page is no longer borrowed) */ private origin?; /** * Borrows an image from the source document's cache (whole page, ordinary drawing): the smallest one in the source with the same page, rotation and multiplier whose long side is 0.9–4 times the target, scaled down to the target size. * Returns undefined when nothing can be borrowed (none, too small, too large, source or copy page changed, layers / separations changed, annotations needed and the source page has annotations or it is unknown, source closed). * What is borrowed is a new canvas (the scaled-down result); the source bitmap is neither pinned nor copied */ private borrowFromOrigin; /** Requests at thumbnail size borrow a whole-page image from this document's own cache (ordinary drawing, same rotation and multiplier) */ private borrowFromSelf; private bitmapKey; /** Releases cached bitmaps of a page (by pageId); in-flight renders of the same page accept no new joins (they draw content from before invalidation, and their results are not cached); match limits which */ private dropBitmaps; /** The content of these pages changed: render version plus one (old keys invalidated), old bitmaps released */ private invalidatePages; /** The content of all pages changed: the render version goes up by one overall, and all of this document's bitmaps are released */ private invalidateAllPages; /** Releases all of this document's bitmaps (layer changes, unloadResources, close); in-flight renders accept no new joins and their results are not cached */ private dropAllBitmaps; /** * Lowers a queued render to background priority; renders already started are not affected. * @param id The id returned by loadCanvas. Unknown ids are ignored. */ pauseLoadCanvas(id: number): void; /** * Moves a queued render back to visible priority. * @param id The id returned by loadCanvas. */ resumeLoadCanvas(id: number): void; /** Moves a queued render to another priority: first looks in the global queue, and if not found (handed to a Worker but not started) in each Worker's queue */ private setRenderPriority; /** * Renders a page thumbnail, including annotations and form widgets. * @param pageNumber Page number (1-based). * @param onLoad Called with the rendered canvas. * @param size Length of the longer side in CSS pixels (the bitmap is multiplied by the canvas multiplier). Defaults to 150. * @returns A request id that can be passed to cancelLoadThumbnail. */ loadThumbnail(pageNumber: number, onLoad: (thumb: HTMLCanvasElement) => void, size?: number): number; /** * Cancels a thumbnail render; same as cancelLoadCanvas. * @param id The id returned by loadThumbnail. */ cancelLoadThumbnail(id: number): void; /** * Waits for a page to be available. The whole document is loaded, so this resolves immediately. * @param pageNumber Page number (1-based). Throws a RangeError when out of range. */ requirePage(pageNumber: number): Promise; /** * Releases the cached bitmaps of a page. * @param pageNumber Page number (1-based). */ unloadCanvasResources(pageNumber: number): void; /** Releases the cached bitmaps of every page. */ unloadResources(): void; /** Read-only view of Document state for RenderClient */ private renderHost; private replicaSource; /** Right after opening, has the render pool open copies from the source Blob, so the first screen can use the render pool; the Blob is released once all are open */ private prepareReplicas; /** * Plain text of this page (one \n between lines) * @param pageNumber Page number (1-based). * @returns A Promise that resolves to the page text. * @example * ```js * const { documentViewer } = instance.Core; * const doc = documentViewer.getDocument(); * const text = await doc.loadPageText(1); * console.log(text.split('\n').length, 'lines on page 1'); * ``` */ loadPageText(pageNumber: number): Promise; /** * Quad of each character in [startIndex, endIndex) (indexes as in the text of loadPageText; page coordinates) * @param pageNumber Page number (1-based). * @param startIndex Index of the first character (inclusive). * @param endIndex Index after the last character (exclusive). The range is clamped to the page text. * @returns A Promise that resolves to one quad per character, in page coordinates. * @example * ```js * // Highlight the first occurrence of a word on page 1 * const { documentViewer, annotationManager, Annotations } = instance.Core; * const doc = documentViewer.getDocument(); * const word = 'Agreement'; * const start = (await doc.loadPageText(1)).indexOf(word); * if (start >= 0) { * const quads = await doc.getTextPosition(1, start, start + word.length); // one quad per character * const highlight = new Annotations.TextHighlightAnnotation({ PageNumber: 1 }); * highlight.setQuads(quads); * await annotationManager.addAnnotation(highlight); * } * ``` */ getTextPosition(pageNumber: number, startIndex: number, endIndex: number): Promise; /** * Characters in the rectangle (page coordinates; the character center inside the rectangle), one \n between lines when spanning lines * @param pageNumber Page number (1-based). * @param rect The rectangle in page coordinates (points, top-left origin). * @returns A Promise that resolves to the text, or an empty string when no character is inside. * @example * ```js * const { documentViewer, Math: CoreMath } = instance.Core; * // Text inside the top 100 pt of page 1 (PDF points, origin at the top-left of the page) * const doc = documentViewer.getDocument(); * const { width } = doc.getPageInfo(1); * const header = await doc.getTextByPageAndRect(1, new CoreMath.Rect(0, 0, width, 100)); * ``` */ getTextByPageAndRect(pageNumber: number, rect: Rect): Promise; /** Drops the page text cache after page content changes (TextManager invalidates by text version) */ refreshTextData(): void; /** * By the writing direction of this page's text (RightToLeft when there is right-to-left text and no left-to-right text); the value set by setPageTextDirection if set * @param pageNumber Page number (1-based). * @returns A Promise that resolves to the text direction. */ getPageTextDirection(pageNumber: number): Promise; /** * Sets this page's writing direction (ignored when not a TextDirection value); follows the page * @param pageNumber Page number (1-based). * @param direction The text direction. */ setPageTextDirection(pageNumber: number, direction: TextDirection): void; private readonly textDirections; /** * Text extraction processing options (an array of TextExtractorProcessingFlags, stored bitwise ORed). * Note: engine text extraction (InitText) has no options, so they are only stored * @param flags TextExtractorProcessingFlags values to combine. */ setTextExtractorProcessingFlags(flags: number[]): void; /** * Rendering options, merged with existing ones; note: engine rendering has no matching settings, so they are only stored. Returns true with a document * @param options Options to merge into the stored rendering options. * @returns Always true. */ updateRasterizerOptions(options: Record): boolean; /** * Overprint preview (OverprintPreviewMode), recorded in overprintMode of the rendering options; note: engine rendering does not simulate overprint * @param mode The overprint preview mode. */ setOverprintPreviewMode(mode: OverprintPreviewMode): void; /** * Named destinations (catalog /Dests and the /Names /Dests name tree): GoTo destinations with a name, 1-based page numbers, page coordinates * @returns A Promise that resolves to the named destinations, each a Dest with its name. */ getDestinations(): Promise>; private textVersion; private pageText; /** * Inserts these pages (all by default) of doc (a document opened in the same Worker) before page insertBeforeThisPage (at the end by default), * bringing the annotations on them along * @param doc The source document; it must be open in the same SDK instance. * @param pagesToInsert Page numbers (1-based) or range strings such as '1-3' of the source document; all pages when omitted. * @param insertBeforeThisPage Page number (1-based) to insert before; at the end when omitted or greater than the page count. */ insertPages(doc: Document, pagesToInsert?: PageList, insertBeforeThisPage?: number): Promise; /** * Copy each selected page immediately after itself, as one page edit and undo step. Input is 1-based, sorted and deduplicated without mutation. * @param pageNumbers Page numbers (1-based) or range strings such as '1-3'. Throws a RangeError when a page does not exist. */ copyPages(pageNumbers: PageList): Promise; /** * Deletes these pages (not all of them); annotations on them are deleted too * @param pageNumbers Page numbers (1-based) or range strings such as '5-7'. Throws a RangeError when a page does not exist; removing every page is rejected. * @example * ```js * const { documentViewer } = instance.Core; * const doc = documentViewer.getDocument(); * await doc.removePages([2, 4]); * await doc.removePages('5-7'); // ranges are allowed too * ``` */ removePages(pageNumbers: PageList): Promise; /** * Moves these pages in page number order before page insertBeforeThisPage (to the end when beyond the page count) * @param pageNumbers Page numbers (1-based) or range strings of the pages to move. * @param insertBeforeThisPage Page number (1-based, counted before the move) to place the pages before; values below 1 mean the front. * @example * ```js * const { documentViewer } = instance.Core; * const doc = documentViewer.getDocument(); * await doc.movePages([5], 1); // move page 5 to the front * await doc.movePages([1, 2], doc.getPageCount() + 1); // move pages 1 and 2 to the end * ``` */ movePages(pageNumbers: PageList, insertBeforeThisPage: number): Promise; /** * Rotates clockwise by rotation (PageRotation, a multiple of 90°) on top of the existing rotation * @param pageNumbers Page numbers (1-based) or range strings. * @param rotation Quarter turns clockwise to add, as a PageRotation value. * @example * ```js * const { documentViewer, PageRotation } = instance.Core; * const doc = documentViewer.getDocument(); * await doc.rotatePages([1, 3], PageRotation.E_90); // adds 90 degrees clockwise to the current rotation * ``` */ rotatePages(pageNumbers: PageList, rotation: PageRotation): Promise; /** * Crops this much from the top, bottom, left and right (pt, in the page's display orientation), written to /CropBox; not undoable, history is cleared * @param pageNumbers Page numbers (1-based) or range strings. * @param top Points to remove from the top. * @param bottom Points to remove from the bottom. * @param left Points to remove from the left. * @param right Points to remove from the right. */ cropPages(pageNumbers: PageList, top: number, bottom: number, left: number, right: number): Promise; /** * Inserts a width × height blank page before each of these pages (page numbers before the change; page count + 1 means at the end) * @param insertBeforeThesePages Page numbers (1-based) before which a blank page is inserted; the page count plus one appends at the end. * @param width Page width in points. * @param height Page height in points. * @example * ```js * const { documentViewer } = instance.Core; * const doc = documentViewer.getDocument(); * // A US Letter page (612 x 792 pt) before page 1 and another one at the end * await doc.insertBlankPages([1, doc.getPageCount() + 1], 612, 792); * ``` */ insertBlankPages(insertBeforeThesePages: number[], width: number, height: number): Promise; /** * Saves these pages (with their committed annotations) as a new PDF. Pages are 1-based page numbers or range strings * such as `'3-4'` / `'1,3-4'`; they are taken in page order. When `xfdfString` is given, its annotations are merged in * (page numbers of this document; annotations already present are not duplicated). * With `{ separateFile: true }` each page becomes its own PDF and an array of files (in page order) is returned. * @param pageNumbers Page numbers (1-based) or range strings. Throws a RangeError when a page does not exist. * @param xfdfString Optional XFDF whose annotations are merged into the output. * @param options Extract options; without `separateFile` (or with false) one PDF is produced. * @returns A Promise that resolves to the bytes of one PDF holding the pages. * @example * ```js * const { documentViewer } = instance.Core; * const doc = documentViewer.getDocument(); * const pages1to3 = await doc.extractPages('1-3'); // one ArrayBuffer * const singlePages = await doc.extractPages([1, 2], undefined, { separateFile: true }); // one ArrayBuffer per page * const blob = new Blob([pages1to3], { type: 'application/pdf' }); * ``` */ extractPages(pageNumbers: PageList, xfdfString?: string, options?: ExtractPagesOptions & { /** Omit or false to get one PDF holding all pages. */ separateFile?: false; }): Promise; /** * Saves these pages as separate PDFs, one per page, in page order. * @param pageNumbers Page numbers (1-based) or range strings. Throws a RangeError when a page does not exist. * @param xfdfString Optional XFDF whose annotations are merged into the output. * @param options Extract options with `separateFile: true`. * @returns A Promise that resolves to one PDF per page, in page order. */ extractPages(pageNumbers: PageList, xfdfString: string | undefined, options: ExtractPagesOptions & { /** true to get one PDF per page. */ separateFile: true; }): Promise; /** * Saves these pages as a new PDF, or as one PDF per page when `options.separateFile` is true. * @param pageNumbers Page numbers (1-based) or range strings. Throws a RangeError when a page does not exist. * @param xfdfString Optional XFDF whose annotations are merged into the output. * @param options Extract options; `separateFile: true` produces one PDF per page. * @returns A Promise that resolves to one PDF, or to an array of PDFs when `separateFile` is true. */ extractPages(pageNumbers: PageList, xfdfString?: string, options?: ExtractPagesOptions): Promise; private pageIdSet; /** Pages added by an operation are recorded as one "pages in" step (on undo saved as bytes and deleted, on redo inserted back at the original positions) */ private recordPresence; /** * One "pages in / pages out" step: ids are these pages, positions their page numbers when all are present (ascending). Bytes are saved before they go out (with the annotations at that moment), and they are inserted back at the original positions with new ids; * saved is the bytes when the pages are already out (saved by the delete operation itself) */ private recordPages; /** Inserts pages saved by extractPages back at their original page numbers (ascending) and returns the new page ids; earlier ones first so later positions are correct */ private restorePages; private rotateBy; /** Moves the pages in moved back to the order in target: in target order, each page moves before the first unmoved page after it (or to the end when none) */ private restoreOrder; /** * Inserts all pages of another document (address, bytes, File and so on, or an opened Document) before page insertBeforePage (at the end by default) * @param src The document to merge: a URL, bytes, Blob or File, or an already opened Document. A source opened here is closed afterwards. * @param insertBeforePage Page number (1-based) to insert before; at the end when omitted or greater than the page count. * @returns A Promise that resolves to the source file name and its inserted page numbers. * @example * ```js * const { documentViewer } = instance.Core; * const doc = documentViewer.getDocument(); * // Append every page of another PDF at the end * const { pages } = await doc.mergeDocument('https://example.com/files/appendix.pdf'); * console.log(`Inserted ${pages.length} pages`); * ``` */ mergeDocument(src: DocumentSource | Document, insertBeforePage?: number): Promise<{ /** File name of the merged document. */ filename: string; /** Page numbers (1-based) of the source document that were inserted (all of its pages). */ pages: number[]; }>; /** 1-based page number → 0-based insert position (at the end when omitted or out of range) */ private insertPosition; /** Expands range strings, removes duplicates, sorts by page number; pages must exist */ private distinctPages; /** Commits annotations first and waits for the page table to be read; after the Worker is done, swaps in the new page table and fires changePageIds and pagesUpdated */ private editPages; /** * Sets headers / footers (replacing existing ones); <<1>> in the text is the page number from 1, <<1,3>> zero-padded to 3 digits * @param options The texts by position, the margins in points (36 by default) and the page numbers (1-based) to apply to (all pages when omitted). * @example * ```js * const { documentViewer } = instance.Core; * const doc = documentViewer.getDocument(); * await doc.setHeaderFooter({ * texts: { * topRight: { text: 'CONFIDENTIAL', fontSize: 10, color: '#ff0000' }, * bottomCenter: 'Page <<1>>', * }, * margins: { top: 24, bottom: 24 }, * }); * ``` */ setHeaderFooter(options: HeaderFooterOptions): Promise; /** * Current headers / footers; null when none * @returns A Promise that resolves to the settings, or null when there are none. */ getHeaderFooter(): Promise; /** Removes all headers and footers. Pages are redrawn afterwards. */ removeAllHeaderFooters(): Promise; /** * Sets Bates numbering (replacing existing ones); <<#digits#start#prefix#suffix>> in the text, such as <<#6#1#ABC#>> giving ABC000001, ABC000002... * @param options The texts by position, the margins in points (36 by default) and the page numbers (1-based) to apply to (all pages when omitted). */ setBates(options: HeaderFooterOptions): Promise; /** * Returns the current Bates numbering settings. * @returns The settings, or null when there is no Bates numbering. */ getBates(): Promise; /** Removes all Bates numbering. Pages are redrawn afterwards. */ removeAllBates(): Promise; /** * Sets the background (replacing the existing one): a solid color (color) or an image (image, RGBA pixels such as ImageData), placed under the page content * @param options Either `color` ('#rrggbb') or `image`, plus optional opacity (1 by default), scale (1), rotation in degrees (0), alignment ('center'), offsets in points (0), page numbers (1-based, all pages when omitted), and whether it shows on screen and in print (both true by default). */ setBackground(options: BackgroundOptions): Promise; /** * Current background settings (image backgrounds do not read back pixels, and the engine cannot read back the page range); null when none * @returns A Promise that resolves to the settings, or null when there is no background. */ getBackground(): Promise<(Omit & { /** Whether the background is a color or an image. */ type: 'color' | 'image'; }) | null>; /** Removes the background. Pages are redrawn afterwards. */ removeAllBackgrounds(): Promise; /** * Adds a watermark to the file (text or image, leaving existing ones); use setWatermark / DocumentViewer.setWatermark for view watermarks * @param options Watermark settings: `text` or `image` is required (rejects otherwise). Defaults: font Helvetica, size 48, color '#808080', opacity 0.5, rotation 45 degrees, scale 1, centered, drawn in front, on all pages. * @example * ```js * const { documentViewer } = instance.Core; * const doc = documentViewer.getDocument(); * await doc.addWatermark({ * text: 'DRAFT', * fontSize: 72, * color: '#ff0000', * opacity: 0.3, * rotation: 45, * pages: [1, 2, 3], * }); * ``` */ addWatermark(options: DocumentWatermarkOptions): Promise; /** * Watermarks already in the file * @returns A Promise that resolves to the watermarks; image pixels are not read back. */ getWatermarks(): Promise>; /** Deletes all watermarks in the file */ removeAllWatermarks(): Promise; /** * Lists the files embedded in the document. * @returns The attachments, in document order. */ getAttachments(): Promise; /** * Embeds a file, written to the file on save * @param name File name of the attachment. * @param data File content; it is copied. * @param description Optional description. */ addAttachment(name: string, data: ArrayBuffer | Uint8Array, description?: string): Promise; /** * Removes an embedded file. * @param index Index of the attachment in getAttachments. */ removeAttachment(index: number): Promise; /** * Reads the content of an embedded file. * @param index Index in getAttachments. * @returns The file bytes. */ readAttachment(index: number): Promise; /** * Converts to PDF/A or PDF/UA-1 (changes this document in place; saving afterwards gives that standard). * PDF/A: iccProfile is the output intent, by default the same as separations (CMYK/CoatedFOGRA39.icc). * PDF/UA-1: adds structure tags automatically (Document → NonStruct → Span), writes the title (shown in the title bar) and language; title defaults to the title in the document info, and it errors when there is neither; * language is a locale name like 'zh-CN' (the engine accepts only 25, see UA_LANGUAGES), not written when omitted. Note: PDF/A and PDF/UA cannot be converted together (the engine aborts); slow with many pages or much content (about 40 s for a few dozen pages of text and images) * @param type The target standard, such as 'PDF/A-2b' or 'PDF/UA-1'. Rejects for other values. * @param options Conversion options. Rejects for PDF/UA when there is no title or the language is not supported. * @param options.iccProfile PDF/A only: output intent ICC profile as bytes or a URL. * @param options.title PDF/UA only: document title; the title in the document information when omitted. * @param options.language PDF/UA only: locale name such as 'en-US'; not written when omitted. */ convertToStandard(type: StandardType, options?: { /** PDF/A only: output intent ICC profile as bytes or a URL. Defaults to CMYK/CoatedFOGRA39.icc in the Worker folder. */ iccProfile?: ArrayBuffer | string; /** PDF/UA only: document title. Defaults to the title in the document information. */ title?: string; /** PDF/UA only: document language as a locale name such as 'en-US'; not written when omitted. */ language?: string; }): Promise; /** * One engine conversion takes tens of seconds and cannot yield midway: with a render pool it goes to one of its Workers (the main Worker hands over the current state and swaps in the result), * while the main Worker keeps rendering and handling other documents, and writes to this document wait for it. Converted in place without a render pool, or when the password was changed this time */ private convertStandard; /** * The standard the document declares: 'PDF' (none) or a name like 'PDF/A-2b' * @returns A Promise that resolves to the standard name. */ getStandardType(): Promise; /** Page content changed in the Worker: page bitmaps and page text are invalidated, rendered by the main Worker afterwards, fires pagesUpdated (all pages contentChanged) */ private changeContent; /** The content of all pages changed: page bitmaps and page text are invalidated, rendered by the main Worker afterwards with copies synced after things quiet down, fires pagesUpdated (all pages contentChanged) */ private contentChanged; private headerFooterData; private headerFooterOptions; /** * Top level of the outline (bookmark) tree; read from the document again on each call. * @returns A Promise that resolves to the top-level bookmarks. * @example * ```js * const { documentViewer } = instance.Core; * const bookmarks = await documentViewer.getDocument().getBookmarks(); * const print = (items, depth = 0) => items.forEach((bookmark) => { * console.log(`${' '.repeat(depth)}${bookmark.getName()} (page ${bookmark.getPageNumber()})`); * print(bookmark.getChildren(), depth + 1); * }); * print(bookmarks); * ``` */ getBookmarks(): Promise; /** * Layer (OCG) tree: name, visible, locked, child layers; obj is the identifier the Worker uses to find the layer. Only one stays on in a radio group (RBGroup) * @returns A Promise that resolves to the top-level layers, or an empty array when layers are disabled. */ getLayersArray(): Promise; /** * Writes back the tree given by getLayersArray (with visible / locked changed); when more than one is on in a radio group, the one just turned on compared with before is kept. * Page bitmaps are invalidated and all rendered by the main Worker afterwards (render pool copies do not know this change); fires layersUpdated (DocumentViewer redraws pages from it) * @param layers The layer tree from getLayersArray with `visible` / `locked` changed. */ setLayersArray(layers: Layer[]): Promise; /** Layer visibility changed: all rendering goes to the main Worker */ private layersChanged; private layersEnabled; /** * Disables layers: the layer tree is not read (getLayersArray gives an empty array), * pages and printing render by the engine default (layers hidden by default in the file stay hidden). Changing it invalidates page bitmaps and fires layersUpdated * @param enabled False to disable layers, true to enable them again. */ setLayersEnabled(enabled: boolean): void; /** * Exports a PDF containing only the content of these layers: objs are layer objs from getLayersArray; without them all layers visible by default are exported * @param objs Layer `obj` identifiers from getLayersArray; the layers visible by default when omitted. * @returns A Promise that resolves to the bytes of the exported PDF. */ exportLayers(objs?: string[]): Promise; /** The layer tree set last (or the first one fetched when never set); radio groups use it to find the one just turned on */ private layersBefore; /** * Turns on separations: page bitmaps afterwards render by ink (inks turned off in getColorSeparations are not drawn), all by the main Worker; * colorSeparationAdded fires once for each new ink. After toggling, call DocumentViewer.refreshAll to redraw. * iccProfile is the CMYK output intent (bytes or address), CMYK/CoatedFOGRA39.icc in the Worker directory by default; * with checkIfBaseColorsUsed inks carry isBaseColor / isBaseColorUsedInDocument (checked by rendering each page at a small size, taking longer with many pages) * @param options Separation options. * @param options.iccProfile CMYK output intent ICC profile as bytes or a URL. * @param options.checkIfBaseColorsUsed When true, each ink also reports whether it is a CMYK base color and whether it is used. False by default. */ enableColorSeparations(options?: { /** CMYK output intent ICC profile as bytes or a URL. Defaults to CMYK/CoatedFOGRA39.icc in the Worker folder. */ iccProfile?: ArrayBuffer | string; /** Also reports whether each ink is a CMYK base color and whether it is used; slower with many pages. */ checkIfBaseColorsUsed?: boolean; }): Promise; /** ICC output intent: bytes are used directly, an address is downloaded; CMYK/CoatedFOGRA39.icc in the Worker directory by default */ private loadIcc; /** Turns off separations and restores normal rendering (the ink list and on/off states are kept) */ disableColorSeparations(): void; /** * Returns the inks found by enableColorSeparations. * @returns The live list of inks; empty before enableColorSeparations. */ getColorSeparations(): ColorSeparation[]; /** * Turns an ink on or off by name; call DocumentViewer.refreshAll afterwards to redraw * @param name Ink name, as in getColorSeparations. Unknown names are ignored. * @param enabled True to draw the ink, false to hide it. */ enableSeparation(name: string, enabled: boolean): void; /** * Returns the density of each ink at a point; empty when separations are off. * @param pageNumber Page number (1-based). * @param x Horizontal position in page coordinates. * @param y Vertical position in page coordinates. * @returns A Promise that resolves to one entry per ink, in getColorSeparations order. */ getColorSeparationsAtPoint(pageNumber: number, x: number, y: number): Promise>; private colorSeparations; private separationsOn; /** * Watermark render quality. Watermarks are drawn as vectors, so only the value is stored. * @param quality A number greater than 0 and at most 10; throws otherwise. */ setWatermarkRenderQuality(quality: number): void; /** * Intended for XOD documents; returns null for PDF documents * @returns Always null. */ getPrintablePDF(): null; /** * The view watermark is already "applied" (for example already drawn into the page): DocumentViewer no longer draws it. * disableWatermarkApplied sets it back to false */ enableWatermarkApplied(): void; /** Sets the view watermark back to not applied, so DocumentViewer draws it again. */ disableWatermarkApplied(): void; private watermarkApplied; /** * View watermark (set here by DocumentViewer.setWatermark, read when drawing); use addWatermark to write into the file * @param options The view watermark, or null to remove it. */ setWatermark(options: WatermarkOptions | null): void; /** * Returns the view watermark set with setWatermark. * @returns The watermark options, or null when none is set. */ getWatermark(): WatermarkOptions | null; private viewWatermark; /** * Current permissions (encrypted documents opened with the user password are restricted, others have all); securityLevel: 0 not encrypted, 1 user, 2 owner. * Passwords and permissions set take effect only after saving; they do not change here * @returns A Promise that resolves to the permission flags and the security level. * @example * ```js * const { documentViewer } = instance.Core; * const doc = documentViewer.getDocument(); * const { printing, copying, securityLevel } = await doc.getPermissions(); * if (!copying) * console.log('Copying text is not allowed'); * ``` */ getPermissions(): Promise; /** * Whether it is the owner password; if so, the document gets owner permissions right away (an empty password counts for unencrypted documents) * @param password The password to check. * @returns A Promise that resolves to true when it is the owner password. * @example * ```js * const { documentViewer } = instance.Core; * const doc = documentViewer.getDocument(); * if (await doc.checkOwnerPassword('owner-secret')) * console.log('Owner permissions granted'); * ``` */ checkOwnerPassword(password: string): Promise; /** * Sets passwords and permissions, written by getFileData (full rewrite). With only the user password, the owner password is the same; with neither, encryption is removed. * Documents opened with the user password cannot change them (PERMISSION_DENIED) * @param options Passwords and permissions. * @param options.userPassword Password required to open the document; none when omitted or empty. * @param options.ownerPassword Password required to change permissions; the user password when omitted. * @param options.permissions Permissions granted to users who open the document with the user password. * @example * ```js * const { documentViewer } = instance.Core; * const doc = documentViewer.getDocument(); * await doc.setPassword({ * userPassword: 'open-me', * ownerPassword: 'owner-secret', * permissions: { * printing: true, * highQualityPrinting: true, * copying: false, * documentChanges: false, * documentAssembly: false, * commenting: true, * formFilling: true, * }, * }); * const protectedFile = await doc.getFileData(); // passwords take effect in the saved file * ``` */ setPassword(options: { /** Password required to open the document; empty for none. */ userPassword?: string; /** Password required to change permissions; the user password is used when only that is given. */ ownerPassword?: string; /** Permissions granted to users who open the document with the user password. */ permissions?: DocumentPermissions; }): Promise; /** * Changes only permissions: reuses the passwords set by this setPassword (the engine writes permissions together with passwords; PERMISSION_DENIED when no password was set) * @param permissions The permissions granted to users who open the document with the user password. */ setPermissions(permissions: DocumentPermissions): Promise; /** * Applies redaction annotations, removing the content under them; page content changes and pagesUpdated fires. * @param annotIds Ids of the redaction annotations to apply. * @param pageNumbers Page numbers (1-based) reported as changed in pagesUpdated. * @param erasureIds Ids of additional annotations to erase. Defaults to none. * @returns A Promise that resolves to the ids of the applied redactions and of the other annotations removed. */ applyRedactions(annotIds: string[], pageNumbers: number[], erasureIds?: string[]): Promise<{ /** Ids of the redaction annotations that were applied. */ applied: string[]; /** Ids of other annotations that were deleted because they lay under a redaction. */ removed: string[]; }>; /** * Verifies the digital signatures in the document: one result per signed signature field. * Checks ByteRange and the signature container, digest and signature value, whether the certificate chain reaches trustedCertificates within validity, and whether changes after signing are allowed; * unsaved modifications also count as changes after signing. Revocation is checked offline with OCSP responses and CRLs in the document DSS (enableLTVOfflineVerification, on by default); note: no online revocation checks (OCSP / CRL are not fetched over the network) * @param options Optional `trustedCertificates`, `validationTime` and `enableLTVOfflineVerification`. * @returns A Promise that resolves to one result per signed signature field. */ verifySignatures(options?: VerificationOptions): Promise; /** * Content comparison: marks replacements / insertions / deletions on **copies** of both documents and produces a combined report; * the two original documents are untouched. Pages correspond by index, compared up to the end of the shorter one * @param other The document to compare with. * @param options What to compare (text and images, both by default), the colors of replacements, insertions and deletions, and the opacity (0.5 by default). * @returns A Promise that resolves to the marked copies of both documents and the combined report document. */ compareContent(other: Document, options?: CompareContentOptions): Promise; /** * Overlay comparison: draws the graphics of both documents over each other in their own colors and opens the result as a new document. Neither original is changed. * @param other The document to compare with. * @param options Pages, colors, opacity and blending. * @returns The new document holding the comparison. */ compareDrawings(other: Document, options?: CompareDrawingsOptions): Promise; } /** Options of signature verification: trusted certificates (DER); time for checking certificate validity (auto: a trusted timestamp if any, otherwise now; signing: signing time; current: now) */ interface VerificationOptions { /** Trusted certificates (DER bytes). */ trustedCertificates?: Array; /** When certificate validity is checked: 'auto' uses a trusted timestamp if present, otherwise now; 'signing' uses the signing time; 'current' uses now; or a specific date. */ validationTime?: 'auto' | 'signing' | 'current' | Date; /** Offline revocation checks with OCSP responses and CRLs in the document DSS (on by default, no network) */ enableLTVOfflineVerification?: boolean; } /** Certificate summary and details (times as Date, der is the certificate bytes; other fields see CertificateData) */ interface VerificationCertificate extends Omit { /** Certificate bytes (DER). */ der: Uint8Array; /** Start of the validity period. */ notBefore: Date; /** End of the validity period. */ notAfter: Date; } /** Verification result of one signature (see SignatureVerificationData) */ interface VerificationResult extends Omit { /** Offline revocation check result: overall status and the status of each certificate in the chain except the root. */ revocation: { /** Overall result: revoked if any certificate is revoked, good if all are valid, unknown if some cannot be checked, not_checked without data. */ status: SignatureVerificationData['revocation']['status']; /** Result for each certificate in the chain except the root. */ certificates: Array<{ /** Subject name of the certificate. */ subject: string; /** Revocation status of the certificate. */ status: 'good' | 'revoked' | 'unknown'; /** Where the status came from: an OCSP response or a CRL. */ source?: 'ocsp' | 'crl'; /** When the certificate was revoked. */ revokedAt?: Date; }>; }; /** Signing time; null when there is none. */ signingTime: Date | null; /** Timestamp token time and whether it is valid; null without a timestamp. */ timestamp: { /** Time in the timestamp token. */ time: Date; /** Whether the timestamp token is valid. */ valid: boolean; } | null; /** Signer certificate; null when it cannot be read. */ signer: VerificationCertificate | null; /** Certificate chain of the signer. */ certificateChain: VerificationCertificate[]; } /** Core.Annotations.Color: R G B A (0–255 / 0–1). */ type ColorInput = Color | number[] | string; /** An RGBA color. */ declare class Color { /** Red component, 0 to 255. */ R: number; /** Green component, 0 to 255. */ G: number; /** Blue component, 0 to 255. */ B: number; /** Alpha (opacity), 0 to 1. */ A: number; /** * Numbers are R G B (0–255) and A (0–1); also accepts another color (copied), an array of 0–1 components (1 gray, 3 RGB, 4 CMYK), or '#rrggbb'. * Note: with no arguments it is opaque black. * @example * ```js * const { Annotations } = instance.Core; * const red = new Annotations.Color(255, 0, 0); * const halfTransparentBlue = new Annotations.Color(0, 0, 255, 0.5); * const fromHex = new Annotations.Color('#00aa55'); * console.log(fromHex.toHexString()); // '#00aa55' * ``` */ constructor(r?: number | ColorInput, g?: number, b?: number, a?: number); /** CSS color string rgba(R,G,B,A). */ toString(): string; /** * Converts the color to a hex string (alpha is ignored). * @returns The color as '#rrggbb'. */ toHexString(): string; } /** * Core.Annotations.Font: font of form widgets and fields: name, size (0 is automatic), type, fill color and stroke color (the text color). * A widget's font maps to /DA (GetAnnotFontDa / SetAnnotFontDa). */ interface FontOptions { name?: string; size?: number; type?: string; fillColor?: ColorInput; strokeColor?: ColorInput; 'horizontal-scaling'?: number | null; } /** Font of form widgets and fields: name, size, type, fill color and stroke color. */ declare class Font { private fontName; private fontSize; private fontType; private fill; private stroke; /** Horizontal scaling of the text (stored only), or null when not set. */ 'horizontal-scaling': number | null; /** Options, another font (copied), or just a font name. */ constructor(options?: FontOptions | Font | string); /** Changes the given items; a string is a font name. */ set(options?: FontOptions | Font | string): void; /** Font name. */ get name(): string; set name(name: string); /** Font size (pt); 0 is automatic by widget size. */ get size(): number; set size(size: number); /** Font type, such as 'Type1' (the default). */ get type(): string; /** Fill color of the text. */ get fillColor(): Color; set fillColor(color: ColorInput); /** Stroke color of the text. */ get strokeColor(): Color; set strokeColor(color: ColorInput); /** Actual font size: not computed here, so 0 when automatic. */ get calculatedSize(): number; /** * Whether another font has the same name, size, type, fill color and stroke color. * @param other The font to compare with. * @returns True when they are equal. */ equals(other: Font): boolean; } /** * Core.Annotations.HTMLAnnotation: a retained intermediate base class whose action methods are shared by Link and all Widgets. * Annotations are drawn on canvas, so DOM methods such as getElement / getInnerElement are not provided. */ declare class HTMLAnnotation extends Annotation$1 { elementName: string; /** Actions by trigger name: 'U' (mouse up) is /A in the file, others are /AA keys. */ private readonly actions; /** Appends to the actions of this trigger; written to the file (/A, /AA) on updateAnnotation / addAnnotation. */ addAction(trigger: string, action: Action): void; /** * Gets the actions of the annotation by trigger. * @returns Trigger name to its actions. */ getActions(): Record; /** Runs through Actions.Dispatcher. */ triggerAction(trigger: string, event?: Event): void; } /** Core.Annotations.WidgetFlags: field flags (/Ff, GetWidgetFieldFlag / SetWidgetFieldFlag), read and written by name. */ /** Form field flags (/Ff) of a field, read and written by name. */ declare class WidgetFlags { /** The field is read-only. */ static readonly READ_ONLY = "ReadOnly"; /** The field must have a value when the form is submitted. */ static readonly REQUIRED = "Required"; /** The field is not exported when the form is submitted. */ static readonly NO_EXPORT = "NoExport"; /** Text field: the text can span multiple lines. */ static readonly MULTILINE = "Multiline"; /** Text field: the text is masked as a password. */ static readonly PASSWORD = "Password"; /** Text field: the text is split into equally spaced character cells (requires a maximum length). */ static readonly COMB = "Comb"; /** Radio button: exactly one button must be selected at all times. */ static readonly NO_TOGGLE_TO_OFF = "NoToggleToOff"; /** Button field: the field is a set of radio buttons. */ static readonly RADIO = "Radio"; /** Button field: the field is a push button. */ static readonly PUSH_BUTTON = "PushButton"; /** Choice field: the field is a combo box (otherwise a list box). */ static readonly COMBO = "Combo"; /** Combo box: the user can type a value of their own. */ static readonly EDIT = "Edit"; /** Text field: the text does not scroll beyond the visible area. */ static readonly DO_NOT_SCROLL = "DoNotScroll"; /** Radio buttons with the same export value turn on and off together. */ static readonly RADIOS_IN_UNISON = "RadiosInUnison"; /** Text field: the value is the path of a file to submit. */ static readonly FILE_SELECT = "FileSelect"; /** Text and choice fields: the text is not spell-checked. */ static readonly DO_NOT_SPELL_CHECK = "DoNotSpellCheck"; /** Text field: the value is rich text. */ static readonly RICH_TEXT = "RichText"; /** Choice field: the options are sorted. */ static readonly SORT = "Sort"; /** List box: more than one option can be selected. */ static readonly MULTI_SELECT = "MultiSelect"; /** Choice field: the value is committed as soon as the selection changes. */ static readonly COMMIT_ON_SEL_CHANGE = "CommitOnSelChange"; private readonly table; /** Takes the /Ff value; also accepts an options object: mask is the names this group of flags knows (for submit forms), onUpdate is unused, starting from 0. */ constructor(bits?: number | Record); /** * Whether a flag is set. * @param flag Flag name, such as WidgetFlags.READ_ONLY. * @returns True when set; false for unknown names. */ get(flag: string): boolean; /** Unknown names are ignored. */ set(flag: string, value?: boolean): void; } /** * Core.Annotations.WidgetAnnotation: base class of form widgets (CreateWidget / GetWidgetType / Get/SetWidgetFieldName ...). * Lives in Core.Annotations, not under Forms. Widgets with the same name belong to the same field (FieldManager groups by fieldName); * values are stored on each widget (widgetValue) and the field value is computed from its widgets. Widgets are displayed with the engine-generated appearance, with a border drawn before one exists. */ interface WidgetOption { value: string; displayValue: string; } /** Text alignment (quadding values, mapping to /Q 0 / 1 / 2). */ type WidgetQuadding = 'Left-justified' | 'Centered' | 'Right-justified'; /** Widget captions (captions: /CA /RC /AC of /MK); caption text for buttons, the ZapfDingbats check character for check boxes / radios. */ interface WidgetCaptions { Normal?: string; Rollover?: string; Down?: string; } declare class WidgetAnnotation extends HTMLAnnotation { /** * Events fired by widgets (these two of WidgetAnnotation.Events; commit / change / mouse* / render are not fired and not listed): * focus when the editor (text field, combo box, list) opens and blur when it closes. Check boxes / radios / buttons have no editor and fire neither. */ static readonly Events: { /** 'focus': the widget's editor opened. */ readonly FOCUS: "focus"; /** 'blur': the widget's editor closed. */ readonly BLUR: "blur"; }; elementName: string; isWidget(): boolean; private highlight; /** Explicit per-widget screen highlight. Does not change the field value, PDF or history. */ setHighlight(enabled: boolean): void; /** Undefined keeps the renderer's existing global/type default. */ getHighlight(): boolean | undefined; /** Fully qualified name of the form field this widget belongs to. */ fieldName: string; /** Form field flags (/Ff) of the field. */ fieldFlags: WidgetFlags; /** Widget rotation (/MK /R, 0 / 90 / 180 / 270 degrees; widget content rotates by it); note: the engine cannot write /MK /R, so changes are not saved to the file. */ rotation: number; private options; /** Form field indicator (shown by the UI layer) and its text; commit with updateAnnotation after changing. */ showIndicator: boolean; /** Text of the form field indicator. */ indicatorText: string; private field; /** Internal: text font, size and color (/DA); for new widgets the engine writes Helvetica 12 black. */ private widgetFont; /** * Text alignment ('Left-justified' / 'Centered' / 'Right-justified', mapping to /Q); written to the file for text fields, combo boxes and lists. * The style (bold / italic) is in the font name (Helvetica-Bold, Times-Italic, etc.); see font. */ quadding: WidgetQuadding; private readonly widgetCaptions; /** * Captions (a read-only object; change its keys). Normal is written to the file: the button text for buttons (/MK /CA), the check style * ZapfDingbats character for check boxes / radios: '4' check, 'l' circle, '8' cross, 'u' diamond, 'n' square, 'H' star (the engine only knows these six); Rollover / Down only go with XFDF. */ get captions(): WidgetCaptions; /** Text font; a copy is made on assignment. */ get font(): Font; set font(font: Font | FontOptions | string); /** Font size (pt), 0 is automatic (simply font.size). */ get FontSize(): number; set FontSize(size: number | string); /** Text color (reads the font fill color; writes change fill and stroke colors together). */ get TextColor(): Color; set TextColor(color: Color | ColorInput); /** When created with a field: the field name, initial value and flags carry over to the widget. */ constructor(field?: Field | null, init?: AnnotationInit); /** * Gets the form field this widget belongs to. * @returns The field, or null when none. */ getField(): Field | null; /** * Sets the form field this widget belongs to. * @param field The field. */ setField(field: Field): void; /** * Gets the name of the form field this widget belongs to. * @returns The field name. */ getFieldName(): string; /** * Gets the form field flags. * @returns The flags. */ getFieldFlags(): WidgetFlags; /** * Sets a form field flag; commit with updateAnnotation afterwards. * @param flag Flag name, such as WidgetFlags.READ_ONLY. * @param value Whether the flag is set. */ setFieldFlag(flag: string, value: boolean): void; /** Indicator (the same fields as FormFieldCreationManager.setShowIndicator / setIndicatorText); commit with updateAnnotation afterwards. */ setFieldIndicator(show: boolean, text?: string): void; /** Options of combo boxes / lists. */ getFieldOptions(): WidgetOption[]; /** Commit with updateAnnotation after changing. */ setFieldOptions(options: WidgetOption[]): void; /** Default value (/DV): readable and writable for text fields and combo boxes / lists, others read an empty string; commit with updateAnnotation after changing. */ get defaultValue(): string; set defaultValue(value: string | number); /** Property form of getValue / setValue; a failed assignment only logs a warning (use setValue to await the result). */ get value(): FieldValue; set value(value: FieldValue); /** Alias of fieldFlags. */ get flags(): WidgetFlags; set flags(flags: WidgetFlags); /** Sets several properties at once: fieldName, value, defaultValue, flags; missing ones are ignored. */ set(options?: { /** New field name. */ fieldName?: string; /** New value. */ value?: FieldValue; /** New default value. */ defaultValue?: string | number; /** New field flags. */ flags?: WidgetFlags; }): void; /** Value of the owning field; the widget's own value when there is no field yet. */ getValue(): FieldValue; /** Sets the value of the owning field (Field.setValue). */ setValue(value: FieldValue): Promise; /** Redraws this widget. */ refresh(): void; /** Placeholder before the appearance arrives (including while drawing): the background color first if any, the border inside the rectangle matching the engine appearance; no border when its width is 0. */ draw(ctx: CanvasRenderingContext2D, _pageMatrix: Matrix): void; } /** * Core.Annotations.Forms.Field: a form field, the set of widgets with the same name. Its value comes from the widgets: text / choices use the first widget's value, * buttons use the checked widget's export value ('Off' when none is checked). setValue changes each widget's value, fires fieldChanged right away, then commits each with updateAnnotation. */ type FieldType = 'Tx' | 'Btn' | 'Ch' | 'Sig'; type FieldValue = string | number | boolean | string[] | null; /** A form field: the set of widgets that share a name and a value. */ declare class Field { name: string; /** Widgets (form field annotations) of this field. */ readonly widgets: WidgetAnnotation[]; /** Field type: 'Tx' (text), 'Btn' (button, check box, radio), 'Ch' (choice) or 'Sig' (signature). */ readonly type: FieldType; /** Initial value and flags given when creating the field (options): widgets created with this field carry them. */ readonly initialValue: FieldValue | undefined; /** Field flags given when creating the field; widgets created with this field carry them. */ readonly initialFlags: WidgetFlags | undefined; /** * The second argument is the type, or the options { type, value, flags }. * @param name Fully qualified name of the field. * @param options The field type, or the type, initial value and flags. */ constructor(name: string, options?: FieldType | { /** Field type; 'Tx' by default. */ type?: FieldType; /** Initial value. */ value?: FieldValue; /** Initial field flags. */ flags?: WidgetFlags; }); /** The user this field belongs to (exported and imported with the XFDF field definition, not written to the PDF). */ getUser(): string; /** * Sets the user this field belongs to (exported and imported with the XFDF field definition, not written to the PDF). * @param user The user name. */ setUser(user: string): void; private user; /** * Gets the field type. * @returns 'Tx', 'Btn', 'Ch' or 'Sig'. */ getFieldType(): FieldType; /** Property form of getValue / setValue; on assignment a failed commit (such as in read-only mode) only logs a warning; use setValue / commit to await the result. */ get value(): FieldValue; set value(value: FieldValue); /** Same as setValue (commit may also run validation actions, but there are no scripts here, so it just sets the value); widget is only a hint, the value belongs to the whole field. */ commit(value: FieldValue, _widget?: WidgetAnnotation): Promise; /** Field flags: those of the first widget (or those given at creation without widgets); on assignment each widget gets a copy, then updateAnnotation commits. */ get flags(): WidgetFlags; set flags(flags: WidgetFlags); /** Options of combo boxes / lists; always null for other types. On assignment written to each widget, then updateAnnotation commits. */ get options(): Array<{ /** Export value of the option. */ value: string; /** Text shown for the option. */ displayValue: string; }> | null; set options(options: Array<{ /** Export value of the option. */ value: string; /** Text shown for the option; defaults to value. */ displayValue?: string; }> | null); /** Child fields: fields here hold widgets directly with no child fields, so always an empty array. */ get children(): Field[]; /** Property form of getActions. */ get actions(): Record; /** Some widget has uncommitted changes. */ get IsModified(): boolean; /** Text alignment: that of the first widget. */ get quadding(): string; /** Export value: the first widget's export value for buttons, otherwise the field value. */ get exportValue(): FieldValue; /** * Default value (/DV): readable and writable (a text string) for text fields and combo boxes / lists; for check boxes / radios /DV is a name, which the Worker does not write, and reads as an empty string. * On assignment written to each widget, then updateAnnotation commits. */ get defaultValue(): string; set defaultValue(value: string | number); /** Tooltip (/TU); on assignment written to each widget, then updateAnnotation commits. */ get tooltipName(): string; set tooltipName(text: string); /** Sets several properties at once: value (set directly), defaultValue, tooltipName, flags, options; missing ones are ignored. */ set(options: { /** New value. */ value?: FieldValue; /** New default value. */ defaultValue?: string | number; /** New tooltip (alternate name). */ tooltipName?: string; /** New field flags. */ flags?: WidgetFlags; /** New options of combo boxes and lists. */ options?: Array<{ /** Export value of the option. */ value: string; /** Text shown for the option; defaults to value. */ displayValue?: string; }> | null; }): void; /** * An array of selected values for multi-select lists, otherwise a string. * @example * ```js * const { annotationManager } = instance.Core; * annotationManager.addEventListener('fieldChanged', (field, value) => { * console.log(field.name, value, field.getValue()); * }); * ``` */ getValue(): FieldValue; /** * Buttons: widgets whose export value equals the value are checked, the rest unchecked; true checks the first widget (check box), false / null unchecks all. * Rejects in read-only mode without changing any widget. * @example * ```js * const { annotationManager } = instance.Core; * const fieldManager = annotationManager.getFieldManager(); * await fieldManager.getField('name').setValue('Jane Doe'); // text field * await fieldManager.getField('agree').setValue(true); // check box * await fieldManager.getField('country').setValue('France'); // combo box * ``` */ setValue(value: FieldValue): Promise; /** Combo boxes / lists: an array selects multiple; null / empty string / false clears. */ private setChoice; /** Font of the field: taken from the first widget (the engine reads and writes /DA on widgets); an empty font without widgets. */ get font(): Font; /** Actions of the field: those on the first widget (button click actions and so on). */ getActions(): Record; /** Shows all widgets of the field. */ show(): Promise; /** Hides all widgets of the field. */ hide(): Promise; /** Fields here hold widgets directly with no child fields. */ isTerminal(): boolean; /** Redraws each widget (the appearance is regenerated by the engine after every write). */ refreshAppearances(): void; } /** * AnnotationManager.prototype.Alignment: align / center / distribute, computed from the common bounding box of the selected annotations in plain JS; * text markup (attached to text) and NoMove annotations do not move. Afterwards each is committed with updateAnnotation and reselected. */ /** Edge alignment types. */ declare enum StandardAlignmentTypes { /** Align the left edges. */ LEFT = "left", /** Align the right edges. */ RIGHT = "right", /** Align the top edges. */ TOP = "top", /** Align the bottom edges. */ BOTTOM = "bottom" } /** Center alignment types. */ declare enum CenterAlignmentTypes { /** Align the vertical centers. */ CENTER_VERTICAL = "centerVertical", /** Align the horizontal centers. */ CENTER_HORIZONTAL = "centerHorizontal", /** Align both centers. */ CENTER = "center" } /** Distribution types. */ declare enum DistributeAlignmentTypes { /** Distribute evenly in the vertical direction. */ DISTRIBUTE_VERTICAL = "distributeVertical", /** Distribute evenly in the horizontal direction. */ DISTRIBUTE_HORIZONTAL = "distributeHorizontal" } declare class Alignment { readonly manager: AnnotationManager; /** The three groups of alignment types (also on the instance; the alignment dialog reads the constants from annotationManager.Alignment; the same object as the static members of AnnotationManager). */ readonly StandardAlignmentTypes: typeof StandardAlignmentTypes; readonly CenterAlignmentTypes: typeof CenterAlignmentTypes; readonly DistributeAlignmentTypes: typeof DistributeAlignmentTypes; constructor(manager: AnnotationManager); /** Aligns the left / right / top / bottom edges to that edge of the common bounding box. */ alignAnnotations(annotations: Annotation$1[], type: StandardAlignmentTypes): void; /** Aligns centers to the center lines of the common bounding box (CENTER_VERTICAL: vertical center line, CENTER_HORIZONTAL: horizontal center line, CENTER: both). */ centerAnnotations(annotations: Annotation$1[], type: CenterAlignmentTypes): void; /** The first and last stay; the ones in between are spaced evenly. */ distributeAnnotations(annotations: Annotation$1[], type: DistributeAlignmentTypes): void; private movable; private commit; } /** * Core.EditBoxManager: annotationManager.getEditBoxManager(). Annotations are drawn on canvas; editing puts a form element over the viewer element: * free text is edited inline in a textarea; text fields use input (textarea for multiline, password for password fields); combo boxes / lists use select. * Only one is open at a time; it commits on blur, Enter (single line) or option selection, Escape abandons (Escape also commits for free text), Tab commits and moves to the next fillable widget. * Keyboard events stop propagating so Delete / Backspace do not delete the selected annotation. */ interface FocusBoxOptions { } /** Manages the in-place editors of free text annotations and fillable form fields (text fields, combo boxes and lists). Only one editor is open at a time. */ declare class EditBoxManager { private readonly annotationManager?; private readonly docViewer?; private open; private readonly focusEditorColors; /** * Creates an edit box manager (normally obtained from AnnotationManager.getEditBoxManager). * @param annotationManager The annotation manager whose annotations are edited. * @param docViewer The document viewer the editors are placed on. */ constructor(annotationManager?: AnnotationManager | undefined, docViewer?: DocumentViewer | undefined); /** Opens the editor for this annotation (committing an open one first); does nothing for types that cannot be edited. */ focusBox(annotation: Annotation$1, options?: FocusBoxOptions): void; /** The open editor; opens one when none is open. */ getEditor(annotation: Annotation$1): HTMLElement | null; /** * Gets the editor element open for an annotation. * @param annotation The annotation. * @returns The editor element, or null when no editor is open for it. */ getExistingEditor(annotation: Annotation$1): HTMLElement | null; /** After the annotation's position or the zoom changes, refits the open editor to the annotation. */ resizeAnnotation(annotation: Annotation$1): void; /** Keep the same input and geometry; the canvas form cue replaces only the editor's blue accent. */ refreshFormFieldFocusOutline(): void; /** Whether the text field editor uses comb layout: Comb + MaxLen; not for multiline or password fields (PDF specification). */ private isCombEditor; /** * Comb field editor: monospaced text with letter spacing of exactly one cell (width / MaxLen) and half a cell on the left, so each character sits in the center of its cell; * tick marks between cells are drawn at the bottom of the box; the box has a white background over the original appearance, so the ticks are drawn here. * The border uses outline, since border would eat into the width and misalign the cells. * With half a cell on the left the content is half a cell wider than the box, and when full the browser would scroll the box to show the caret and push out the first character, * so the box gets that extra half cell on the right (the content fits exactly without scrolling). */ private combStyle; /** * Position and size of the editor within the viewer element (at the current zoom); for free text with a callout it covers the text box. * Rotated ones (box-rotated free text) cover the unrotated box and rotate around the center (a counterclockwise angle on the page keeps its direction on screen, also with view rotation in multiples of 90°). */ private place; private mount; private editFreeText; private editWidget; /** The press that opened the editor: a combo box opens its dropdown; a list selects the clicked item (the editor has just covered it, which would otherwise need another click). */ private applyPress; /** The next widget fillable with an editor in Tab order. */ private nextWidget; private show; /** Removes the editor; returns false when already removed. */ private release; } /** * Core.FormFieldCreationManager: annotationManager.getFormFieldCreationManager(). Form field creation mode: * clicking a widget in this mode selects it (to drag or resize) instead of filling it; other annotations are hidden by default. Widgets are real fields (CreateWidget); no placeholder annotations are created. * Ending is refused while some fields have no name, and formFieldCreationEmptyFieldNames fires. * Indicators are widget fields (showIndicator / indicatorText, saved with the file); * all buttons of a radio group are set together; they are committed here (updateAnnotation) and saved with the file and XFDF. Showing indicators belongs to the UI layer; core does not draw them. */ interface FormFieldCreationManagerEvents { formFieldCreationModeStarted: []; formFieldCreationModeEnded: []; formFieldCreationEmptyFieldNames: []; } declare class FormFieldCreationManager extends EventHandler { private readonly annotationManager?; private readonly docViewer?; /** Event names of the form field creation manager. */ static readonly Events: { /** 'formFieldCreationModeStarted': form field creation mode was entered. */ readonly FORM_CREATION_STARTED: "formFieldCreationModeStarted"; /** 'formFieldCreationModeEnded': form field creation mode was left. */ readonly FORM_CREATION_ENDED: "formFieldCreationModeEnded"; /** 'formFieldCreationEmptyFieldNames': form field creation mode could not end because some fields have no name. */ readonly FORM_CREATION_EMPTY_FIELD_NAMES: "formFieldCreationEmptyFieldNames"; }; private active; private showingMarkup; private clickToCreate; private readonly clickSizes; private readonly allowed; /** * Creates a form field creation manager (normally obtained from AnnotationManager.getFormFieldCreationManager). * @param annotationManager The annotation manager whose widgets are edited. * @param docViewer The document viewer to redraw. */ constructor(annotationManager?: AnnotationManager | undefined, docViewer?: DocumentViewer | undefined); /** Enters form field creation mode: widgets become editable as annotations instead of fillable fields. Fires formFieldCreationModeStarted; does nothing if already in the mode. */ startFormFieldCreationMode(): void; /** Does not end while some fields have no name; fires formFieldCreationEmptyFieldNames. */ endFormFieldCreationMode(): Promise; /** * Whether form field creation mode is on. * @returns True in form field creation mode. */ isInFormFieldCreationMode(): boolean; /** * Changes a widget's field name and commits; returns whether the name is usable: empty after trimming is empty (still set, used to clear); * a name used by another field is duplicate (not changed), except that radio buttons may join a radio group of the same name, but not a non-radio field with that name. * For non-radio widgets the whole field is renamed (all widgets of the field together). */ setFieldName(annotation: WidgetAnnotation, name: string): { /** Whether the name was accepted. */ isValid: boolean; /** Why the name was not accepted, or null when it was. */ errorType: 'empty' | 'duplicate' | null; }; /** Field name of the radio group. */ getRadioButtonGroups(): string[]; /** * Allows tools to be used in form field creation mode. * @param names Tool names to allow. */ allowToolsInFormFieldCreationMode(names: string[]): void; /** * Disallows tools in form field creation mode. * @param names Tool names to disallow. */ disallowToolsInFormFieldCreationMode(names: string[]): void; /** * Whether a tool can be used in form field creation mode. * @param name The tool name. * @returns True when the tool is allowed. */ isToolAllowedInFormFieldCreationMode(name: string): boolean; /** * Whether the indicator is shown for a widget in form field creation mode. * @param annotation The widget. * @returns True when the indicator is shown. */ getShowIndicator(annotation: WidgetAnnotation): boolean; /** * Shows or hides the indicator of a widget in form field creation mode (for radio buttons, the whole group) and commits. * @param annotation The widget. * @param show Whether to show the indicator. */ setShowIndicator(annotation: WidgetAnnotation, show: boolean): void; /** * Gets the indicator text of a widget in form field creation mode. * @param annotation The widget. * @returns The indicator text. */ getIndicatorText(annotation: WidgetAnnotation): string; /** * Sets the indicator text of a widget in form field creation mode (for radio buttons, the whole group) and commits. * @param annotation The widget. * @param text The indicator text. */ setIndicatorText(annotation: WidgetAnnotation, text: string): void; /** Changes the widget and commits; for radio buttons the whole group is changed. */ private setOnGroup; /** * Switch for adding form fields with a click (off by default: a click adds nothing, only dragging out a box does). When on, a click adds one at the default size, which can be changed per tool (setClickCreateSize). */ enableClickToCreate(): void; /** Turns off adding form fields with a single click (the default); fields are drawn by dragging. */ disableClickToCreate(): void; /** * Whether form fields can be added with a single click. * @returns True when click-to-create is on. */ isClickToCreateEnabled(): boolean; /** Changes the default size (pt) of a form field tool (such as TextFormFieldCreateTool) when adding with a click. */ setClickCreateSize(toolName: string, size: [number, number]): void; /** Default size of a form field tool when adding with a click: the changed size if changed, otherwise the tool's own default; undefined when not a form field tool. */ getClickCreateSize(toolName: string): [number, number] | undefined; /** Also shows other annotations in creation mode (shown by default, just not selectable or editable; call disable to hide them). */ enableShowingMarkupAnnotations(): void; /** Hides markup annotations while in form field creation mode. */ disableShowingMarkupAnnotations(): void; /** * Whether markup annotations are shown in form field creation mode. * @returns True when shown (the default). */ isShowingMarkupAnnotations(): boolean; private widgets; } /** * Core.Annotations.Forms.FieldManager: annotationManager.getFieldManager(). * Fields group widgets by fieldName and are recomputed from the current annotation list on every query (field objects are reused by name); widgets without a name (radios under a parent field cannot read their name) form their own field keyed by annotation Id. * Known limitations: no calculated fields, formatting or validation. */ /** Manages the form fields of the document; fields group the widgets that share a field name. */ declare class FieldManager { private readonly annotationManager?; private readonly fields; /** Fields added by addField: kept even without widgets. */ private readonly added; /** Regrouped right after annotations are added, deleted or modified (including reads and imports), so widgets' getField() always works. */ constructor(annotationManager?: AnnotationManager | undefined); /** Goes to the page of the field's first widget and centers it (does nothing without widgets); options as in AnnotationManager#jumpToAnnotation. */ jumpToField(field: Field, options?: JumpOptions): void; /** The named action Print and form script printing go to it (only a warning is logged when unset). */ setPrintHandler(handler: (() => void) | null): void; /** Form script alert boxes go to it (window.alert when unset). */ setAlertHandler(handler: ((message: string) => void) | null): void; private printHandler; private alertHandler; /** * Gets a field by its fully qualified name. * @param name The field name. * @returns The field, or null when not found. * @example * ```js * const { annotationManager } = instance.Core; * const fieldManager = annotationManager.getFieldManager(); * const field = fieldManager.getField('address.city'); * if (field) * console.log(field.getValue()); * ``` */ getField(name: string): Field | null; /** * Gets all fields. * @returns The fields. * @example * ```js * const { annotationManager } = instance.Core; * for (const field of annotationManager.getFieldManager().getFields()) * console.log(field.name, field.getFieldType(), field.getValue()); * ``` */ getFields(): Field[]; /** * Adds a field; it is kept even when it has no widgets. * @param field The field to add. */ addField(field: Field): void; /** * Gets a field by name, creating and adding it when it does not exist. * @param name The field name. * @param type Field type of a new field: 'Tx', 'Btn', 'Ch' or 'Sig'. * @returns The existing or new field. */ getOrCreateField(name: string, type: string): Field; /** Renames a field: the widgets' fieldName changes too and is committed; joins an existing field with the new name if there is one. */ updateFieldName(field: Field, name: string): void; /** Fields of this user (Field.getUser equals it). */ getFieldsForUser(user: string): Field[]; private widgetHighlighting; /** * Whether fillable widgets are highlighted. * @returns True when highlighting is on (the default). */ isWidgetHighlightingEnabled(): boolean; /** Highlights fillable widgets (except buttons) on screen and fires widgetHighlightingChanged. */ enableWidgetHighlighting(): void; /** Turns off widget highlighting and fires widgetHighlightingChanged. */ disableWidgetHighlighting(): void; private setWidgetHighlighting; private calculationOrder; /** * Gets the calculation order of fields (/AcroForm /CO). Only stored; calculations are not run. * @returns Field names in calculation order. */ getCalculationOrder(): string[]; /** Written to /AcroForm /CO on save (field names not in the file are removed), and as when exporting XFDF. */ setCalculationOrder(order: string[]): void; /** All required (Required) fields have values (neither an empty string nor 'Off'). */ areRequiredFieldsFilled(): boolean; /** Regroups by the current annotation list. */ private sync; } /** * Core.Scale: a scale where pageScale on the page corresponds to the real-world worldScale. * new Scale([[1, 'in'], [2, 'ft']]), new Scale('1 in = 2 ft') and new Scale({ pageScale, worldScale }) are equivalent; * precision is the precision of results (0.01 means two decimals). */ type ScaleRatio = [[number, string], [number, string]]; interface ScaleUnit { value: number; unit: string; } /** Measurement scale: `pageScale` on the page corresponds to `worldScale` in the real world. */ declare class Scale { precision?: number | undefined; /** Length on the page and its unit. Value 0 and an empty unit when the input could not be parsed. */ pageScale: ScaleUnit; /** Real-world length and its unit. Value 0 and an empty unit when the input could not be parsed. */ worldScale: ScaleUnit; /** * Creates a scale. `[[1, 'in'], [2, 'ft']]`, `'1 in = 2 ft'` and `{ pageScale, worldScale }` are equivalent. * @param scale Scale as a ratio array, a 'value unit = value unit' string, or a pageScale / worldScale object. * @param precision Precision of measured values; 0.01 means two decimals. */ constructor(scale: ScaleRatio | string | { /** Length on the page and its unit. */ pageScale: ScaleUnit; /** Corresponding real-world length and its unit. */ worldScale: ScaleUnit; }, precision?: number | undefined); /** * Returns the scale as a ratio array. * @returns `[[pageValue, pageUnit], [worldValue, worldUnit]]`. */ getScaleRatioAsArray(): ScaleRatio; /** * Returns the scale as text. * @returns A string such as '1 in = 2 ft'. */ toString(): string; /** Both sides have a positive value and a unit. */ isValid(): boolean; /** * Formats by precision: decimal getFormattedValue(1.2345, 'ft', 0.01) → '1.23 ft'; * inches and feet-inches use fractions when the precision is 1/8, 1/16, 1/32 or 1/64: (2.0833, 'in', 0.125) → '2 ⅛"', (2.0833, 'ft-in', 0.125) → '2\'-1"'; * feet-inches with decimals is '2ft-1.00in'. With useUnicodeFraction false, fractions are written as 1/8 (standard fonts cannot draw characters such as ⅛); * with showZero true, zero inches are written too ('2 0', '2ft-0.00in'). */ static getFormattedValue(value: number, unit: string, precision?: number, useUnicodeFraction?: boolean, showZero?: boolean): string; } /** Core.Annotations.MarkupAnnotation: base class of annotations with author, content and replies; Measure / Scale / Precision of measurement annotations are here too. */ type MeasureType = 'distance' | 'perimeter' | 'area' | 'angle' | 'count' | 'arc' | 'curve'; /** Measurement info: kind, scale string ("1 in = 1 ft"), precision (0.01 for two decimals); value / text are results computed by the engine (read-only). */ interface MeasureData { type: MeasureType; scale: string; precision: number; value?: number; text?: string; } declare class MarkupAnnotation extends Annotation$1 { elementName: string; /** Internal: measurement info; when type is missing it is filled in from the annotation type on read (the subclass elementName is not assigned yet when set in the constructor). */ private measureData; /** * Creates a markup annotation. * @param init Initial property values. */ constructor(init?: AnnotationInit); /** Measurement info of a measurement annotation; null when not a measurement annotation. */ get Measure(): MeasureData | null; set Measure(measure: MeasureData | null); /** Scale [[page value, unit], [real value, unit]]; when set without measurement info, one is created from the annotation type. */ get Scale(): ScaleRatio | null; set Scale(ratio: ScaleRatio | null); /** Result precision (0.01 for two decimals). */ get Precision(): number | null; set Precision(precision: number | null); /** Measurement result text (such as "L = 1.00 ft"), generated by the engine; an empty string when not a measurement annotation. */ getMeasurementTextWithScaleAndUnits(): string; /** Sets stroke / fill / opacity of ctx for subclasses' draw(). */ setStyles(ctx: CanvasRenderingContext2D, _pageMatrix: Matrix): void; } type StickyStateModel = 'Review' | 'Marked'; declare class StickyAnnotation extends MarkupAnnotation { /** Icon names of sticky notes. */ static readonly IconNames: { /** Insert icon. */ readonly INSERT: "Insert"; /** Circle icon. */ readonly CIRCLE: "Circle"; /** New paragraph icon. */ readonly NEW_PARAGRAPH: "NewParagraph"; /** Help (question mark) icon. */ readonly HELP: "Help"; /** Key icon. */ readonly KEY: "Key"; /** Check icon. */ readonly CHECK: "Check"; /** Checkmark icon. */ readonly CHECKMARK: "Checkmark"; /** Cross icon. */ readonly CROSS: "Cross"; /** Crosshairs icon. */ readonly CROSS_HAIRS: "CrossHair"; /** Paragraph icon. */ readonly PARAGRAPH: "Paragraph"; /** Right arrow icon. */ readonly RIGHT_ARROW: "RightArrow"; /** Right pointer icon. */ readonly RIGHT_POINTER: "RightPointer"; /** Star icon. */ readonly STAR: "Star"; /** Up arrow icon. */ readonly UP_ARROW: "UpArrow"; /** Up-left arrow icon. */ readonly UP_LEFT_ARROW: "UpLeftArrow"; /** Comment (speech bubble); also used for unknown icon names icon. */ readonly COMMENT: "Comment"; }; /** Size of new notes (static SIZE; only affects notes created afterwards, existing ones keep their own rectangle). */ static get SIZE(): number; static set SIZE(value: number); elementName: string; NoZoom: boolean; NoRotate: boolean; Width: number; Height: number; /** * Creates a sticky note annotation (NoZoom and NoRotate, StickyAnnotation.SIZE wide and high). * @param init Initial property values. */ constructor(init?: AnnotationInit); /** Accepted / Rejected / Cancelled / Completed / None (Review model), Marked / Unmarked (Marked model). */ State: string; /** State model of a review state reply: 'Review' or 'Marked'; an empty string when the note is not a state reply. */ StateModel: StickyStateModel | ''; /** * Gets the review state. * @returns The state; an empty string when none. */ getState(): string; /** * Sets the review state (commit with updateAnnotation afterwards). * @param state The state, such as 'Accepted' or 'Marked'. */ setState(state: string): void; /** * Gets the state model. * @returns 'Review', 'Marked', or an empty string when none. */ getStateModel(): StickyStateModel | ''; /** * Sets the state model. * @param model 'Review' or 'Marked'. */ setStateModel(model: StickyStateModel): void; /** * Draws the icon (StickyAnnotation.draw): black outline filled with the note color, top-left at (X, Y), scaled to the note size; replies are not drawn. * With NoZoom the viewer first scales the canvas by 1 / zoom, and this draws in page coordinates as usual. */ draw(ctx: CanvasRenderingContext2D, _pageMatrix?: Matrix): void; } /** * Result text options of area measurements (measurementCaptionOptions): { isEnabled, captionRect, captionOffset, captionStyle }, * captionStyle is { fontFamily, color, staticSize, maximumSize }. Kept in memory only as JSON (MarkupAnnotation.measurementCaption, * captionRect written as "x1,y1,x2,y2"). * The result text is drawn by the engine appearance from /DA (font, size, color); these three are computed here: the size is staticSize (when greater than 0), * otherwise (width + height) / 30, capped at maximumSize (when greater than 0); the color defaults to the stroke color; the font maps the CSS font family to a standard font. */ interface MeasurementCaptionStyle { fontFamily: string; color: string; staticSize: string; maximumSize: string; } interface MeasurementCaptionOptions { isEnabled: boolean; captionRect: Rect; captionOffset?: { x: number; y: number; }; captionStyle: MeasurementCaptionStyle; } type MeasurementCaptionOptionsInput = Partial> & { captionStyle?: Partial; }; /** * Which items the measurement result text shows (the check boxes of the measurement settings). Area measurements (polygon, rectangle): perimeter, area; circle: radius, perimeter, area; * arc: radius, arc length, angle. Kept in memory only (MarkupAnnotation.measurementDisplay, JSON); the defaults apply when nothing is set. * Each item is one line in a fixed order; no text when nothing is selected. */ interface MeasurementDisplayOptions { /** Circle, arc. */ radius?: boolean; /** Polygon, rectangle, circle. */ perimeter?: boolean; /** Polygon, rectangle, circle. */ area?: boolean; /** Arc. */ arcLength?: boolean; /** Arc. */ angle?: boolean; } declare class FreeHandAnnotation extends MarkupAnnotation { /** Values of the ink intent (see setIntent). */ static readonly Intent: { /** Highlighter ink, drawn with multiply blending. */ readonly InkHighlight: "InkHighlight"; }; elementName: string; /** Result text style (changed in the style panel; an empty string / null means unchanged: the engine default Helvetica 9 black); see MeasureTextStyle in utils/measurement-caption.ts. */ Font: string; /** Font size of the measurement result text in points, as a string; an empty string keeps the default. */ FontSize: string; /** Color of the measurement result text; null keeps the default. */ TextColor: Color | null; /** Intent (/IT); null when none. */ private intent; /** The 4 control points of a curve measurement (Measure.type curve); the paths are the curve sampled from them. */ private curvePoints; /** * Whether this ink annotation is a curve measurement. * @returns True for a curve measurement. */ isCurveMeasure(): boolean; /** Control points of a curve measurement (start, two middle control points, end); null when not a curve measurement. */ getCurveControlPoints(): Point[] | null; /** Sets the control points: the paths are resampled along the curve, and the bounding box and result text are recomputed. */ setCurveControlPoints(points: Point[]): void; /** * Moves one control point of a curve measurement; the curve is resampled. Does nothing when not a curve measurement or the index is out of range. * @param index Zero-based control point index (0 to 3). * @param x X in PDF points. * @param y Y in PDF points. */ setCurveControlPoint(index: number, x: number, y: number): void; /** Which items the result text of arc measurements shows: radius, arcLength, angle; only the angle by default; undefined when not an arc measurement. */ getMeasurementDisplayOptions(): MeasurementDisplayOptions | undefined; /** Changes only the given keys (inapplicable ones are ignored); then updateAnnotation commits and the result text and appearance are rewritten. */ setMeasurementDisplayOptions(options: MeasurementDisplayOptions): void; /** Curve length (real units); undefined when the scale is invalid. */ getCurveLength(): number | undefined; /** Result text ('1.2cm', the value followed immediately by the unit); feet-inches use feet. */ getCurveContents(): string; /** * Recomputes the result text from the current control points and scale, and records control points, scale, precision and text style in custom data (the engine does not know curve measurement, as with ellipse measurement). * Called by AnnotationManager on save. */ adjustCurve(): void; /** Read back: restores a curve measurement from custom data (the file holds a sampled ink; control points and scale are in custom data). */ restoreCurve(): void; /** * A highlighter when init.intent is InkHighlight. * @example * ```js * const { annotationManager, Annotations, Math: CoreMath } = instance.Core; * const ink = new Annotations.FreeHandAnnotation({ PageNumber: 1 }); * ink.setPath([new CoreMath.Point(100, 100), new CoreMath.Point(150, 130), new CoreMath.Point(200, 100)], 0); * ink.setPath([new CoreMath.Point(100, 160), new CoreMath.Point(200, 160)], 1); // a second stroke * ink.StrokeColor = new Annotations.Color(0, 128, 0); * ink.StrokeThickness = 3; * await annotationManager.addAnnotation(ink); // the bounding box is computed from the strokes * ``` */ constructor(init?: AnnotationInit & { /** Ink intent (/IT), such as 'InkHighlight'. */ intent?: string; }); /** * Gets the ink intent (/IT). * @returns The intent, such as 'InkHighlight', or null when none. */ getIntent(): string | null; /** Setting InkHighlight changes BlendMode to multiply (other intents leave BlendMode unchanged). */ setIntent(intent: string | null): void; /** Internal: paths (/InkList). */ protected paths: Point[][]; /** simplifyPaths simplifies only when true (turned on when a stylus stroke ends). */ shouldSimplifyPath: boolean; setRect(rect: Rect): void; /** * Gets all strokes. * @returns The strokes, each an array of points in page coordinates (the internal array, not a copy). */ getPaths(): Point[][]; /** * Gets one stroke. * @param index Zero-based stroke index; defaults to 0. * @returns The points of the stroke; an empty array when it does not exist. */ getPath(index?: number): Point[]; /** * Replaces one stroke. Call adjustRect afterwards to update the bounding box. * @param points The points of the stroke in page coordinates. * @param index Zero-based stroke index; defaults to 0. */ setPath(points: Point[], index?: number): void; /** * Gets one point of a stroke. * @param pathIndex Zero-based stroke index. * @param pointIndex Zero-based point index. * @returns The point, or undefined when it does not exist. */ getPathPoint(pathIndex: number, pointIndex: number): Point | undefined; /** * Sets one point of a stroke (creating the stroke if needed). * @param pathIndex Zero-based stroke index. * @param pointIndex Zero-based point index. * @param x X in PDF points. * @param y Y in PDF points. */ setPathPoint(pathIndex: number, pointIndex: number, x: number, y: number): void; /** Appends to the last path when index is omitted. */ addPathPoint(x: number, y: number, index?: number): void; /** Removes the last stroke. */ popPath(): void; /** Removes all strokes. */ emptyPaths(): void; /** Rotates by radians around the bounding box center (or center); Rotation follows and the bounding box is recomputed from the points. */ rotate(radians: number, center?: { /** X of the rotation center in PDF points. */ x: number; /** Y of the rotation center in PDF points. */ y: number; }): void; adjustRect(): void; getRectPadding(): number; /** The path of an arc length measurement (Measure.type arc) is three points: start, a point on the arc, end, drawn as the arc through them (sketch before the three points are fixed: see below). */ draw(ctx: CanvasRenderingContext2D, pageMatrix: Matrix): void; /** Result text of a curve measurement: centered on the curve midpoint, along the curve direction (turned upright when pointing left), above the line. */ private drawCurveCaption; } /** * Core.Annotations.StampAnnotation: CreateAnnot(kStamp). Standard stamps: Icon is the stamp name (SetStandardStamp); * when width or height is 0, (X, Y) is treated as the center with the stamp's natural size, and the actual rectangle is fetched after the Worker confirms; * image stamps: setImageData(dataURL) decodes to RGBA on the main thread and is written with the commit (SetImageStampWithPixel). Display uses the appearance bitmap (RenderAnnot). * Text stamps: setStampText (SetTextStamp). For image stamps read from the file, getImageData gives a PNG rendered from the appearance (not the original image in the file). */ declare const TEXT_STAMP_COLOR: Readonly<{ /** White background. */ readonly WHITE: "white"; /** Red background. */ readonly RED: "red"; /** Green background. */ readonly GREEN: "green"; /** Blue background. */ readonly BLUE: "blue"; }>; declare const TEXT_STAMP_SHAPE: Readonly<{ /** Rectangle. */ readonly RECTANGLE: "rectangle"; /** Rectangle with a triangle pointing left. */ readonly LEFT_TRIANGLE: "leftTriangle"; /** Rectangle with a triangle pointing right. */ readonly RIGHT_TRIANGLE: "rightTriangle"; /** No border shape. */ readonly NONE: "none"; }>; /** Background color of a text stamp: 'white', 'red', 'green' or 'blue'. */ type TextStampColor = typeof TEXT_STAMP_COLOR[keyof typeof TEXT_STAMP_COLOR]; /** Shape of a text stamp: 'rectangle', 'leftTriangle', 'rightTriangle' or 'none'. */ type TextStampShape = typeof TEXT_STAMP_SHAPE[keyof typeof TEXT_STAMP_SHAPE]; declare class StampAnnotation extends MarkupAnnotation { /** Background colors of text stamps (the engine has only these four). */ static readonly TextStampColor: Readonly<{ /** White background. */ readonly WHITE: "white"; /** Red background. */ readonly RED: "red"; /** Green background. */ readonly GREEN: "green"; /** Blue background. */ readonly BLUE: "blue"; }>; /** Shapes of text stamps: rectangle / left arrow / right arrow / no border. */ static readonly TextStampShape: Readonly<{ /** Rectangle. */ readonly RECTANGLE: "rectangle"; /** Rectangle with a triangle pointing left. */ readonly LEFT_TRIANGLE: "leftTriangle"; /** Rectangle with a triangle pointing right. */ readonly RIGHT_TRIANGLE: "rightTriangle"; /** No border shape. */ readonly NONE: "none"; }>; elementName: string; /** * Creates a stamp annotation; MaintainAspectRatio is true unless given in init. * @param init Initial property values. */ constructor(init?: AnnotationInit); /** Rotates by radians around center (the center by default; clockwise is positive): the unrotated box stays, the rectangle becomes the rotated bounding box, and Rotation follows. */ rotate(radians: number, center?: { /** X of the rotation center in PDF points. */ x: number; /** Y of the rotation center in PDF points. */ y: number; }): void; /** Natural size of the image (after setImageData); tools use it for the stamp aspect ratio. */ getImageSize(): { /** Image width in pixels. */ width: number; /** Image height in pixels. */ height: number; } | null; /** * dataURL of the image: the original set by setImageData; for image stamps read from the file (engine type 0 / 2), a PNG rendered from the appearance * at ceil(rectangle × devicePixelRatio); an empty string otherwise. */ getImageData(): Promise; /** * Sets the stamp image from a data URL; the image is decoded and written with the next commit. * @param dataUrl A PNG or JPEG data URL. * @example * ```js * const { annotationManager, Annotations } = instance.Core; * const stamp = new Annotations.StampAnnotation({ PageNumber: 1, X: 400, Y: 650, Width: 120, Height: 60 }); * await stamp.setImageData('data:image/png;base64,iVBORw0KGgo...'); // a PNG or JPEG data URL * await annotationManager.addAnnotation(stamp); * ``` */ setImageData(dataUrl: string): Promise; /** Engine stamp type GetStampType: 0 unknown / 1 standard / 2 image / 3 text / 4 digital signature; null before it is read or committed (ComPDFKit extension). */ getStampType(): number | null; /** Second line (date), background color and shape (TextStampColor / TextStampShape values) of a text stamp; null when not a text stamp (ComPDFKit extension). */ getTextStampStyle(): { /** Second line of the text stamp (usually a date); an empty string when none. */ date: string; /** Background color. */ color: TextStampColor; /** Shape. */ shape: TextStampShape; } | null; /** Text of a text stamp (SetTextStamp); an empty string when not a text stamp. */ getStampText(): string; /** * Turns into a text stamp: text is the first line, options.date the second (smaller); color defaults to 'red', shape to 'rectangle' (engine indexes 0~3 are also accepted). * When width or height is 0 the engine's natural size is used (as with standard stamps). */ setStampText(text: string, options?: { /** Second line of the text stamp (usually a date); keeps the current value when omitted. */ date?: string; /** Background color, as a name or an engine index; keeps the current value when omitted. */ color?: TextStampColor | number; /** Shape, as a name or an engine index; keeps the current value when omitted. */ shape?: TextStampShape | number; }): void; /** Display uses the appearance bitmap; previewImage is drawn when the bitmap has not arrived (or for the preview before placement). */ draw(ctx: CanvasRenderingContext2D, _pageMatrix: Matrix): void; } /** * CreateWidget(SignatureFields). Two ways to sign: * - Hand-drawn / image signatures (two modes, see SignatureCreateTool.SigningModes): appearance mode draws the signature as the field appearance (isSignedByAppearance), * annotation mode places a signature annotation on the field and associates it (getAssociatedSignatureAnnotation, recorded by field name in the signature annotation's custom data so it still matches after reopening) * - Digital signatures: AnnotationManager.sign (isDigitallySigned) */ declare class SignatureWidgetAnnotation extends WidgetAnnotation { elementName: string; private associated; /** * The signature field appearance rendered as a PNG dataURL; without a size it is trunc(rectangle × devicePixelRatio + 1). * An empty string when not in a document (not added yet or deleted) (ComPDFKit extension). */ renderAppearance(width?: number, height?: number): Promise; /** The appearance is a hand-drawn / image signature (signed in appearance mode). */ isSignedByAppearance(): boolean; /** * Already has a digital signature (SignatureWidgetAnnotation.hasCryptographicSignature, returns Promise). * The single source of whether it is signed; in form field creation mode signed fields cannot be selected (AnnotationManager.isSelectableWhenDesigning). */ hasCryptographicSignature(): Promise; /** Synchronous form of hasCryptographicSignature (for synchronous paths such as hit tests and marquee selection; same source, updated with the Signed returned by the Worker). */ isDigitallySigned(): boolean; /** The signature annotation signed in annotation mode; null when none. */ getAssociatedSignatureAnnotation(): Annotation$1 | null; /** Associates a signature annotation (records the field name in its custom data, saved with the file); null removes the association. */ setAssociatedSignatureAnnotation(annotation: Annotation$1 | null): void; /** Before the appearance arrives (including while being dragged out): signature fields without a background draw a light blue block (#93B9FD, opacity 0.3) without a border. */ draw(ctx: CanvasRenderingContext2D, pageMatrix: Matrix): void; /** * Signs this signature field with signature (ink or image stamp) (SignatureWidgetAnnotation#sign): places a copy by the field's rotation and size. * By the signature tool's signing mode: annotation mode (default) adds the copy to the document and associates it (deleting an existing associated one first); appearance mode draws it as the field appearance; signature itself is not added to the document. * Bypasses the signature tool's placement flow: does not fire locationSelected / signatureReady / annotationAdded and leaves the tool's signature and position alone * (used by UI.signSignatureWidget with a signature argument). Digital signing is AnnotationManager#sign, not this. * Returns a Promise like other write methods (the Worker confirms the write). */ sign(signature: FreeHandAnnotation | StampAnnotation): Promise; /** Draws the signature annotation (ink, image stamp, etc.) as this signature field's appearance and commits (appearance mode); the signature annotation itself is not added to the document. */ createSignatureAppearance(annotation: Annotation$1, annotationManager: AnnotationManager): Promise; /** * Removes the signature: the appearance in appearance mode and the associated signature annotation in annotation mode; a digital signature is removed too * (the engine's RemoveSignature cannot remove the signature value, so an incremental update removes /V and the appearance instead; see worker/signatures/clear-signature.ts). */ clearSignature(annotationManager: AnnotationManager): Promise; } /** * Core.AnnotationManager: documentViewer.getAnnotationManager(). * Annotation objects live on the main thread and hit testing is synchronous; write methods turn into commands with baseVersion internally and resolve after the Worker confirms. * Write methods return Promises. bringToFront / bringToBack change the drawing order, and on save the Worker reorders the page's /Annots accordingly (the engine has no z-order export). */ /** An empty XFDF document (no fields and no annotations). */ declare const EMPTY_XFDF = ""; /** * A text appearance for a digital signature, laid out by the engine (the same layout as `renderDigitalSignaturePreview`). * ComPDFKit extension. */ interface DigitalSignatureTextAppearance { /** The text lines on the right (or the whole field when there is no `text`), separated by `\n`. */ content?: string; /** The large text on the left, for example the signer's name. */ text?: string; /** Align the content lines to the left instead of centering them. */ isContentAlignLeft?: boolean; /** Draw only the content lines. */ isDrawOnlyContent?: boolean; /** Draw the logo behind the text. */ isDrawLogo?: boolean; /** The logo image (PNG / JPEG bytes). */ logo?: ArrayBuffer | Uint8Array; /** An image drawn on the left instead of `text` (PNG / JPEG bytes), for example a handwritten signature. */ image?: ArrayBuffer | Uint8Array; } /** Options of AnnotationManager.sign (appearance may also be a text appearance). */ interface SignOptions { /** The signing certificate as PKCS#12 (.p12 / .pfx) bytes, including the private key. */ certificate: ArrayBuffer | Uint8Array; /** Password of the certificate file. */ password?: string; /** Appearance of the signature field: PNG / JPEG bytes, a document (the page appearancePageNumber), or a text appearance (DigitalSignatureTextAppearance). */ appearance?: ArrayBuffer | Uint8Array | Document | DigitalSignatureTextAppearance; /** Page of the appearance document to use when appearance is a document (1-based). */ appearancePageNumber?: number; /** Reason for signing, written to the signature. */ reason?: string; /** Location of signing, written to the signature. */ location?: string; /** Note: the engine cannot write it. */ contactInfo?: string; } /** Result of sign: the signed file, field name and signature field. */ /** Options of exportAnnotations. */ interface ExportAnnotationsOptions { annotationList?: Annotation$1[]; links?: boolean; fields?: boolean; useDisplayAuthor?: boolean; generateInlineAppearances?: boolean; } /** What setBeforeSubmitFormActionCallback receives: fdf true means not XFDF; fields are the field names listed in the action. */ interface SubmitFormInfo { url: string; fdf: boolean; empty: boolean; fields: string[]; } /** Result of a signing operation. */ interface SignResult { /** The signed PDF file. */ buffer: ArrayBuffer; /** Name of the signed signature field. */ fieldName: string; /** The signed signature widget, or null when it is not found. */ widget: SignatureWidgetAnnotation | null; } /** Options of prepareExternalSign: signing certificate and certificate chain (DER); appearance as in sign. */ interface ExternalSignOptions { /** The signing certificate (DER bytes, public part only). */ certificate: ArrayBuffer | Uint8Array; /** Intermediate certificates of the chain (DER bytes), embedded in the signature. */ certificateChain?: Array; /** Appearance of the signature field: PNG / JPEG bytes, a document (the page appearancePageNumber), or a text appearance. */ appearance?: ArrayBuffer | Uint8Array | Document | DigitalSignatureTextAppearance; /** Page of the appearance document to use when appearance is a document (1-based). */ appearancePageNumber?: number; /** Reason for signing, written to the signature. */ reason?: string; /** Location of signing, written to the signature. */ location?: string; /** Bytes reserved for /Contents (16384 by default); increase for large signature containers (with timestamps, revocation info). */ estimatedContentsSize?: number; } /** * External signing session: hashToSign goes to the signing service (HSM, cloud signing, smart card); documentDigest is the digest of the file content (the two ByteRange parts), * used as messageDigest when building the CMS container yourself; state is the session state text (can be stored). */ interface ExternalSignSession { /** Session id. */ id: string; /** Name of the signature field being signed. */ fieldName: string; /** Digest algorithm of hashToSign and documentDigest. */ digestAlgorithm: 'SHA-256'; /** The hash to be signed by the signing service. */ hashToSign: Uint8Array; /** Digest of the signed byte ranges of the file; use it as messageDigest when building the CMS container yourself. */ documentDigest: Uint8Array; /** Serialized session state; can be stored and passed to completeExternalSign instead of the session object. */ state: string; } /** Value for completeExternalSign: the signature value (raw RSA / ECDSA signature; the engine builds PKCS#7) or a complete CMS signature container. */ type ExternalSignValue = { /** Raw RSA / ECDSA signature value of hashToSign; the PKCS#7 container is built by the engine. */ signature: ArrayBuffer | Uint8Array; /** Not allowed together with signature. */ container?: never; } | { /** A complete CMS signature container. */ container: ArrayBuffer | Uint8Array; /** Not allowed together with container. */ signature?: never; }; /** Events of AnnotationManager and their listener arguments. */ interface AnnotationManagerEvents { /** * info.source: 'pagesUpdated' for annotations deleted together with a deleted page (not recorded in undo history). * @example * ```js * const { annotationManager } = instance.Core; * annotationManager.addEventListener('annotationChanged', (annotations, action, { imported }) => { * if (imported) * return; // loaded from the document or imported from XFDF * annotations.forEach(annot => console.log(action, annot.Id, annot.PageNumber)); * }); * ``` */ annotationChanged: [ annotations: Annotation$1[], action: 'add' | 'modify' | 'delete', info: { /** The change comes from an import or from reading the document. */ imported: boolean; /** The change comes from undo / redo. */ isUndoRedo: boolean; /** Origin of the change, such as 'pagesUpdated'. */ source?: string; /** How added annotations were created (only for 'add'). */ creation?: AnnotationCreation; } ]; /** * Annotations were selected or deselected. * @example * ```js * const { annotationManager } = instance.Core; * annotationManager.addEventListener('annotationSelected', (annotations, action) => { * if (action === 'selected') * console.log('Selected', annotations.map(annot => annot.Id)); * else * console.log('Deselected', annotations.length); * }); * ``` */ annotationSelected: [annotations: Annotation$1[], action: 'selected' | 'deselected']; /** Annotations were deselected. */ annotationDeselected: [annotations: Annotation$1[]]; /** The focused annotation changed (null when focus was cleared). */ annotationFocusChanged: [annotation: Annotation$1 | null, previous: Annotation$1 | null]; /** An annotation was double-clicked. */ annotationDoubleClicked: [annotation: Annotation$1]; /** The current user, admin or read-only state changed (fired every time by setCurrentUser / promote / demote / enable / disableReadOnlyMode, without arguments). */ updateAnnotationPermission: [annotation?: Annotation$1]; /** Annotations of a page were drawn. */ annotationsDrawn: [ info: { /** The page that was drawn (1-based). */ pageNumber: number; } ]; /** Annotations were hidden or shown. */ annotationHidden: [annotations: Annotation$1[], hidden: boolean]; /** The contents of a note were changed with setNoteContents. */ setNoteText: [annotation: Annotation$1, text: string]; /** A reply was added (with its direct parent and the root annotation of the thread). */ addReply: [reply: Annotation$1, parent: Annotation$1, root: Annotation$1]; /** A reply was deleted. */ deleteReply: [reply: Annotation$1, parent: Annotation$1]; /** The value of a form field changed. */ fieldChanged: [field: Field, value: unknown]; /** The file data of a file attachment annotation is available. */ fileAttachmentDataAvailable: [ annotation: Annotation$1, fileInfo: { /** The attached file. */ fileData: Blob; /** File name of the attachment. */ filename: string; /** MIME type of the attachment. */ mimeType: string; } ]; /** Form widget highlighting was turned on or off. */ widgetHighlightingChanged: [enabled: boolean]; /** sign completed: the signed file, field name and signature field. */ digitalSignatureApplied: [result: SignResult]; } /** Options of jumpToAnnotation / jumpToField. */ interface JumpOptions { /** Place the annotation center at this percentage of the viewport width ('0%' is the left edge); centered by default. */ horizontalOffset?: string; /** Same as above, for the height. */ verticalOffset?: string; /** Zoom (1 is 100%); keeps the current zoom by default. */ zoom?: string | number; /** Zoom so the whole annotation just fits in the viewport (takes precedence over zoom). */ fitToView?: boolean; /** Smooth scrolling (done in one step here, without animation). */ isSmoothScroll?: boolean; } /** Provenance of this write, independent of active tool and stored annotation properties. */ type AnnotationCreation = { /** Created by a tool. */ source: 'tool'; /** Whether the tool selects the annotation after creating it by default. */ autoSelect: boolean; } | { /** Created by code. */ source: 'programmatic'; }; /** Options of annotation writes (add, update, delete). */ interface AnnotationWriteOptions { /** Tool completion supplies its selection default; omission is a programmatic write. */ creation?: AnnotationCreation; /** Shown and interactive only in the current viewer, never written to PDF / XFDF. false turns an object re-added after deletion into a persistent annotation. */ transient?: boolean; /** The change comes from an import: it is allowed in read-only mode, is not recorded as a user change, and annotationChanged reports imported true. */ imported?: boolean; /** The change comes from undo / redo; reported as isUndoRedo in annotationChanged. */ isUndoRedo?: boolean; /** Accepted for compatibility; currently has no effect. */ force?: boolean; /** Lets an admin user write as usual in read-only mode (not allowed by default, keeping read-only semantics). */ allowReadOnlyAdmin?: boolean; } interface SnapOptions { radiusThreshold: number; indicatorSize: number; indicatorColor: string; } type AnnotationCtor = new (...args: unknown[]) => Annotation$1; /** Runtime creation selection policy; tool-default preserves each UI/tool default. */ type AutoSelectOnCreatePolicy = 'all' | 'none' | 'tool-default' | 'legacy-default'; /** Options of the rotation handle (see setRotationOptions). */ interface RotationOptions { isEnabled: boolean; defaultRotationType: 'SnapRotation' | 'FreeformRotation'; hotkeyTogglesRotationType: boolean; snapAngleStepSizeInDegrees: number; } declare class AnnotationManager extends EventHandler { private readonly docViewer?; /** Edge alignment types (same as Alignment.StandardAlignmentTypes). */ static readonly StandardAlignmentTypes: typeof StandardAlignmentTypes; /** The two rotation modes of the rotation handle: stepped (by snapAngleStepSizeInDegrees) and free. */ /** Values of the action of annotationChanged events. */ static readonly AnnotationChangedActions: { /** Annotations were added. */ readonly ADD: "add"; /** Annotations were deleted. */ readonly DELETE: "delete"; /** Annotations were modified. */ readonly MODIFY: "modify"; }; /** The two rotation modes of the rotation handle: stepped (by snapAngleStepSizeInDegrees) and free. */ static readonly RotationTypes: { /** Rotates in steps of snapAngleStepSizeInDegrees. */ readonly SNAP_ROTATION: "SnapRotation"; /** Rotates freely. */ readonly FREEFORM_ROTATION: "FreeformRotation"; }; /** Center alignment types (same as Alignment.CenterAlignmentTypes). */ static readonly CenterAlignmentTypes: typeof CenterAlignmentTypes; /** Distribution types (same as Alignment.DistributeAlignmentTypes). */ static readonly DistributeAlignmentTypes: typeof DistributeAlignmentTypes; /** Collection of the three groups of alignment types (as in Core.AnnotationManager.Alignment.StandardAlignmentTypes.LEFT); the same object as the three static members above. */ static readonly Alignment: { /** Edge alignment types. */ readonly StandardAlignmentTypes: typeof StandardAlignmentTypes; /** Center alignment types. */ readonly CenterAlignmentTypes: typeof CenterAlignmentTypes; /** Distribution types. */ readonly DistributeAlignmentTypes: typeof DistributeAlignmentTypes; }; /** Event names of AnnotationManager. */ static readonly Events: { /** 'annotationFocusChanged': the focused annotation changed. */ readonly ANNOTATION_FOCUS_CHANGED: "annotationFocusChanged"; /** 'annotationSelected': annotations were selected or deselected. */ readonly ANNOTATION_SELECTED: "annotationSelected"; /** 'annotationDeselected': annotations were deselected. */ readonly ANNOTATION_DESELECTED: "annotationDeselected"; /** 'annotationDoubleClicked': an annotation was double-clicked. */ readonly ANNOTATION_DOUBLE_CLICKED: "annotationDoubleClicked"; /** 'annotationChanged': annotations were added, modified or deleted. */ readonly ANNOTATION_CHANGED: "annotationChanged"; /** 'updateAnnotationPermission': the current user, admin or read-only state changed. */ readonly UPDATE_ANNOTATION_PERMISSION: "updateAnnotationPermission"; /** 'annotationsDrawn': annotations of a page were drawn. */ readonly ANNOTATIONS_DRAWN: "annotationsDrawn"; /** 'annotationHidden': annotations were hidden or shown. */ readonly ANNOTATION_HIDDEN: "annotationHidden"; /** 'setNoteText': the contents of a note were changed. */ readonly SET_NOTE_TEXT: "setNoteText"; /** 'addReply': a reply was added. */ readonly ADD_REPLY: "addReply"; /** 'deleteReply': a reply was deleted. */ readonly DELETE_REPLY: "deleteReply"; /** 'fieldChanged': the value of a form field changed. */ readonly FIELD_CHANGED: "fieldChanged"; /** 'fileAttachmentDataAvailable': the file data of a file attachment is available. */ readonly FILE_ATTACHMENT_DATA_AVAILABLE: "fileAttachmentDataAvailable"; /** 'widgetHighlightingChanged': form widget highlighting was turned on or off. */ readonly WIDGET_HIGHLIGHTING_CHANGED: "widgetHighlightingChanged"; /** 'digitalSignatureApplied': a digital signature was applied with sign. */ readonly DIGITAL_SIGNATURE_APPLIED: "digitalSignatureApplied"; /** 'digitalSignaturesChanged': a digital signature in the document was changed by undo / redo. */ readonly DIGITAL_SIGNATURES_CHANGED: "digitalSignaturesChanged"; }; /** Align / center / distribute. */ readonly Alignment: Alignment; /** By page order, and within a page by PDF order (later is on top). */ private annotations; private readonly byId; private readonly synced; private readonly transient; /** Annotations moved by bringToFront / bringToBack: on save, /Annots of their pages is reordered by list order. */ private readonly reordered; private readonly selected; private unselectableAnnotationTypes; private focusedAnnotation; private formFieldFocusOutlineAnnotations; private autoSelectOnCreatePolicy; private stickyNoteCreationMode; /** The redaction annotation the pointer rests on (hover previews the applied result). */ private hoveredRedaction; private currentUser; private admin; private readOnly; private permissionCheck; private displayAuthor; private tabOrder; private widgetTabOrdering; /** Annotations can be dragged onto other pages (on by default). */ private draggingAcrossPages; private readonly fieldManager; private readonly editBoxManager; private readonly formFieldCreationManager; private readonly snapOptions; private readonly sinceExport; private readonly sinceLoad; /** Replies are shown as ordinary notes when their parent is missing. */ private detachedRepliesShown; /** * Creates an annotation manager. * @param docViewer The document viewer whose annotations are managed; without it, viewer-dependent features (drawing, scrolling, mouse positions) are unavailable. */ constructor(docViewer?: DocumentViewer | undefined); /** * Sets the rich text style of the annotation and commits it with updateAnnotation (for free text the style is written to the rich text contents and the appearance follows it). Commit failures are logged, not thrown. * @param annotation The annotation to change, usually a free text annotation. * @param style The rich text style to apply to the whole text; null removes the rich text style. */ setAnnotationRichTextStyle(annotation: Annotation$1, style: RichTextStyle | null): void; /** * Applies a style to the characters in [start, end) of the annotation's rich text and commits the change. Logs a warning and does nothing when start is greater than end. * @param annotation The annotation to change. * @param style Style to apply (underline, line-through, font-weight, font-style, color, font-family, font-size). * @param start Index of the first character; defaults to 0. * @param end Index after the last character; defaults to the length of the contents. */ updateAnnotationRichTextStyle(annotation: Annotation$1, style: Record, start?: number, end?: number): void; /** Adds the read annotations to the list, attaches replies, fires annotationChanged (add, imported) and redraws. */ private adopt; /** Signature annotations and signature fields are matched by field name (in the signature annotation's custom data); the first to arrive waits for the other. */ private linkSignature; private calculationOrderWrite?; private fromData; /** Writes Worker properties onto the annotation object (both reading and conflict rollback go through here). */ private applyProps; /** Annotation object → serializable properties (full). */ private toProps; /** Bounding box of the geometry (text markup quadrilaterals, points of ink / lines / polygons); null without geometry. */ private geometryBounds; /** How much the current rectangle extends beyond the geometry. */ private marginOf; /** * When the geometry changes (or on creation), recomputes X / Y / Width / Height from the geometry, expanded by margin (the difference between the Worker's last rectangle and the geometry, * so the appearance bitmap's box stays the same before and after committing); without it, expanded by half the line width (text markup is not expanded). */ private syncRect; /** * Fetches the rectangle after the Worker writes: when generating the appearance the engine expands the rectangle for line width, line endings, clouds, result text and so on, and the appearance bitmap is drawn by that rectangle, * so not following it would squeeze it. Not changed when the rectangle was changed locally after sending. Returns true when fetched. */ /** * Free text with a callout: when updating the appearance the engine expands the rectangle to enclose the callout and the padding (/RD) changes accordingly, so the Worker's padding is fetched * (not when changed locally meanwhile, like adoptRect). */ private adoptPadding; private adoptRect; /** * Gets all annotations in the document, in page order and, within a page, from bottom to top. * @returns A copy of the annotation list. * @example * ```js * const { annotationManager, Annotations } = instance.Core; * const rectanglesOnPage1 = annotationManager.getAnnotationsList() * .filter(annot => annot instanceof Annotations.RectangleAnnotation && annot.PageNumber === 1); * ``` */ getAnnotationsList(): Annotation$1[]; /** * Finds an annotation by its Id. * @param id The annotation Id. * @returns The annotation, or null when not found. * @example * ```js * const { annotationManager } = instance.Core; * const annot = annotationManager.getAnnotationById('my-annotation-id'); * if (annot) * annotationManager.jumpToAnnotation(annot); * ``` */ getAnnotationById(id: string): Annotation$1 | null; /** * The topmost visible annotation under the pointer. includeWidgetsAndLinks defaults to false: form widgets and links are excluded * (pass true explicitly when they need to be hit: filling forms, clicking links, creating widgets). * @param e A mouse or pointer event; only clientX and clientY are read. * @param includeWidgetsAndLinks Also hit form widgets and links. Defaults to false. * @returns The topmost hit annotation, or null when nothing is under the pointer, no document is loaded or annotations are disabled. */ getAnnotationByMouseEvent(e: Pick, includeWidgetsAndLinks?: boolean): Annotation$1 | null; /** * All visible annotations under the pointer, topmost first; includeWidgetsAndLinks as in getAnnotationByMouseEvent, excluding form widgets and links by default. * @param e A mouse or pointer event; only clientX and clientY are read. * @param includeWidgetsAndLinks Also hit form widgets and links. Defaults to false. * @returns The hit annotations, topmost first; empty when none, when no document is loaded or when annotations are disabled. Hidden annotations, replies and annotations that cannot be selected are excluded. */ getAnnotationsByMouseEvent(e: Pick, includeWidgetsAndLinks?: boolean): Annotation$1[]; /** * Whether it can be clicked / marquee-selected: signature fields with a digital signature cannot, in any mode and with any tool (the signature field creation tool can select widgets outside form field creation mode too, * so this does not depend on the mode). They cannot be moved, changed or deleted: deleting the field would orphan the signature with no way left in the UI to remove it; unsigned ones and ones with only hand-drawn / image appearances are selected as usual. Whether it is signed comes from the digital signature property of SignatureWidgetAnnotation (hasCryptographicSignature). */ private isHittable; /** * Marquee selection: selectable annotations on this page whose bounding box intersects the rectangle; replies, hidden ones, links, redactions and widgets outside form field creation mode are excluded. * @param pageNumber The page number (1-based). * @param rect The selection rectangle in PDF points, with x1 / y1 the top-left and x2 / y2 the bottom-right corner. * @param rect.x1 Left edge. * @param rect.y1 Top edge. * @param rect.x2 Right edge. * @param rect.y2 Bottom edge. * @returns The annotations whose bounding box intersects the rectangle, in stacking order (bottom first). */ getAnnotationsInRect(pageNumber: number, rect: { /** Left edge in PDF points. */ x1: number; /** Top edge in PDF points. */ y1: number; /** Right edge in PDF points. */ x2: number; /** Bottom edge in PDF points. */ y2: number; }): Annotation$1[]; /** * Whether this exact annotation object is in the document. * @param annotation The annotation to check. * @returns True when the annotation is managed by this manager. */ hasAnnotation(annotation: Annotation$1): boolean; /** * Hit testing (testSelection of each selection model): when unselected, by the drawn shape: unfilled rectangles, ellipses and polygons only by their edges, * ink, polylines and arcs only by their paths, filled ones also inside; when selected, by the whole bounding box (polygons by their inside); lines always by the line. * Instead of drawing the annotation onto a small canvas and checking pixels, the same result is computed geometrically: half the line width plus tolerance, plus the bulge height for clouds. */ private hits; /** * Follows InReplyTo to the one that is not a reply; null when a parent along the way is missing. * @param annotation The annotation, usually a reply. * @returns The root annotation (the annotation itself when it is not a reply), or null when a parent in the chain is not in the document. */ getRootAnnotation(annotation: Annotation$1): Annotation$1 | null; /** * The group it belongs to: the primary annotation first, followed by its grouped children; just itself when ungrouped. * @param annotation Any annotation of the group (the primary annotation or a grouped child). * @returns The primary annotation followed by its grouped children; [annotation] when it is not grouped; empty when the primary annotation is not in the document. */ getGroupAnnotations(annotation: Annotation$1): Annotation$1[]; /** * How many groups these annotations belong to (each ungrouped one counts as a group). * @param annotations The annotations to count. * @returns The number of distinct groups; annotations of the same group count once. */ getNumberOfGroups(annotations: Annotation$1[]): number; /** * Sets the annotation types that cannot be selected, clicked or marquee-selected. Names are XFDF element names (such as 'square', 'ink', 'freetext') or widget names ('textfield', 'checkbox', 'radiobutton', 'pushbutton', 'listbox', 'combobox', 'signatureFields'); redactions are 'redaction'. * Measurements have their own names: rectangleMeasurement, inkMeasurement (arc), lineMeasurement, polylineMeasurement, polygonMeasurement, circleMeasurement; squareMeasurement, arcMeasurement and curveMeasurement are also accepted. * Unknown names are kept for custom annotation types. Selected annotations of these types are deselected (with more than one selected annotation, the whole selection is cleared). This is independent of Locked, Hidden and document permissions. * @param types The type names; the array is copied. Replaces the previous list; an empty array makes every type selectable again. Throws a TypeError when it is not an array of strings. */ setUnselectableAnnotationTypes(types: readonly string[]): void; /** * Gets the annotation types that cannot be selected. * @returns A copy of the type list set with setUnselectableAnnotationTypes. */ getUnselectableAnnotationTypes(): string[]; /** * Checks whether the annotation's type is in the list set with setUnselectableAnnotationTypes. This is independent of Locked, Hidden and document permissions. * @param annotation The annotation to check. * @returns True when its type cannot be selected. */ isAnnotationUnselectable(annotation: Annotation$1): boolean; /** * Sets the form widgets that show the focus outline used for keyboard form navigation; an empty array (the default) disables the outline. * This affects only how widgets are drawn: it does not change focus, the selection or fire events. * @param annotations The widgets that may show the outline; annotations that are not widgets or not in the document are ignored. The focused annotation's page is redrawn when the set changes. */ setFormFieldFocusOutlineAnnotations(annotations: readonly WidgetAnnotation[]): void; /** * Checks whether the focus outline is shown for a widget: it is one of the widgets set with setFormFieldFocusOutlineAnnotations and can currently be filled (visible, not read-only, not a push button or a signed signature field, not in form field creation mode). * It never grants editing or changes focus. * @param annotation The annotation to check. * @returns True when the outline is shown. */ isFormFieldFocusOutlineVisible(annotation: Annotation$1): boolean; /** * Sets the focused annotation. Focus is independent of the selection: the previous annotation receives 'blur', the new one 'focus', annotationFocusChanged fires and the affected pages are redrawn. An in-place editor open on the previous annotation is closed. * @param annotation The annotation to focus; null removes the focus without deselecting anything. Annotations not in the document are ignored, and setting the current one again does nothing. */ setFocusedAnnotation(annotation: Annotation$1 | null): void; /** * Gets the focused annotation. * @returns The focused annotation, or null when none. */ getFocusedAnnotation(): Annotation$1 | null; /** * Sets how sticky notes are created by the tool. Drafts already in progress keep their mode. * @param mode 'immediate' (the default) or 'draft'. Throws a TypeError for other values. */ setStickyNoteCreationMode(mode: 'immediate' | 'draft'): void; /** * Gets the sticky note creation mode. * @returns 'immediate' (default) or 'draft'. */ getStickyNoteCreationMode(): 'immediate' | 'draft'; /** * Sets whether annotations are selected after they are created by a tool. Existing selections and imported or replayed annotations are not affected. * @param policy 'all' selects every created annotation, 'none' never selects, 'tool-default' (the default) follows each tool's own default, and 'legacy-default' selects only annotations completed by a tool whose default is to select. Throws a TypeError for other values. */ setAutoSelectOnCreatePolicy(policy: AutoSelectOnCreatePolicy): void; /** * Gets the policy for selecting annotations after they are created. * @returns The current policy; 'tool-default' by default. */ getAutoSelectOnCreatePolicy(): AutoSelectOnCreatePolicy; /** * Decides whether a newly created annotation is selected, by the policy set with setAutoSelectOnCreatePolicy. * @param toolDefault Whether the creating tool selects by default. * @param creation Where the annotation comes from; with the 'legacy-default' policy only `{ source: 'tool', autoSelect: true }` selects. * @returns True when the annotation should be selected. */ shouldAutoSelectOnCreate(toolDefault: boolean, creation?: AnnotationCreation): boolean; /** * Selects an annotation (see selectAnnotations). * @param annotation The annotation to select. * @example * ```js * const { annotationManager } = instance.Core; * const [first] = annotationManager.getAnnotationsList(); * if (first) { * annotationManager.jumpToAnnotation(first); * annotationManager.selectAnnotation(first); * } * ``` */ selectAnnotation(annotation: Annotation$1): void; /** * Selects annotations and fires annotationSelected. Annotations not in the document, unselectable or already selected are skipped. * @param annotations The annotations to select. * @example * ```js * const { annotationManager } = instance.Core; * const onPage2 = annotationManager.getAnnotationsList().filter(annot => annot.PageNumber === 2); * annotationManager.selectAnnotations(onPage2); * ``` */ selectAnnotations(annotations: Annotation$1[]): void; /** * Deselects an annotation (see deselectAnnotations). * @param annotation The annotation to deselect. */ deselectAnnotation(annotation: Annotation$1): void; /** * Deselects annotations and fires annotationSelected (with 'deselected') and annotationDeselected. Clears the focus when the focused annotation is deselected. * @param annotations The annotations to deselect. */ deselectAnnotations(annotations: Annotation$1[]): void; /** * Deselects all selected annotations. * @example * ```js * const { annotationManager } = instance.Core; * annotationManager.deselectAllAnnotations(); * ``` */ deselectAllAnnotations(): void; /** * Gets the selected annotations. * @returns A copy of the selected annotations, in selection order; empty when none is selected. * @example * ```js * const { annotationManager } = instance.Core; * const selected = annotationManager.getSelectedAnnotations(); * await annotationManager.deleteAnnotations(selected); * ``` */ getSelectedAnnotations(): Annotation$1[]; /** * Whether an annotation is selected. * @param annotation The annotation to check. * @returns True when selected. */ isAnnotationSelected(annotation: Annotation$1): boolean; /** * Scrolls to the annotation's page and centers the annotation in the viewport (aligns its top-left when the viewport is smaller than the annotation). * @param annotation The annotation to scroll to. * @param options Optional. `zoom` zooms to this level first (1 is 100%; the current zoom is kept by default); `fitToView` zooms so the whole annotation fits the viewport and takes precedence over zoom; `horizontalOffset` / `verticalOffset` (such as '25%') place the annotation center at that percentage of the viewport instead of the middle; `isSmoothScroll` is accepted but scrolling is always immediate. Does nothing when no document is loaded. * @example * ```js * const { annotationManager } = instance.Core; * const annot = annotationManager.getAnnotationById('my-annotation-id'); * if (annot) * annotationManager.jumpToAnnotation(annot, { zoom: 2 }); * ``` */ jumpToAnnotation(annotation: Annotation$1, options?: JumpOptions): void; /** * Adds to the list immediately and fires annotationChanged('add'), then writes it to the document; if writing fails it is removed again and 'delete' fires. * Annotations without an Id get one; geometric types (text markup / ink / lines / polygons) get their rectangle computed from the geometry. * @param annotation The annotation to add. * @param options Optional write options: `imported` marks the change as an import (allowed in read-only mode, not recorded as a user change, reported as imported in annotationChanged); `isUndoRedo` reports it as undo / redo; `transient` keeps it only in this viewer, never written to the PDF or XFDF; `creation` tells whether a tool or code created it; `allowReadOnlyAdmin` lets an admin write in read-only mode. * @returns A promise that resolves when the annotation has been written to the document. It rejects in read-only mode (PERMISSION_DENIED), when no document is loaded, or when writing fails. * @example * ```js * const { annotationManager, Annotations } = instance.Core; * // Coordinates are PDF points measured from the top-left corner of the page. * const rectangle = new Annotations.RectangleAnnotation({ * PageNumber: 1, * X: 100, * Y: 150, * Width: 200, * Height: 50, * }); * rectangle.StrokeColor = new Annotations.Color(255, 0, 0); * rectangle.StrokeThickness = 2; * rectangle.Author = annotationManager.getCurrentUser(); * await annotationManager.addAnnotation(rectangle); * ``` */ addAnnotation(annotation: Annotation$1, options?: AnnotationWriteOptions): Promise; private isMainThreadOnly; /** * Adds annotations to the document: they are listed immediately, annotationChanged('add') fires, and then they are written to the document. Annotations already in the document are skipped; annotations without an Id get one. * @param annotations The annotations to add. * @param options Write options. * @example * ```js * const { annotationManager, Annotations } = instance.Core; * const marks = [1, 2, 3].map(pageNumber => new Annotations.EllipseAnnotation({ * PageNumber: pageNumber, * X: 20, * Y: 20, * Width: 30, * Height: 30, * })); * await annotationManager.addAnnotations(marks); * ``` */ addAnnotations(annotations: Annotation$1[], options?: AnnotationWriteOptions): Promise; /** * Commits changes made to the annotation object: fires annotationChanged('modify') immediately and writes the changes to the document. * Commits of the same annotation are applied in order; if the document rejects a change, the annotation is rolled back to the saved state and the promise rejects. * @param annotation The changed annotation; it must be in the document. * @param options Optional write options; see addAnnotation. With `imported` the change is not recorded as a user change and is allowed in read-only mode. * @returns A promise that resolves when the change has been written. It rejects in read-only mode (PERMISSION_DENIED), when the annotation is not in the document (INVALID_HANDLE), or when the document rejects the change (CONFLICT or INTERNAL; the annotation is rolled back and annotationChanged('modify') fires again). * @example * ```js * const { annotationManager, Annotations } = instance.Core; * const annot = annotationManager.getAnnotationById('my-annotation-id'); * annot.StrokeColor = new Annotations.Color(0, 0, 255); * annot.setContents('Checked'); * annot.setCustomData('status', 'reviewed'); * await annotationManager.updateAnnotation(annot); * ``` */ updateAnnotation(annotation: Annotation$1, options?: AnnotationWriteOptions): Promise; private commitAnnotationUpdate; /** * Removes from the list immediately and fires annotationChanged('delete'), then deletes it from the document; on failure it is put back and 'add' fires. * @param annotation The annotation to delete. Annotations with NoDelete, or that the current user cannot modify, are left alone. * @param options Optional write options; see addAnnotation. With `allowReadOnlyAdmin` an admin can delete a sticky note in read-only mode; for other users or annotation types the promise rejects with PERMISSION_DENIED. * @returns A promise that resolves when the annotation has been deleted from the document. It rejects in read-only mode, when no document is loaded, or when deleting fails. * @example * ```js * const { annotationManager } = instance.Core; * const annot = annotationManager.getAnnotationById('my-annotation-id'); * if (annot) * await annotationManager.deleteAnnotation(annot); * ``` */ deleteAnnotation(annotation: Annotation$1, options?: AnnotationWriteOptions & { /** Lets an admin delete a sticky note in read-only mode; rejects for other users or annotation types. */ allowReadOnlyAdmin?: boolean; }): Promise; /** * Deletes annotations: they are removed from the list and deselected immediately, annotationChanged('delete') fires (deleteReply for replies), and then they are deleted from the document; if deleting fails an annotation is put back and 'add' fires. * Annotations with NoDelete or that the current user cannot modify (canModify) are left alone; this is checked regardless of imported / force / isUndoRedo. * With allowReadOnlyAdmin, admins delete as usual in read-only mode. Replies of a deleted annotation that are not deleted with it become ordinary annotations. * @param annotations The annotations to delete; annotations not in the document are skipped. * @param options Optional write options; see addAnnotation. * @returns A promise that resolves when the annotations have been deleted from the document. It rejects in read-only mode (PERMISSION_DENIED), when no document is loaded, or when deleting one of them fails. * @example * ```js * const { annotationManager } = instance.Core; * // Delete every annotation on page 3 * const onPage3 = annotationManager.getAnnotationsList().filter(annot => annot.PageNumber === 3); * await annotationManager.deleteAnnotations(onPage3); * ``` */ deleteAnnotations(annotations: Annotation$1[], options?: AnnotationWriteOptions): Promise; private removeAnnotations; /** * Changes the Id of an annotation in the document (written to its /NM name). No annotationChanged event fires. * @param annotation The annotation to rename; it must be in the document. * @param newId The new Id; it must not be used by another annotation. * @returns A promise that resolves when the document has been updated. It rejects with INVALID_HANDLE when the annotation is not in the document or newId is taken, and when the document rejects the change. */ updateAnnotationId(annotation: Annotation$1, newId: string): Promise; /** * Groups annotations under a primary annotation: each one is attached to primary (InReplyTo = primary.Id, ReplyType = 'group'), together with its own grouped children, and committed with updateAnnotation. * @param primary The primary annotation of the group. * @param annotations The annotations to attach; primary itself is skipped if included. * @returns A promise that resolves when all changed annotations have been committed. */ groupAnnotations(primary: Annotation$1, annotations: Annotation$1[]): Promise; /** * Removes group membership from annotations (only annotations whose ReplyType is 'group') and commits them. * @param annotations The annotations to ungroup. */ ungroupAnnotations(annotations: Annotation$1[]): Promise; /** * Hides an annotation (see hideAnnotations). * @param annotation The annotation to hide. * @returns A promise that resolves when the change has been committed. * @example * ```js * const { annotationManager } = instance.Core; * const annot = annotationManager.getAnnotationById('my-annotation-id'); * await annotationManager.hideAnnotation(annot); * await annotationManager.showAnnotation(annot); * ``` */ hideAnnotation(annotation: Annotation$1): Promise; /** * Hides annotations: sets Hidden, clears their focus and selection, fires annotationHidden, then commits each with updateAnnotation (annotationChanged('modify'), recorded in undo history, written on save). * @param annotations The annotations to hide. * @returns A promise that resolves when all changes have been committed; it rejects like updateAnnotation. */ hideAnnotations(annotations: Annotation$1[]): Promise; /** * Shows a hidden annotation (see showAnnotations). * @param annotation The annotation to show. */ showAnnotation(annotation: Annotation$1): Promise; /** * Shows hidden annotations by clearing their Hidden flag and commits them. * @param annotations The annotations to show. */ showAnnotations(annotations: Annotation$1[]): Promise; /** * Brings an annotation to the top of the stacking order and redraws its page. The order is used by hit testing and drawing; it is written to the page's annotation list on save, and exported XFDF follows it too (not written for encrypted documents). * @param annotation The annotation to move; annotations not in the document are ignored. */ bringToFront(annotation: Annotation$1): void; /** * Sends an annotation to the bottom of its page's stacking order (see bringToFront for how the order is saved). * @param annotation The annotation to move. */ bringToBack(annotation: Annotation$1): void; /** Pages whose stacking order changed: one group of annotation ids per page, in list order (earlier drawn first); written to the file on save. */ private reorderedPages; /** * Sets the contents of an annotation, fires setNoteText and commits the change. * @param annotation The annotation to change. * @param contents The new contents. * @param options Optional. With `allowReadOnlyAdmin: true` an admin can edit a sticky note in read-only mode; for other users or annotation types it throws PERMISSION_DENIED. * @param options.allowReadOnlyAdmin Lets an admin edit a sticky note in read-only mode. * @returns A promise that resolves when the change has been committed; it rejects like updateAnnotation. */ setNoteContents(annotation: Annotation$1, contents: string, options?: { /** Lets an admin edit a sticky note in read-only mode; throws for other users or annotation types. */ allowReadOnlyAdmin?: boolean; }): Promise; /** * Sets the review state of an annotation by adding a hidden state reply (a sticky note with State / StateModel, authored by the current user). Fires addReply and annotationChanged('add'). * @param annotation The annotation whose state is set. * @param state The state, such as 'Accepted', 'Rejected', 'Cancelled', 'Completed', 'None', 'Marked' or 'Unmarked'. Defaults to 'None'. * @param stateModel 'Review' (the default) or 'Marked'. * @param message Optional contents of the state reply; defaults to ' set by '. * @returns A promise that resolves with the state reply once it has been added. */ updateAnnotationState(annotation: Annotation$1, state?: string, stateModel?: 'Review' | 'Marked', message?: string): Promise; /** * Adds a reply by the current user to an annotation. Fires addReply and annotationChanged('add'). * @param annotation The annotation to reply to. * @param text The reply text. Defaults to an empty string. * @returns A promise that resolves with the new reply once it has been added. */ createAnnotationReply(annotation: Annotation$1, text?: string): Promise; private newReply; private addReplyTo; /** Hides replies whose parent annotation is missing (the default). */ hideDetachedReplies(): void; /** Shows replies whose parent annotation is missing as ordinary notes on the page. */ showDetachedReplies(): void; /** Replies attached to a parent are not drawn on the page and take no part in hit testing (they only appear in the comment list). */ private isAttachedReply; /** Attaches the annotation under the parent InReplyTo points to; file attachments also get the channel for exporting their own XFDF. */ private link; private unlink; /** * A new annotation of the same type with copied properties (including geometry, style, content), without an Id and not in the document. * @param annotation The annotation to copy. * @param _options Unused; kept for compatibility. * @param _options.copyAssociatedLink Unused; kept for compatibility. * @returns The copy, on the same page, not a reply and not grouped. Stamp images and file attachment data are shared with the copy. */ getAnnotationCopy(annotation: Annotation$1, _options?: { /** Accepted for compatibility; currently has no effect. */ copyAssociatedLink?: boolean; }): Annotation$1; /** * Gets the annotations copied by updateCopiedAnnotations (the selection at that time, excluding text markup). * @returns The copied annotations; empty when nothing was copied. */ getCopiedAnnotations(): Annotation$1[]; /** Copies the selected annotations (text markup is attached to text and is not copied). */ updateCopiedAnnotations(): void; /** Whether pasting uses viewport-relative positions by default (setViewportRelativeAnnotationPositioning; off by default). */ private viewportRelativePositioning; /** * Sets whether pasteCopiedAnnotations puts the copies back at the same position in the viewport as when they were copied. False by default; an explicit options.viewportRelative of pasteCopiedAnnotations takes precedence. * @param enabled True to paste at viewport-relative positions. */ setViewportRelativeAnnotationPositioning(enabled: boolean): void; /** * Checks whether pasting uses viewport-relative positions by default (see setViewportRelativeAnnotationPositioning). * @returns True when enabled; false by default. */ isViewportRelativeAnnotationPositioningEnabled(): boolean; /** * Pastes the copied annotations and selects what was pasted: * - by default onto the current page, offset by another getAnnotationPasteOffsets for each paste on the same page; * - with pasteToMousePosition, the first copy's top-left goes to the last mouse position (on that page), the rest keep their relative positions; * - with options.viewportRelative, back to the same place in the viewport as at copy time (on the current page), plus the offset. * Nothing goes beyond the page. * @param pasteToMousePosition Paste at the last mouse position. Defaults to false; ignored when pasting at viewport-relative positions. * @param options Optional. `viewportRelative` pastes at the same viewport position as at copy time; defaults to the setViewportRelativeAnnotationPositioning setting. * @param options.viewportRelative Paste at the same viewport position as at copy time. * @returns A promise that resolves after the copies have been added and selected. Does nothing in read-only mode or when nothing was copied; it rejects like addAnnotations. */ pasteCopiedAnnotations(pasteToMousePosition?: boolean, options?: { /** Paste at the same viewport position as at copy time; defaults to the setViewportRelativeAnnotationPositioning setting. */ viewportRelative?: boolean; }): Promise; /** * Gets the offset of each paste relative to the previous one. * @returns A copy of the offsets in PDF points; { x: 0, y: 5 } by default. */ getAnnotationPasteOffsets(): { /** Horizontal offset in PDF points. */ x: number; /** Vertical offset in PDF points. */ y: number; }; /** * Sets the offset of each paste relative to the previous one. Values that are not numbers keep the current offset. * @param offsets x and y in PDF points (numbers or numeric strings). * @param offsets.x Horizontal offset. * @param offsets.y Vertical offset. */ setAnnotationPasteOffsets(offsets: { /** Horizontal offset in PDF points. */ x?: number | string; /** Vertical offset in PDF points. */ y?: number | string; }): void; private copied; /** Position (px) of each annotation's top-left in the viewport at copy time. */ private copiedInViewport; private pasteOffsets; /** Page number → how many times pasted on that page. */ private readonly pasteCounts; /** * Redraws the annotation layer of the annotation's page. * @param annotation The annotation to redraw. * @example * ```js * const { annotationManager } = instance.Core; * const annot = annotationManager.getAnnotationById('my-annotation-id'); * annot.Opacity = 0.5; * annotationManager.redrawAnnotation(annot); // show the change right away * await annotationManager.updateAnnotation(annot); // save it to the document * ``` */ redrawAnnotation(annotation: Annotation$1): void; /** * Redraws this page's annotation layer; with overrideCanvas, draws this page's annotations into it instead: the canvas is the whole page in display orientation, * the multiplier is computed from the canvas width, and appearance bitmaps are fetched before drawing. * @param options `pageNumber` is the page to draw (1-based); `overrideCanvas` draws the page's annotations into this canvas instead of the annotation layer; `majorRedraw` has no effect. * @param options.pageNumber The page to draw (1-based). * @param options.overrideCanvas Canvas to draw the page's annotations into instead of the annotation layer. * @param options.majorRedraw Unused; kept for compatibility. * @returns A promise that resolves when drawing into overrideCanvas is done; without it, resolves right away and the layer is redrawn in the next frame. */ drawAnnotations(options: { /** The page to draw (1-based). */ pageNumber: number; /** Canvas to draw the page's annotations into instead of the annotation layer. */ overrideCanvas?: HTMLCanvasElement; /** Accepted for compatibility; currently has no effect. */ majorRedraw?: boolean; }): Promise; /** * Redraws the annotation layers of the pages the given annotations are on. * @param annotations The annotations to redraw. */ drawAnnotationsFromList(annotations: Annotation$1[]): Promise; /** * Assigns style properties to the annotation (StrokeColor, FillColor, Opacity, StrokeThickness and so on) and commits it with updateAnnotation. * @param annotation The annotation to change. * @param styles Property names and values to assign to the annotation. * @returns A promise that resolves when the change has been committed; it rejects like updateAnnotation. */ setAnnotationStyles(annotation: Annotation$1, styles: Record): Promise; private commit; /** Writes of the same annotation are queued; a failure of the previous one does not affect the next. */ private enqueue; private setHidden; /** * After the Worker confirms: the thumbnail cache is invalidated and the annotation layer redrawn. The appearance bitmap of the new version is fetched by version, and the old one is kept until the new one arrives (standing in while loading, without flashing); * bitmaps of deleted annotations are dropped right away. */ private committed; /** Redraws the annotation layers of these pages (merged into the next frame). */ private redrawPages; /** * Returns the annotations on one page, in drawing order (earlier ones are drawn below later ones). * Replies attached to another annotation are left out, as they are not drawn on the page; use `getAnnotationsList()` to include them. * @param pageNumber Page number (1-based). * @returns A new array of the page's annotations, including form field widgets and links; empty when the page has none. * @example * ```js * const { annotationManager, Annotations } = instance.Core; * const [first] = annotationManager.getPageAnnotations(1); // the first annotation on page 1 * const rectangles = annotationManager.getPageAnnotations(1).filter(a => a instanceof Annotations.RectangleAnnotation); * ``` */ getPageAnnotations(pageNumber: number): Annotation$1[]; /** Measurement annotations: fetches the result computed by the Worker and the result text written to /Contents (the rectangle including the result text is fetched by adoptRect). */ private adoptMeasurement; /** * Renders the appearance of an annotation (only the annotation itself, on a transparent background) as a PNG data URL, after the annotation's pending writes finish. * Used by StampAnnotation.getImageData and SignatureWidgetAnnotation.renderAppearance. * @param annotation The annotation to render. * @param width Width of the image in device pixels (rounded, at least 1). * @param height Height of the image in device pixels (rounded, at least 1). * @returns A promise that resolves with the PNG data URL, or an empty string when the annotation is not in this document or has not been written yet. */ renderAppearanceDataUrl(annotation: Annotation$1, width: number, height: number): Promise; private remove; private requireDocument; /** * Has no effect: redraws of the annotation layer are already merged per frame. Kept for compatibility. * @param _ms Unused; kept for compatibility. */ setRedrawThrottleRate(_ms: number): void; /** * Options of the rotation handle: isEnabled shows the rotation handle; defaultRotationType defaults to free rotation, * with hotkeyTogglesRotationType true holding Shift switches to the other mode; snapAngleStepSizeInDegrees is the step of stepped rotation (0–180°). * @param options The options to change; omitted keys keep their values. Throws INVALID_SOURCE for an unknown defaultRotationType or a snap angle outside (0, 180]. The annotation layers are redrawn. */ setRotationOptions(options: Partial): void; /** * Gets the options of the rotation handle. * @returns A copy of the options. */ getRotationOptions(): RotationOptions; private rotationOptions; /** * Applies redactions (ApplyRedaction): page content under the redaction boxes is deleted and the redaction annotations themselves are removed (all redaction annotations by default); * enableRedaction must be called first. The page is redrawn right away (contentChanged of pagesUpdated). * @param annotations The redaction annotations to apply; other annotation types are ignored. Defaults to all redaction annotations in the document. * @returns A promise that resolves when the redactions have been applied; annotationChanged('delete') fires with imported true for the removed redactions and any annotations removed with the content under them, and the change is not recorded in undo history. It rejects with PERMISSION_DENIED when redaction is not enabled. */ applyRedactions(annotations?: Annotation$1[]): Promise; /** * Checks whether an annotation is a redaction annotation that can be applied (redaction must be enabled with enableRedaction and a document loaded). * @param annotation The annotation to check. * @returns True when it can be applied. */ isAnnotationRedactable(annotation: Annotation$1): boolean; /** Allows creating and applying redactions. */ enableRedaction(): void; /** Disallows creating and applying redactions (the default). */ disableRedaction(): void; /** * Whether redaction annotations can be created. * @returns True when redaction is enabled. */ isCreateRedactionEnabled(): boolean; /** * Whether redactions can be applied: redaction is enabled and a document is loaded. * @returns True when redactions can be applied. */ isApplyRedactionEnabled(): boolean; private redactionEnabled; private submitFormCallback?; private beforeSubmitFormCallback?; /** * Sets the function that receives the server response after a SubmitForm action succeeds. Without it a warning is logged. * @param callback Receives the response text. */ setSubmitFormActionCallback(callback: (response: string) => void): void; /** * Sets the function called before a SubmitForm action submits. * @param callback Receives the URL, whether it is FDF, whether empty fields are included, and the listed field names; returning false cancels the submission. */ setBeforeSubmitFormActionCallback(callback: (info: SubmitFormInfo) => boolean | void): void; private widgetPresentation; /** * Sets how form widgets are presented on screen. It does not change PDF flags, field values, the selection or form field creation mode. * Without a call, the normal display and interaction rules apply. * @param options `showHiddenWidgets` displays widgets that are invisible, hidden or NoView; `allowInteractionInCreationMode` lets widgets be filled in form field creation mode, either a boolean or a function read each time it is needed (an open editor is not refreshed when its value changes). null restores the normal rules. Throws a TypeError for other values. The annotation layers are redrawn. */ setWidgetPresentation(options: { /** Display widgets that are invisible, hidden or NoView. */ showHiddenWidgets: boolean; /** Whether widgets can be filled in form field creation mode, or a function read each time it is needed. */ allowInteractionInCreationMode: boolean | (() => boolean); } | null): void; /** * Gets the widget presentation set with setWidgetPresentation. * @returns The presentation (with a reader function resolved to its current value), or null when the normal policy applies. */ getWidgetPresentation(): { /** Widgets that are invisible, hidden or NoView are displayed. */ showHiddenWidgets: boolean; /** Widgets can be filled in form field creation mode. */ allowInteractionInCreationMode: boolean; } | null; /** * Reads a PKCS#12 certificate (.p12 / .pfx) before signing: checks the password and returns the signing certificate's summary and details (subject CN and so on, issuer, validity, version, signature algorithm, public key, * key usage, basic constraints, key identifiers, policies, CRL distribution points, authority information access, SHA-1 / MD5, the same as the certificate in verifySignatures results). * Use it to show the certificate before signing digitally. Does not change the document; password defaults to an empty string. * PASSWORD_REQUIRED for a wrong password; INVALID_SOURCE when it is not PKCS#12 or the algorithm is not supported. * @param certificate The PKCS#12 file bytes. * @param password The certificate password. Defaults to an empty string. * @returns A promise that resolves with the certificate summary and details. It rejects with PASSWORD_REQUIRED for a wrong password and INVALID_SOURCE when it is not PKCS#12 or the algorithm is not supported. */ getCertificateInfo(certificate: ArrayBuffer | Uint8Array, password?: string): Promise; /** * Digitally signs a signature field with a PKCS#12 certificate (bytes and password). The first argument is the field name (a signature field object is also accepted), optionally with reason and location; * appearance is the signature field appearance: an image (PNG / JPEG bytes) or a document (the page appearancePageNumber, page 1 by default); * without it, when the field has no hand-drawn / image signature, "signed by, date, reason, location" is drawn (the engine default is blank). * The certificate is PKCS#12 (.p12 / .pfx, 3DES / RC2 / AES encryption, RSA or EC P-256 / P-384 / P-521 keys); the private key is decrypted in the Worker and signs through WebCrypto, * and the CMS carries signedAttrs (signingCertificateV2 as required by the PAdES baseline), validating with standard tools. * The signature is written into the document right away, and getFileData then only saves incrementally (a full rewrite would invalidate the signature); returns the signed file, field name and signature field, and the same object is fired with digitalSignatureApplied. * PASSWORD_REQUIRED for a wrong password; INVALID_SOURCE when it is not PKCS#12 or the algorithm is not supported; note: the engine cannot write contactInfo (only a warning is logged). * field may be omitted (undefined / null): the selected signature field is signed; INVALID_HANDLE when none is selected; * appearance may also be a text appearance (DigitalSignatureTextAppearance: content lines, large text on the left, left-aligned content and so on), laid out by the engine. * @param field The field name or the signature widget. Omit it (`undefined` or `null`) to sign the selected signature field (ComPDFKit extension). * @param options The certificate, password, reason, location and appearance. The appearance can also be a {@link DigitalSignatureTextAppearance} (ComPDFKit extension). * @returns The signed file, the field name and the signature widget. */ sign(field: string | SignatureWidgetAnnotation | null | undefined, options: SignOptions): Promise; /** * Step one of external signing, for when the private key is not local (HSM, cloud signing, smart card). Takes the signing certificate (DER) and certificate chain, draws the appearance and writes a file with a placeholder, * and returns the hash to sign (SHA-256); call completeExternalSign with the signature. Do not change the document between the two steps. * @param field The signature field name or widget; omit it (undefined or null) to use the selected signature field. Rejects with INVALID_HANDLE when the field is not found or none is selected. * @param options The signing certificate (DER), optional certificate chain, appearance (image bytes, a document page or a text appearance), reason, location and the space reserved for the signature (estimatedContentsSize, 16384 bytes by default). * @returns A promise that resolves with the session: its id, the field name, the digest algorithm ('SHA-256'), the hash to sign and the document digest. */ prepareExternalSign(field: string | SignatureWidgetAnnotation | null | undefined, options: ExternalSignOptions): Promise; /** * Deletes a digitally signed signature field together with its signature, as one step in undo history: * undo restores the file before the deletion (the field and its signature come back, the signature still valid), redo deletes it again. The user permission check is skipped. * @param widget The signed signature widget. * @returns A promise that resolves when the field has been deleted. */ deleteSignedField(widget: SignatureWidgetAnnotation): Promise; /** * Step two of external signing: fills in the signature value or CMS container and writes it into the document; the result is the same as sign, and digitalSignatureApplied fires likewise. INVALID_SOURCE when the signature does not match. * @param session The session returned by prepareExternalSign, or its id. Rejects with INVALID_HANDLE when there is no such session. * @param value Either `signature`, the raw RSA / ECDSA signature of hashToSign, or `container`, a complete CMS signature container. * @returns A promise that resolves with the signed file, the field name and the signature widget. */ completeExternalSign(session: ExternalSignSession | string, value: ExternalSignValue): Promise; /** * Verifies the digital signature of a signature field (field name or signature field object): the result is as in Document.verifySignatures, plus widget. * documentStatus is unsigned when the field is not signed. * @param field The signature field name or widget. Rejects with INVALID_HANDLE when it is not found. * @param options Optional: trusted certificates (DER bytes), when certificate validity is checked (validationTime), and whether offline revocation checks use the document's revocation data (on by default). * @returns A promise that resolves with the verification result plus the verified widget. Pending annotation changes are committed first. */ verifySignature(field: string | SignatureWidgetAnnotation, options?: VerificationOptions): Promise; private readonly externalSessions; /** * Renders a preview of a digital signature appearance: draws a width x height signature field appearance from the layout options and returns RGBA pixels. * Use it for previews in an appearance dialog; passing the same appearance to sign produces the same appearance in the file. No signature field needs to be selected. * @param options The size (width, height) and layout: content and text lines, isContentAlignLeft, isDrawOnlyContent, isDrawLogo, and optional logo and image bytes. * @returns A promise that resolves with the width, height and RGBA pixels of the preview. It rejects when no document is loaded. */ renderDigitalSignaturePreview(options: DigitalSignaturePreviewOptions): Promise; /** Finds a signature field by field name (or signature field object). */ private signatureField; /** Appearance for sign: image bytes go to the Worker as is; a document's page is rendered at 3× the signature field size; with neither and no visible signature on the field, the signature info is drawn. */ private signAppearance; /** * Exports XFDF. fields / links both default to included without annotationList, and to excluded with it: * links decides ; fields writes field values in . Widgets live in the PDF and are not written. * With useDisplayAuthor, title uses the name mapped by setAnnotationDisplayAuthorMap. generateInlineAppearances is not used (appearances are in the engine). * @param options Optional: `annotationList` exports only these annotations; `links` includes link elements and `fields` includes field values (both default to true without annotationList and false with it); `useDisplayAuthor` writes author names mapped by setAnnotationDisplayAuthorMap; `generateInlineAppearances` has no effect. * @returns A promise that resolves with the XFDF string. Pending annotation changes are committed first; it rejects when no document is loaded. * @example * ```js * const { annotationManager } = instance.Core; * const xfdf = await annotationManager.exportAnnotations(); * localStorage.setItem('annotations', xfdf); * // Only the annotations on page 1 * const page1 = annotationManager.getAnnotationsList().filter(annot => annot.PageNumber === 1); * const page1Xfdf = await annotationManager.exportAnnotations({ annotationList: page1 }); * ``` */ exportAnnotations(options?: ExportAnnotationsOptions): Promise; /** * File attachments: the exported by the engine is decompressed hex but still says filter="FlateDecode" (so decompressing by filter fails); * it is changed to compressed hex (length is the compressed length) and mimetype is added. */ private attachmentsAsReference; /** Replaces each element in with the result of map (null removes it). */ private mapAnnots; /** Unrotated height of page n (pt). */ private pageHeight; /** Imports the form part of XFDF: values (and users) in go to the matching fields; no widgets are created. */ private importForms; /** Annotation elements in XFDF by page, and within a page in list order (when the stacking order changed; the engine exports in file order). */ private inListOrder; /** * Imports annotations from XFDF: new annotations are added ('add') and existing ones with the same Id are updated in place * ('modify'), both with `imported: true`; annotations removed by a command XFDF `` are deleted. The XFDF can be a string or a File / Blob holding it. * Resolves with the added, modified and deleted annotations. * @param xfdf The XFDF, as a string or a File / Blob holding it. Command XFDF (add / modify / delete) is applied as well, and field values in fields are filled in. * @returns A promise that resolves with the added, modified and deleted annotations. It rejects with a TypeError for other input and when no document is loaded. * @example * ```js * const { documentViewer, annotationManager } = instance.Core; * documentViewer.addEventListener('annotationsLoaded', async () => { * const xfdf = localStorage.getItem('annotations'); * if (xfdf) { * const annotations = await annotationManager.importAnnotations(xfdf); * console.log(`Imported ${annotations.length} annotations`); * } * }); * ``` */ importAnnotations(xfdf: string | Blob): Promise; /** * The engine import cannot create file attachments: they are created from the element itself (attributes icon, file, mimetype, ; filter defaults to FlateDecode), * and the file is attached with the commit (the same path as setFileData); an existing attachment with the same name is replaced in place by the imported one. */ private importFileAttachments; /** Stamps are not drawn as vector appearances (only the switch is stored); note: our stamps are drawn from appearance bitmaps anyway. */ disableStampVectorAppearance(): void; /** * Stores a date before which notes would be drawn in an older style. Notes have only one style here, so only the date is stored. * @param date The date. */ setOldStickyNoteRenderingDate(date: Date): void; /** * Sets the transform of an annotation canvas by zoom and rotation (Core.getPageMatrix, moving the origin to the matching corner of the canvas by rotation). * @param ctx The 2D context of the annotation canvas. * @param zoom The zoom level (1 is 100%). * @param rotation The rotation in quarter turns (0 to 3). */ setAnnotationCanvasTransform(ctx: CanvasRenderingContext2D, zoom: number, rotation: number): void; /** * When importing the engine rewrites the styles into its own set (font sizes in px, defaults added, italic and others dropped), * so the rich text style is reset from the original element and committed, writing /RC back unchanged. */ private importRichText; /** * The engine import ignores rotation: box-rotated annotations (rectangle, ellipse, stamp, free text) get the angle from the element (the XFDF rect is the rotated bounding box), * the unrotated box is derived from the bounding box and angle, and after committing the Worker rotates the appearance. */ private importRotations; /** * The engine drops when importing (format: mode="raw" encoding="hex", filter defaults to FlateDecode): * the decoded bytes and rate / channels / bits / encoding are recorded on the annotation and committed, and the Worker writes /Sound. */ private importSounds; /** The engine import ignores : the measurement info is reset from the scale and precision in the element and committed (the engine recomputes the result and writes /Measure). */ private importMeasures; /** What the rich text image looked like when last drawn (text, styles, font, text box size; not redrawn when unchanged). */ private readonly richTextFrom; /** * Before committing: free text with rich text styles is laid out by style and drawn as a text image (text box size, 4×, transparent background) that goes into the appearance with the commit; once the styles are removed it is no longer replaced. * Not drawn without a canvas (in Node); the appearance follows the engine. */ private prepareRichTextImage; /** Notes read from the Worker (reading the file, inserting / merging pages; by default the icon is written as the appearance on save, with no custom drawing): the properties at read time count as written, so it is rewritten only after changes and appearances written by other software are left alone. */ private seedGenerated; /** Annotation properties at the last write when custom drawing is written as the appearance (not redrawn when unchanged). */ private readonly generatedFrom; /** * Before saving: annotations with custom drawing and generateAppearance whose properties changed have their custom drawing drawn on a canvas and written as the appearance in the file * (multiplier at least 2, centered on the annotation center, clouds get max(line width, 12) of extra margin). */ private generateCustomAppearances; /** * Draws custom drawing as the appearance and writes it to the engine; not redrawn when properties are unchanged. quiet: no history and no UI-visible changes * (note color changes and the like are synced at any time so pages and thumbnails rendered by the engine keep up without waiting for a save). */ private generateAppearance; /** Properties that decide what the custom drawing looks like (excluding appearance pixels and markers in custom data). */ private drawSignature; /** * Exports the annotations added, modified and deleted since the last call as command XFDF (add / modify / delete), then starts a new change log and clears IsModified on all annotations. * Imported changes are not included. * @returns A promise that resolves with the command XFDF string. Pending annotation changes are committed first. */ exportAnnotationCommand(): Promise; /** * Applies a command XFDF (add / modify / delete), as importAnnotations does. * @param command The command XFDF, as a string or a File / Blob holding it. * @returns A promise that resolves with the added, modified and deleted annotations. */ importAnnotationCommand(command: string | Blob): Promise; /** * Exports all annotation changes since the document was loaded as command XFDF; unlike exportAnnotationCommand, the change log is never cleared. * @returns A promise that resolves with the command XFDF string. Pending annotation changes are committed first. */ exportDocumentAnnotationCommand(): Promise; private recordChange; private exportChanges; /** Applies the Worker's import result on the main thread: removes those deleted by commands, updates existing ones in place, adds new ones. */ private applyImport; /** * Uses your own subclass when reading or importing annotations with this XFDF element name ('square', 'freetext' and so on); later registrations win. * @param elementName The XFDF element name. * @param ctor The annotation class to use. * @returns False when the arguments are invalid; otherwise true. */ registerAnnotationType(elementName: string, ctor: AnnotationCtor): boolean; /** * Removes a custom annotation class registered for an XFDF element name. * @param elementName The XFDF element name. * @param ctor The annotation class to remove. * @returns False when the arguments are invalid; otherwise true. */ deregisterAnnotationType(elementName: string, ctor: AnnotationCtor): boolean; /** * Gets the custom annotation classes registered for each XFDF element name. * @returns Element name to registered classes. */ getRegisteredAnnotationTypes(): Record; private readonly registeredTypes; /** * Sets the current user name: the author of new annotations, replies and state replies, and the user checked by canModify. Fires updateAnnotationPermission. * @param name The user name. * @example * ```js * const { annotationManager } = instance.Core; * annotationManager.setCurrentUser('Jane Doe'); * console.log(annotationManager.getCurrentUser()); // 'Jane Doe' * ``` */ setCurrentUser(name: string): void; /** * Gets the current user name (author of new annotations and replies). * @returns The user name; 'Guest' by default. */ getCurrentUser(): string; /** * Gets the author name to display, mapped by the function set with setAnnotationDisplayAuthorMap. * @param author The author name stored in the annotation. * @returns The mapped name, or author unchanged when no map is set. */ getDisplayAuthor(author: string): string; /** * Sets how author names are displayed (see getDisplayAuthor). * @param fn Maps an author name to the name to display. */ setAnnotationDisplayAuthorMap(fn: (author: string) => string): void; /** * Admins can modify other users' annotations. * @example * ```js * const { annotationManager } = instance.Core; * annotationManager.setCurrentUser('Reviewer'); * annotationManager.promoteUserToAdmin(); // can now modify annotations by other authors * ``` */ promoteUserToAdmin(): void; /** Removes admin rights from the current user and fires updateAnnotationPermission. */ demoteUserFromAdmin(): void; /** * Whether the current user is an admin. * @returns True for an admin. */ isUserAdmin(): boolean; /** * Read-only: canModify is always false, and adds / deletes / modifications (except imports) and form filling reject. * @example * ```js * const { annotationManager } = instance.Core; * annotationManager.enableReadOnlyMode(); * console.log(annotationManager.isReadOnlyModeEnabled()); // true * annotationManager.disableReadOnlyMode(); * ``` */ enableReadOnlyMode(): void; /** Turns off read-only mode and fires updateAnnotationPermission. */ disableReadOnlyMode(): void; /** Modifiability changed: redraws the focus and the pages of selected annotations (selected ones that cannot be modified get only a box, no handles), then fires updateAnnotationPermission. */ private permissionChanged; /** * Whether read-only mode is on. * @returns True in read-only mode. */ isReadOnlyModeEnabled(): boolean; /** * Whether the current user can modify this annotation: not in read-only mode or when the annotation is read-only; when setPermissionCheckCallback is set it decides, * otherwise admins can modify everything and others only their own (annotations without an author too). * @param annotation The annotation to check. * @returns True when the current user can modify it. */ canModify(annotation: Annotation$1): boolean; /** * Checks whether the current user can modify the contents of an annotation: canModify is true and the contents are not locked (LockedContents). * @param annotation The annotation to check. * @returns True when the contents can be modified. */ canModifyContents(annotation: Annotation$1): boolean; /** * Sets a callback that decides whether the current user can modify an annotation, replacing the default author and admin check (read-only mode still applies). * @param fn Receives the annotation's author and the annotation; returns true to allow modifying it. * @example * ```js * const { annotationManager } = instance.Core; * // Allow editing your own annotations and those marked as shared * annotationManager.setPermissionCheckCallback((author, annotation) => * author === annotationManager.getCurrentUser() || annotation.getCustomData('shared') === 'true'); * ``` */ setPermissionCheckCallback(fn: (author: string, annotation: Annotation$1) => boolean): void; /** * Sets the order in which Tab moves between widgets when filling forms (across pages, in the given order). * @param widgets The widgets in tab order; the array is copied. Widgets not listed follow in document order. */ setTabOrder(widgets: WidgetAnnotation[]): void; /** * Gets the tab order of form widgets: the order set with setTabOrder (widgets no longer in the document are dropped, unlisted ones follow), or document order (page order, then PDF order within a page) when none was set. * @param pageNumber Optional page number (1-based); only widgets on that page are returned. * @returns The widgets in tab order. */ getTabOrder(pageNumber?: number): WidgetAnnotation[]; /** Tab moves to the next widget when filling forms (on by default). */ enableWidgetTabOrdering(): void; /** Turns off the tab order set with setTabOrder when filling forms. */ disableWidgetTabOrdering(): void; /** Allows dragging annotations onto other pages (the default). */ enableDraggingAcrossPages(): void; /** Keeps dragged annotations on their own page. */ disableDraggingAcrossPages(): void; /** * Whether annotations can be dragged onto other pages. * @returns True when dragging across pages is enabled. */ isDraggingAcrossPagesEnabled(): boolean; /** * Gets the difference annotations produced by DocumentViewer.startSemanticDiff. * @returns The annotations that mark text differences; empty when there are none. */ getSemanticDiffAnnotations(): Annotation$1[]; /** * Gets the snapping options of measurement tools: snap radius (screen pixels), indicator size and indicator color. * @returns A copy of the options. */ getSnapDefaultOptions(): SnapOptions; /** * Sets the snapping options of measurement tools. * @param options `radiusThreshold` (snap radius in screen pixels), `indicatorSize` and `indicatorColor`; omitted and unknown keys are ignored. */ setSnapDefaultOptions(options: Partial): void; /** * Gets the form field manager. * @returns The field manager. * @example * ```js * const { annotationManager } = instance.Core; * const field = annotationManager.getFieldManager().getField('customerName'); * if (field) * await field.setValue('Jane Doe'); * ``` */ getFieldManager(): FieldManager; /** * Gets the manager of the in-place text editors of free text annotations and form fields. * @returns The edit box manager. */ getEditBoxManager(): EditBoxManager; /** * Gets the manager of form field creation mode. * @returns The form field creation manager. */ getFormFieldCreationManager(): FormFieldCreationManager; /** Refuses writes in read-only mode; imports (imported) proceed as usual. */ private checkWritable; } /** * Core.Tools.Tool: the tool base class. Event methods (mouseLeftDown / mouseMove / mouseLeftUp / mouseDoubleClick / * mouseRightDown / contextMenu / keyDown / tap) are bound on the viewer element and dispatched by DocumentViewer. * No await and no load* / request* on the hot path. */ /** Tool name constants. */ declare const ToolNames: { /** Second freehand (ink) creation tool, registered by the UI. */ readonly FREEHAND2: "AnnotationCreateFreeHand2"; /** Pan tool: drags the view. */ readonly PAN: "Pan"; /** Annotation edit tool: selects, moves and resizes annotations. */ readonly EDIT: "AnnotationEdit"; /** Text selection tool. */ readonly TEXT_SELECT: "TextSelect"; /** Marquee zoom tool: zooms to a dragged rectangle. */ readonly MARQUEE: "MarqueeZoomTool"; /** Annotation eraser tool: erases ink and deletes annotations it touches. */ readonly ERASER: "AnnotationEraserTool"; /** Page crop tool. */ readonly CROP: "CropPage"; /** Snipping tool: captures a region of a page as an image. */ readonly SNIPPING: "SnippingTool"; /** Content editing tool: edits page text and images. */ readonly CONTENT_EDIT: "ContentEditTool"; /** Content editing tool that adds a text paragraph. */ readonly ADD_PARAGRAPH: "AddParagraphTool"; /** Content editing tool that adds an image. */ readonly ADD_IMAGE_CONTENT: "AddImageContentTool"; /** Text highlight creation tool. */ readonly HIGHLIGHT: "AnnotationCreateTextHighlight"; /** Text underline creation tool. */ readonly UNDERLINE: "AnnotationCreateTextUnderline"; /** Text squiggly underline creation tool. */ readonly SQUIGGLY: "AnnotationCreateTextSquiggly"; /** Text strikeout creation tool. */ readonly STRIKEOUT: "AnnotationCreateTextStrikeout"; /** Redaction creation tool. */ readonly REDACTION: "AnnotationCreateRedaction"; /** Redaction erasure tool. */ readonly REDACTION_ERASURE: "AnnotationCreateRedactionErasure"; /** Insert-text mark (caret) creation tool. */ readonly MARK_INSERT_TEXT: "AnnotationCreateMarkInsertText"; /** Replace-text mark creation tool. */ readonly MARK_REPLACE_TEXT: "AnnotationCreateMarkReplaceText"; /** Rectangle creation tool. */ readonly RECTANGLE: "AnnotationCreateRectangle"; /** Ellipse creation tool. */ readonly ELLIPSE: "AnnotationCreateEllipse"; /** Ellipse area measurement tool. */ readonly ELLIPSE_MEASUREMENT: "AnnotationCreateEllipseMeasurement"; /** Curve length measurement tool. */ readonly CURVE_MEASUREMENT: "AnnotationCreateCurveMeasurement"; /** Line creation tool. */ readonly LINE: "AnnotationCreateLine"; /** Arrow creation tool. */ readonly ARROW: "AnnotationCreateArrow"; /** Polyline creation tool. */ readonly POLYLINE: "AnnotationCreatePolyline"; /** Polygon creation tool. */ readonly POLYGON: "AnnotationCreatePolygon"; /** Cloudy polygon creation tool. */ readonly POLYGON_CLOUD: "AnnotationCreatePolygonCloud"; /** Arc creation tool. */ readonly ARC: "AnnotationCreateArc"; /** Callout (free text with a leader line) creation tool. */ readonly CALLOUT: "AnnotationCreateCallout"; /** Freehand (ink) creation tool. */ readonly FREEHAND: "AnnotationCreateFreeHand"; /** Freehand highlighter creation tool. */ readonly FREEHAND_HIGHLIGHT: "AnnotationCreateFreeHandHighlight"; /** Free text creation tool. */ readonly FREETEXT: "AnnotationCreateFreeText"; /** Date free text creation tool. */ readonly DATE_FREETEXT: "AnnotationCreateDateFreeText"; /** Sticky note creation tool. */ readonly STICKY: "AnnotationCreateSticky"; /** Image stamp creation tool. */ readonly STAMP: "AnnotationCreateStamp"; /** File attachment creation tool. */ readonly FILEATTACHMENT: "AnnotationCreateFileAttachment"; /** Rubber stamp (standard and custom stamps) creation tool. */ readonly RUBBER_STAMP: "AnnotationCreateRubberStamp"; /** Signature creation tool. */ readonly SIGNATURE: "AnnotationCreateSignature"; /** Distance measurement tool. */ readonly DISTANCE_MEASUREMENT: "AnnotationCreateDistanceMeasurement"; /** Perimeter measurement tool. */ readonly PERIMETER_MEASUREMENT: "AnnotationCreatePerimeterMeasurement"; /** Polygon area measurement tool. */ readonly AREA_MEASUREMENT: "AnnotationCreateAreaMeasurement"; /** Rectangular area measurement tool. */ readonly RECTANGULAR_AREA_MEASUREMENT: "AnnotationCreateRectangularAreaMeasurement"; /** Cloudy rectangular area measurement tool. */ readonly CLOUDY_RECTANGULAR_AREA_MEASUREMENT: "AnnotationCreateCloudyRectangularAreaMeasurement"; /** Arc measurement tool. */ readonly ARC_MEASUREMENT: "AnnotationCreateArcMeasurement"; /** Count measurement tool. */ readonly COUNT_MEASUREMENT: "AnnotationCreateCountMeasurement"; /** Scale calibration tool. */ readonly CALIBRATION_MEASUREMENT: "AnnotationCreateCalibrationMeasurement"; /** Text form field creation tool. */ readonly TEXT_FORM_FIELD: "TextFormFieldCreateTool"; /** Check box form field creation tool. */ readonly CHECK_BOX_FIELD: "CheckBoxFormFieldCreateTool"; /** Radio button form field creation tool. */ readonly RADIO_FORM_FIELD: "RadioButtonFormFieldCreateTool"; /** Combo box form field creation tool. */ readonly COMBO_BOX_FIELD: "ComboBoxFormFieldCreateTool"; /** List box form field creation tool. */ readonly LIST_BOX_FIELD: "ListBoxFormFieldCreateTool"; /** Signature form field creation tool. */ readonly SIG_FORM_FIELD: "SignatureFormFieldCreateTool"; /** Date picker form field creation tool. */ readonly DATE_PICKER_FORM_FIELD: "DatePickerFormFieldCreateTool"; }; /** Snap targets of measurement and line tools; values can be combined. See `setSnapMode`. */ declare enum SnapModes { /** Snap to the nearest point on a line. */ POINT_ON_LINE = 1, /** Snap to the midpoint of a line. */ LINE_MID_POINT = 2, /** Snap to the intersection of two lines. */ LINE_INTERSECTION = 4, /** Snap to the endpoint of a path. */ PATH_ENDPOINT = 8, /** The default combination: LINE_MID_POINT, LINE_INTERSECTION and PATH_ENDPOINT. */ DEFAULT = 14 } interface MouseLocation { x: number; y: number; pageNumber: number; } /** Tool events: creation tools fire annotationCreated (drawing starts) and annotationAdded (added to the document). */ interface ToolEvents { annotationCreated: [annotation: Annotation$1]; annotationAdded: [annotation: Annotation$1, info?: { creation?: AnnotationCreation; }]; /** A real tool-owned annotation, absent from AM until commit; null ends the draft. */ annotationDraftChanged: [annotation: Annotation$1 | null]; [name: string]: unknown[]; } declare class Tool extends EventHandler { protected readonly docViewer: DocumentViewer; /** Whether annotations can be dragged outside the page (off by default: dragging stops at the page edge and does not move in a direction where the annotation is larger than the page). */ static get ALLOW_ANNOTS_OUTSIDE_PAGE(): boolean; static set ALLOW_ANNOTS_OUTSIDE_PAGE(allow: boolean); /** Allows annotations to be dragged outside the page (sets ALLOW_ANNOTS_OUTSIDE_PAGE to true). */ static allowAnnotationsOutsidePage(): void; /** Keeps dragged annotations inside the page (sets ALLOW_ANNOTS_OUTSIDE_PAGE to false; the default). */ static disallowAnnotationsOutsidePage(): void; /** * Changes the cursor on hover by what is under the pointer (annotations, handles, text); the stamp, attachment, eraser and marquee zoom tools turn it off, * and it is turned back on when they switch out (Tool.ENABLE_ANNOTATION_HOVER_CURSORS). */ static ENABLE_ANNOTATION_HOVER_CURSORS: boolean; /** * Whether the edit tool selects text automatically when hovering over text (the edit tool selects text itself, so when this is off it * neither selects text nor shows the text cursor; the instance enable / disableTextSelection must also be on). Turned off on touch screens. */ static ENABLE_AUTO_SWITCH: boolean; /** Turns on automatic text selection by the edit tool (sets ENABLE_AUTO_SWITCH to true). */ static enableAutoSwitch(): void; /** Turns off automatic text selection by the edit tool (sets ENABLE_AUTO_SWITCH to false). */ static disableAutoSwitch(): void; /** Turns on hover cursors (sets ENABLE_ANNOTATION_HOVER_CURSORS to true). */ static enableAnnotationHoverCursors(): void; /** Turns off hover cursors: the tool's own cursor is always used (sets ENABLE_ANNOTATION_HOVER_CURSORS to false). */ static disableAnnotationHoverCursors(): void; /** Name the tool is registered under (one of ToolNames). */ name: string; /** Default style of annotations created by the tool (such as StrokeColor, StrokeThickness, Opacity); changed with setStyles. */ defaults: Record; /** The tool's own cursor: used when switching in and when hovering over empty space (default for the edit tool, crosshair for creation tools, text for text tools, grab for pan...). */ cursor: string; /** * Creates a tool. * @param docViewer The document viewer the tool works on. */ constructor(docViewer: DocumentViewer); /** * Gets the document viewer the tool works on. * @returns The document viewer. */ getDocumentViewer(): DocumentViewer; /** * Sets the name of the tool. * @param name The tool name. */ setName(name: string): void; /** * Changes the tool's default style (used by annotations created afterwards); fires toolUpdated. * @example * ```js * const { documentViewer, Annotations, Tools } = instance.Core; * const freeTextTool = documentViewer.getTool(Tools.ToolNames.FREETEXT); * freeTextTool.setStyles({ TextColor: new Annotations.Color(0, 0, 0), FontSize: '14pt', Font: 'Helvetica' }); * documentViewer.getTool(Tools.ToolNames.HIGHLIGHT).setStyles({ StrokeColor: new Annotations.Color(0, 255, 0), Opacity: 0.6 }); * ``` */ setStyles(styles: Record): void; /** Viewport event → the page and page coordinates under the pointer (unrotated page, top-left origin, pt). */ getMouseLocation(e: Pick): MouseLocation; /** Switch in: use the tool's own cursor. */ switchIn(_oldTool?: Tool): void; /** Switch out: the cursor returns to default. */ switchOut(_newTool?: Tool): void; /** Text cursor when the pointer is on text (within selection sensitivity): text for horizontal, vertical-text for vertical; the page text is prefetched when not cached. */ private textCursorAt; /** * Called when the left mouse button or a touch goes down on the viewer; does nothing in the base class. * @param _e The pointer event. */ mouseLeftDown(_e: PointerEvent): void; /** * Called when the pointer moves over the viewer; does nothing in the base class. * @param _e The pointer event. */ mouseMove(_e: PointerEvent): void; /** * Called when the left mouse button or a touch is released; does nothing in the base class. * @param _e The pointer event. */ mouseLeftUp(_e: PointerEvent): void; /** * Called on a double-click in the viewer; does nothing in the base class. * @param _e The mouse event. */ mouseDoubleClick(_e: MouseEvent): void; /** * Called when the right mouse button goes down on the viewer; does nothing in the base class. * @param _e The pointer event. */ mouseRightDown(_e: PointerEvent): void; /** * Called when the context menu is requested on the viewer; does nothing in the base class. * @param _e The mouse event. */ contextMenu(_e: MouseEvent): void; /** * Called when a key is pressed while the viewer has focus; does nothing in the base class. * @param _e The keyboard event. */ keyDown(_e: KeyboardEvent): void; /** * Called on a tap (a touch press and release without moving); does nothing in the base class. * @param _e The pointer event. */ tap(_e: PointerEvent): void; } /** * Core.DisplayMode: the single source of truth for layout modes and coordinate conversion (pageToWindow / windowToPage). * The visible-page and coordinate duties of the former PageInfoManager moved here. * * The layout is computed by formula without measuring the DOM: getMargin() px (CSS px, not scaled with zoom, 20 by default) between pages and around the outside; * the same in all display modes. Row height is the tallest page in the row, column width the widest page in the column; * in two-column modes the left column aligns right and the right column left, and pages are centered vertically in the row; cover mode puts a blank slot the size of the first page before it, and an incomplete last row is padded with slots the size of the last page. * Non-continuous modes only lay out the row of the current page. * The DOM is laid out by rows as a flow (DocumentViewer.syncFlow), and coordinates are still computed by these formulas; the two agree. * * Coordinate systems: * - page coordinates: unrotated page, top-left origin, y downward, in pt (what annotations use) * - window coordinates: px with the top-left of the viewer element as origin (zoom applied); independent of the scroll position, pointer coordinate = clientX − viewer element left */ /** Page layout modes. */ declare enum DisplayModes { /** One page at a time. */ Single = "Single", /** All pages in one vertically scrolling column. */ Continuous = "Continuous", /** Two pages side by side, one pair at a time. */ Facing = "Facing", /** Two pages side by side, scrolling continuously. */ FacingContinuous = "FacingContinuous", /** Two pages side by side, scrolling continuously, with the first page alone as a cover. */ Cover = "Cover", /** Two pages side by side, one pair at a time, with the first page alone as a cover. */ CoverFacing = "CoverFacing", /** Custom layout set with setParameters or setCustomFunctions. */ Custom = "Custom" } /** Public viewer methods read by DisplayMode */ type DisplayModeViewer = Pick & { getDocument: () => Pick | null; } & Partial> & { pageZoomKey?: () => string; }; interface WindowPoint { x: number; y: number; } /** Methods setCustomFunctions can override */ interface DisplayModeCustomFunctions { pageToWindow?: (pt: WindowPoint, pageNumber: number) => WindowPoint; windowToPage?: (pt: WindowPoint, pageNumber: number) => WindowPoint & { pageNumber: number; }; getSelectedPages?: (pt1: WindowPoint, pt2: WindowPoint) => { first: number | null; last: number | null; }; getVisiblePages?: (topMargin?: number, horizontalMargin?: number) => number[]; getPageTransform?: (pageNumber: number) => { x: number; y: number; width: number; height: number; }; createPageSections?: () => void; } /** A page layout mode together with the coordinate conversions between page and window coordinates. Page coordinates are unrotated, top-left origin, in PDF points; window coordinates are CSS pixels relative to the viewer element. */ declare class DisplayMode { readonly docViewer: DisplayModeViewer; private mode; private custom; private readonly scrollable; /** Custom grid set by setParameters */ private grid; private cache; /** * Creates a display mode. * @param docViewer The viewer to lay out. * @param mode The layout mode. * @param isScrollable Whether the layout scrolls. Defaults to true for every mode except Custom. */ constructor(docViewer: DisplayModeViewer, mode: DisplayModes, isScrollable?: boolean); /** * Returns the layout mode. * @returns The mode. */ getMode(): DisplayModes; /** * Checks whether the mode scrolls through all pages. * @returns true for Continuous, FacingContinuous and Cover. */ isContinuous(): boolean; /** * Checks whether the layout scrolls. * @returns The value given to the constructor, or true for every mode except Custom. */ IsScrollable(): boolean; /** Deprecated custom grid: columns columns, only rows [startRow, endRow) laid out; switches to Custom mode */ setParameters(columns: number, _totalRows: number, _currentRow: number, startRow: number, endRow: number): void; /** * Overrides layout and coordinate methods with your own implementations; methods not given keep the default behavior. * @param functions The methods to override. */ setCustomFunctions(functions: DisplayModeCustomFunctions): void; /** Lays out and returns the page numbers laid out */ createPageSections(): number[]; /** * Converts a point from page coordinates to window coordinates, applying zoom and the full page rotation. * @param pt Point in page coordinates. * @param pageNumber Page number (1-based). * @returns The point in window coordinates. */ pageToWindow(pt: WindowPoint, pageNumber: number): WindowPoint; /** Ignores the page's own /Rotate: page coordinates are in display orientation (sizes of getPageInfo), with only the view rotation added */ pageToWindowNoRotate(pt: WindowPoint, pageNumber: number): WindowPoint; /** * Converts a point from window coordinates to page coordinates of a page. * @param pt Point in window coordinates. * @param pageNumber Page number (1-based). * @returns The point in page coordinates, with the page number. */ windowToPage(pt: WindowPoint, pageNumber: number): WindowPoint & { /** The page number passed in. */ pageNumber: number; }; /** * Like windowToPage, but ignores the page's own rotation: the result is in display orientation, with only the view rotation removed. * @param pt Point in window coordinates. * @param pageNumber Page number (1-based). * @returns The point in display-oriented page coordinates, with the page number. */ windowToPageNoRotate(pt: WindowPoint, pageNumber: number): WindowPoint & { /** The page number passed in. */ pageNumber: number; }; /** The page each of the two window points falls on; null when on no page */ getSelectedPages(pt1: WindowPoint, pt2: WindowPoint): { /** The lower of the two page numbers; null when the point is on no page. */ first: number | null; /** The higher of the two page numbers; null when the point is on no page. */ last: number | null; }; /** * Pages intersecting the viewport (extended by topMargin viewport heights up and down, and horizontalMargin viewport widths left and right), * sorted by visible fraction in the unextended viewport, highest first. Extends by half a viewport each way by default, for prefetching. */ getVisiblePages(topMargin?: number, horizontalMargin?: number): number[]; /** Display size of the page (full rotation, zoom not applied) */ getPageTransform(pageNumber: number): { /** Always 0. */ x: number; /** Always 0. */ y: number; /** Displayed width in PDF points. */ width: number; /** Displayed height in PDF points. */ height: number; }; /** * Returns the offset of a page. * @param _pageNumber Page number (1-based); unused. * @returns Always (0, 0). */ getPageOffset(_pageNumber: number): WindowPoint; /** * Returns the CSS scale applied to the viewer element. * @returns Always 1 on both axes. */ getScale(): { /** Horizontal scale. */ scaleX: number; /** Vertical scale. */ scaleY: number; }; private unrotatedSize; /** Display size including the page's own /Rotate */ private displayedSize; /** Size including full rotation (page + view) */ private rotatedSize; private toWindow; private toPage; /** Pages not in the current layout (other pages in non-continuous modes) are treated as at the origin */ private box; private computeLayout; } /** Core.Search: Mode constants (combined by bitwise OR) and result codes ResultCode */ /** Text search options, combined with bitwise OR. */ declare enum SearchMode { /** Matches letter case exactly. */ CASE_SENSITIVE = 1, /** Matches whole words only. */ WHOLE_WORD = 2, /** Searches backwards, from the last page to the first. */ SEARCH_UP = 4, /** Reports a PAGE result each time a page has been searched. */ PAGE_STOP = 8, /** Highlights the results on the page. */ HIGHLIGHT = 16, /** Requests surrounding text in results; `ambientStr` is always filled. */ AMBIENT_STRING = 32, /** Treats the pattern as a regular expression. */ REGEX = 64, /** Treats `*` in the pattern as any text and `?` as any single character. */ WILD_CARD = 128 } /** resultCode of search results: DONE when finished, PAGE when a page is finished (PAGE_STOP mode), FOUND for a match */ declare const SearchResultCode: { /** The search finished. */ readonly DONE: 0; /** A page has been searched (PAGE_STOP mode). */ readonly PAGE: 1; /** A match was found. */ readonly FOUND: 2; }; type SearchResultCode = typeof SearchResultCode[keyof typeof SearchResultCode]; /** Search constants: `Mode` (SearchMode) and `ResultCode` (SearchResultCode). */ declare const Search: { /** Search options. */ readonly Mode: typeof SearchMode; /** Result codes. */ readonly ResultCode: { /** The search finished. */ readonly DONE: 0; /** A page has been searched (PAGE_STOP mode). */ readonly PAGE: 1; /** A match was found. */ readonly FOUND: 2; }; }; /** A position in page text. */ interface TextPosition { /** Page number (1-based). */ pageNumber: number; /** Character index in the page text; as a caret position, the character it is before. */ charIndex: number; } /** Result of hit testing a point against page text. */ interface TextHit extends TextPosition { /** Quad of the character that was hit, in page coordinates. */ quad: Quad; /** Index (0-based) of the line on the page. */ line: number; /** Index of the first character of the word */ word: number; /** Whether it falls on the left or right half of the character, deciding whether the caret (selection endpoint) is before or after it */ side: 'before' | 'after'; } interface LineIndex { readonly count: number; readonly startChar: Int32Array; /** Line end (exclusive), not including the \n after the line */ readonly endChar: Int32Array; /** 4 numbers per line: x, y, w, h (page coordinates) */ readonly bbox: Float32Array; } /** Text and character geometry of one page, in page coordinates. */ interface PageText { /** Page number (1-based). */ readonly pageNumber: number; /** Plain text in logical order, one \n between lines */ readonly text: string; /** 8 numbers per character: x1,y1,x2,y2,x3,y3,x4,y4 (bottom-left, bottom-right, top-right, top-left, page coordinates); top and bottom take the line's edges */ readonly quads: Float32Array; /** Number of characters, not counting the \n between lines. */ readonly charCount: number; /** Character ranges and bounding boxes of the lines. */ readonly lines: LineIndex; /** Writing direction of the page text. */ readonly direction: 'ltr' | 'rtl' | 'mixed'; /** Approximate memory used by this entry, counted against the text cache limit. */ readonly bytes: number; } /** Point a selection end handle points at (page coordinates): x / y is the bottom corner of the line, mid is the y of the line middle */ interface HandleSpot { pageNumber: number; x: number; y: number; mid: number; } /** The current text selection. */ interface TextSelection { /** Where the selection started; null without a selection. */ anchor: TextPosition | null; /** Where the selection ends (the moving end); null without a selection. */ focus: TextPosition | null; /** Character ranges per page (half-open), keyed by page number */ ranges: ReadonlyMap; } /** One text search result. */ interface SearchResult { /** FOUND (a match); PAGE / DONE results in search callbacks have no text or quads */ resultCode: SearchResultCode; /** Page number (1-based). */ pageNumber: number; /** Same as pageNumber (an alias of the same name on result objects) */ pageNum: number; /** The matched text; empty for PAGE and DONE results. */ resultStr: string; /** Surrounding text (as the engine FindNext context: at most 10 characters before the match and 30 more than the match, possibly spanning lines, newlines written as spaces), for the result list */ ambientStr: string; /** [start, end) of resultStr in ambientStr */ resultStrStart: number; /** End (exclusive) of resultStr within ambientStr. */ resultStrEnd: number; /** Quads of the matched text, one per line (page coordinates) */ quads: Quad[]; } interface TextCacheOptions { /** 20 by default */ maxPages?: number; /** 32MB by default; whichever of this and maxPages comes first */ maxBytes?: number; prefetchBefore?: number; prefetchAfter?: number; } /** Page text cache, text selection state and text hit testing for a document viewer. Coordinates are unrotated page coordinates (top-left origin, PDF points). */ declare class TextManager { private readonly docViewer?; private readonly onSelectionChanged?; private readonly cache; private readonly pending; private readonly queued; private options; private anchor; private focus; /** Cache generation: in-flight results are discarded after invalidate */ private generation; private searchSeq; /** onSelectionChanged: the selection changed (DocumentViewer fires textSelected and redraws the selection) */ constructor(docViewer?: DocumentViewer | undefined, onSelectionChanged?: ((pages: number[]) => void) | undefined); /** * Returns cached page text without loading it. * @param pageNumber Page number (1-based). * @returns The page text, or undefined when it is not cached. */ peekPageText(pageNumber: number): PageText | undefined; /** * Which character the point is on: among lines the point falls into vertically (after extending by tolerance), first the vertically nearest, then the horizontally nearest line; within the line, binary search by x; * null when the page text is not cached or no line is nearby */ hitTest(pageNumber: number, pt: { /** Horizontal position in page coordinates. */ x: number; /** Vertical position in page coordinates. */ y: number; }, tolerance?: number): TextHit | null; /** * Returns the current selection. * @returns Anchor, focus and the selected character ranges per page. */ getSelection(): TextSelection; /** Selection from anchor to focus (charIndex is the caret position: before which character), may span pages and be reversed */ setSelection(anchor: TextPosition, focus: TextPosition): void; /** Clears the selection; does nothing when nothing is selected. */ clearSelection(): void; /** Selected text; with a page number only that page. Pages are joined with \n (pages not cached cannot be read) */ getSelectedText(pageNumber?: number): string; /** Both ends of the selection in order (caret positions); null without a selection or when it is empty */ getSelectionEnds(): { /** The earlier end of the selection. */ start: TextPosition; /** The later end of the selection. */ end: TextPosition; } | null; /** * Points the selection end handles point at (page coordinates): the start is the bottom-left of the first line, the end the bottom-right of the last line; mid is the middle of that line * (only for pages with cached text and selected characters; null otherwise) */ getSelectionHandles(): { /** Spot of the start handle: bottom-left of the first selected line. */ start: HandleSpot; /** Spot of the end handle: bottom-right of the last selected line. */ end: HandleSpot; } | null; /** Quads of the selected text, one per line per page */ getSelectedQuads(pageNumber: number): Quad[]; /** * Loads the text of a page, from the cache when available. * @param pageNumber Page number (1-based). * @returns The page text. */ loadPageText(pageNumber: number): Promise; /** fire-and-forget, queued at P3 */ prefetch(pageNumbers: number[]): void; /** * Text range the engine selects in reading order between two points (unrotated page coordinates), page text indexes [start, end); null when no characters are selected. * Used by the 2.x compatibility layer to select text the same way as the 2.x API. */ getRangeAtPoints(pageNumber: number, pt1: { /** Horizontal position in page coordinates. */ x: number; /** Vertical position in page coordinates. */ y: number; }, pt2: { /** Horizontal position in page coordinates. */ x: number; /** Vertical position in page coordinates. */ y: number; }): Promise<[number, number] | null>; /** The Worker searches page text page by page and streams results back (in page order, reversed with SEARCH_UP); closing the iterator (break / return) cancels */ search(pattern: string, mode: SearchMode, pageNumbers?: number[]): AsyncIterable; /** Internal: like search, but one chunk per page (including pages without matches); DocumentViewer reports the end of each page from it */ searchByPage(pattern: string, mode: SearchMode, pageNumbers?: number[]): AsyncIterable<{ /** Page number (1-based). */ pageNumber: number; /** Matches on the page; empty when there are none. */ results: SearchResult[]; }>; /** * Changes the text cache limits and evicts pages that no longer fit. * @param options Limits to change; others keep their current values. */ setOptions(options: TextCacheOptions): void; /** Drops the cache of these pages (all when omitted); in-flight results are discarded */ invalidate(pageNumbers?: number[]): void; /** Number of cached pages, bytes and in-flight requests */ stats(): { /** Number of cached pages. */ pages: number; /** Approximate bytes used by the cache. */ bytes: number; /** Text requests in flight, by priority. */ queued: { /** Requests at interactive priority. */ interactive: number; /** Prefetch requests. */ prefetch: number; }; }; /** Expands the selection by page: first and last pages by caret position, middle pages whole (end is Infinity for pages not cached) */ private ranges; private changed; private load; /** Beyond the page or byte limit, evicts the pages farthest from the current page (pages with the selection are not evicted) */ private evict; private pageId; /** Text version of the document (refreshTextData adds one); the cache is invalidated by it */ private textVersion; } declare class AnnotationHistoryManager extends EventHandler<{ /** The history changed (a step was added, undone, redone or cleared). */ historyChanged: []; }> { private readonly manager; /** Event names of the history manager. */ static readonly Events: { /** 'historyChanged': the history changed. */ readonly HISTORY_CHANGED: "historyChanged"; }; /** Maximum number of steps (setMaxHistorySize). */ private maxSteps; /** One annotationChanged is one step. */ private steps; /** Steps done: steps[position - 1] is the most recent; those after it can be redone. */ private position; /** The latest properties of each annotation, used as the "before" of the next modification. */ private readonly last; private notifyTimer; /** The step of the current batch (null after the batch closes); merged into only while it is still the most recent step. */ private batch; /** Depth of internal holdBatch: the batch does not close with the microtask while it is above 0. */ private held; /** An explicit batch enters history only at end, separate from synchronous / eraser batches that enter immediately. */ private explicitBatch; private batchId; /** New records during apply are pushed after the position is committed, so they do not overwrite the step being undone. */ private deferred; private applying; private pending; /** When the Worker rejects a write, AM restores properties / lists with ordinary events; after a failure such compensation must not be recorded as a user operation. */ private readonly replayWrites; /** * Creates a history manager that records the annotation changes of an annotation manager. * @param manager The annotation manager whose changes are recorded. */ constructor(manager: AnnotationManager); /** Maximum number of steps (at least 1); the oldest are dropped when exceeded (setMaxHistorySize). */ setMaxHistorySize(size: number): void; /** * Whether there is a step to undo. * @returns True when undo is possible. */ canUndo(): boolean; /** * Whether there is a step to redo. * @returns True when redo is possible. */ canRedo(): boolean; /** Captures the properties before a modification for later records; does not commit the document or add history. */ takeSnapshot(annotation: Annotation$1): void; /** Starts an explicit batch spanning awaits; repeated calls return the same id. Cannot start while undo / redo is busy. */ beginBatchOperation(): string; /** Commits the explicit batch as one step; an empty batch is not recorded. */ endBatchOperation(): void; /** Discards only the records of the current explicit batch; the document and earlier undo / redo stay. */ cancelBatchOperation(): void; /** * Whether an explicit batch (beginBatchOperation) is in progress. * @returns True while a batch is open. */ isBatchMode(): boolean; /** Includes queued requests not yet started; all native entry points share this state. */ isInProgress(): boolean; /** The committed history counts; an explicit batch is not counted before end. Each call returns an independent snapshot. */ getHistoryState(): { /** Whether there is a step to undo. */ canUndo: boolean; /** Whether there is a step to redo. */ canRedo: boolean; /** Number of steps that can be undone. */ undoCount: number; /** Number of steps that can be redone. */ redoCount: number; }; /** Undo / redo are queued: while the previous adds / deletes are still in the Worker, the next cannot start (otherwise annotations would be in the list without being registered and could not be deleted later). */ private queue; private enqueue; /** Undoes the last step. Queued behind pending writes and other undo / redo calls. */ undo(): Promise; /** Redoes the last undone step. Queued behind pending writes and other undo / redo calls. */ redo(): Promise; private navigate; /** Clears the whole history, including an open batch. */ clear(): void; /** Composite steps also take part in object replacement, discard and page history cleanup. */ private leafSteps; private pruneSteps; private record; private appendStep; /** The batch closes on the next microtask (not during holdBatch). */ private closeBatchSoon; /** After a failure, removes the compensations that restored the original state / Worker conflict data; new records of other annotations are kept. */ private replayWrite; /** Undo: added ones are deleted, deleted ones put back, modified ones restored to before; redo does the reverse. */ private apply; /** Multiple changes in one round merge into one historyChanged. */ private notify; } /** * Core.ContentEditHistoryManager: calls the engine's native CanUndo / CanRedo / Undo / Redo directly, without snapshots. * Native undo is one stack per page; this records "which page, how many steps" per operation in order (a replace is two steps, delete + insert), and undo calls native Undo on that page repeatedly; * one history entry can span pages (find and replace across pages), undone part by part in reverse. * Separate from the AnnotationHistoryManager stack. */ /** One history entry: parts of "which page, how many steps" in order (find and replace across pages has several parts). */ type Entry = Array<{ pageNumber: number; steps: number; }>; interface ContentEditHistoryManagerEvents { undoRedoStatusChanged: [status: { canUndo: boolean; canRedo: boolean; }]; } /** Undo and redo history of content editing, separate from the annotation history. */ declare class ContentEditHistoryManager extends EventHandler { private readonly docViewer?; private undoStack; private redoStack; /** * Creates the history; the document viewer creates one, available through `documentViewer.getContentEditHistoryManager()`. * @param docViewer The viewer whose content edits are tracked. */ constructor(docViewer?: DocumentViewer | undefined); /** * Checks whether there is an entry to undo. * @returns true when undo is available. */ canUndo(): boolean; /** * Checks whether there is an entry to redo. * @returns true when redo is available. */ canRedo(): boolean; /** Undoes the latest entry; does nothing when there is none. Fires undoRedoStatusChanged. */ undo(): Promise; /** Redoes the latest undone entry; does nothing when there is none. Fires undoRedoStatusChanged. */ redo(): Promise; /** Merges the latest count entries into one (such as creating a paragraph + writing its content, or all replacements of one find and replace); returns the entry. */ createCommandObject(count: number): Entry | undefined; /** Returns a snapshot of the logical undo and redo entry counts; native commands inside composite entries are not counted separately. */ getHistoryState(): { /** Number of entries that can be undone. */ undoCount: number; /** Number of entries that can be redone. */ redoCount: number; }; private replay; private changed; } /** Kind of a content box. */ declare enum Types { /** A text box. */ TEXT = "text", /** An image box. */ OBJECT = "object" } /** Worker attributes → TextAttributes. */ declare function toTextAttributes(a: Record): TextAttributes; /** * The 24 namespace functions of Core.ContentEdit. * Direct calls (13): SetCharsFont* / AddUnderline / AddStrikethrough / SetTextAligning* / GetTextStyle / GetTextByRange / CreateNewTextArea + InsertText * Plus 4 standalone functions of the same shape (like setContentFontSize / setTextColor; there were none for line spacing / paragraph spacing / character spacing / opacity): * setContentLineSpacing / setContentParagraphSpacing / setContentCharacterSpacing / setTextOpacity, read back through loadTextAttributes * Composed (9): setContent / updateDocumentContent (DeleteChars + InsertText), searchAndReplaceText, getContentEditingFonts, 5 path functions forwarded to Core * Not implemented (2): getLongTextReflow / setLongTextReflow (the engine has no long-text reflow switch) * Format functions take a box or an editor: while editing with selected text they apply only to the selection (committing pending changes in the editor first), otherwise to the whole box. */ /** Names of the content editing events. */ declare const Events: { /** 'undoRedoStatusChanged': fired by ContentEditHistoryManager when undo or redo availability may have changed. */ readonly UNDO_REDO_STATUS_CHANGED: "undoRedoStatusChanged"; }; /** Text style of a range in a text content box. Read values describe the first character of the range unless noted; set values apply to the whole range. */ interface TextAttributes { /** Font name, such as 'Helvetica'. See getContentEditingFonts for settable names. */ fontName?: string; /** Font size in points. */ fontSize?: number; /** Text color. Read as '#rrggbb'; set as '#rrggbb' or 'rgb(r, g, b)' with channels 0-255. */ color?: string; /** Whether the text is bold. */ bold?: boolean; /** Whether the text is italic. */ italic?: boolean; /** Whether the text is underlined. */ underline?: boolean; /** Whether the text is struck out. */ strikeout?: boolean; /** Paragraph alignment. */ textAlign?: 'left' | 'center' | 'right' | 'justify'; /** Line spacing as a multiple (1 is single); reads the line of the first character in the range, sets every line in the range. */ lineSpacing?: number; /** Space after paragraph (pt); reads the paragraph of the first character, sets every paragraph in the range. */ paragraphSpacing?: number; /** Character spacing (pt); null when it differs within the range. */ characterSpacing?: number | null; /** Text opacity 0–1. */ opacity?: number; /** * Sets bold and italic together (ComPDFKit extension): `0` / `'regular'`, `1` / `'bold'`, `2` / `'italic'` / `'oblique'`, * `3` / `'boldItalic'` / `'boldOblique'`. An explicit `bold` or `italic` in the same call overrides its half. Write-only. */ fontStyle?: FontStyle; } /** Combined bold / italic style accepted by {@link TextAttributes.fontStyle} (ComPDFKit extension). */ type FontStyle = 0 | 1 | 2 | 3 | 'regular' | 'bold' | 'italic' | 'oblique' | 'boldItalic' | 'boldOblique'; /** * A character range in a text content box (ComPDFKit extension): either character indices `[startIndex, endIndex)` in the * box text (paragraphs joined by one `\n`), or layout positions such as `ContentBox.getTextSelectionGeometry().range`. */ type ContentTextRange = { /** Index of the first character in the range. */ startIndex: number; /** Index after the last character in the range. */ endIndex: number; } | { /** Layout position where the range starts. */ start: ContentTextPosition; /** Layout position where the range ends. */ end: ContentTextPosition; }; /** Options for addNewParagraph. */ interface AddNewParagraphOptions { /** The viewer whose document to use (there is no global viewer, so it must be given). */ documentViewer: DocumentViewer; /** Page number (1-based) of the new paragraph. */ pageNumber: number; /** Page coordinates (top-left origin, pt). */ position: { /** Top edge. */ top: number; /** Left edge. */ left: number; /** Right edge. */ right: number; /** Bottom edge. */ bottom: number; }; /** Text style of the new paragraph. */ font?: TextAttributes; } /** Options for searchAndReplaceText. */ interface SearchAndReplaceOptions { /** The viewer whose document to search. */ documentViewer: DocumentViewer; /** Text to find. */ searchText: string; /** Replacement text. */ replaceWith: string; /** All pages by default. */ pageNumbers?: number[]; /** Whether matching is case-sensitive. Defaults to false. */ matchCase?: boolean; /** Whether only whole words match. Defaults to false. */ wholeWords?: boolean; } /** Target of format functions: a box, or an editor (its selected range). */ type ContentTarget = ContentBox | ContentBoxEditor; /** * Toggles bold on the target, based on the style of the first character of the range. * @param target A content box or its editor. While the box is being edited with text selected, only the selection changes; otherwise the whole box does. */ declare function toggleBoldContents(target: ContentTarget): Promise; /** * Toggles italic on the target, based on the style of the first character of the range. * @param target A content box or its editor. While the box is being edited with text selected, only the selection changes; otherwise the whole box does. */ declare function toggleItalicContents(target: ContentTarget): Promise; /** * Toggles underline on the target, based on the style of the first character of the range. * @param target A content box or its editor. While the box is being edited with text selected, only the selection changes; otherwise the whole box does. */ declare function toggleUnderlineContents(target: ContentTarget): Promise; /** * Toggles strikeout on the target, based on the style of the first character of the range. * @param target A content box or its editor. While the box is being edited with text selected, only the selection changes; otherwise the whole box does. */ declare function toggleStrikeContents(target: ContentTarget): Promise; /** For font names see getContentEditingFonts. */ declare function setContentFont(target: ContentTarget, fontName: string): Promise; /** Font size: a number or '14' / '14pt' / '14px' (all treated as pt). */ declare function setContentFontSize(target: ContentTarget, size: string | number): Promise; /** Color: '#rrggbb', 'rgb(r, g, b)' or Annotations.Color. */ declare function setTextColor(target: ContentTarget, color: string | Color): Promise; /** Line spacing as a multiple (1 is single): every line in the range; multiple lines are still one history entry. */ declare function setContentLineSpacing(target: ContentTarget, spacing: number): Promise; /** Space after paragraph (pt): every paragraph in the range. */ declare function setContentParagraphSpacing(target: ContentTarget, spacing: number): Promise; /** Character spacing (pt): every character in the range. */ declare function setContentCharacterSpacing(target: ContentTarget, spacing: number): Promise; /** Text opacity 0–1 (for image boxes see ContentImageBoxEditor.setOpacity). */ declare function setTextOpacity(target: ContentTarget, opacity: number): Promise; /** Paragraph alignment (paragraphs in the range). */ declare function alignContents(target: ContentTarget, align: TextAttributes['textAlign']): Promise; /** Attributes of the first character in the range; underline, strikethrough, bold and italic are true only when the whole range has them; range is an explicit character range. */ declare function loadTextAttributes(target: ContentTarget, range?: ContentTextRange): Promise; /** Sets several attributes at once as one history entry; range is an explicit character range (otherwise as above: the selected text or the whole box); fontStyle sets bold and italic together. */ declare function setTextAttributes(target: ContentTarget, attrs: TextAttributes, range?: ContentTextRange): Promise; /** Full text of the box, with \n between paragraphs. */ declare function getContent(box: ContentBox): Promise; /** One span of text (spanObjects of getContent; one per paragraph here, with only text and paragraph number). */ interface SpanObject { /** Text of the span. */ text: string; /** Index (0-based) of the paragraph the span belongs to. */ paragraphIndex: number; /** Font family; not filled in by getContent and ignored by setContent. */ fontFamily?: string; /** Font weight; not filled in by getContent and ignored by setContent. */ fontWeight?: string; /** Font size; not filled in by getContent and ignored by setContent. */ fontSize?: string; /** Font style; not filled in by getContent and ignored by setContent. */ fontStyle?: string; /** Text color; not filled in by getContent and ignored by setContent. */ color?: string; /** Alignment; not filled in by getContent and ignored by setContent. */ align?: string; /** Leading mode; not filled in by getContent and ignored by setContent. */ leadingMode?: string; /** Start indent; not filled in by getContent and ignored by setContent. */ startIndent?: string; /** Start of the underline; not filled in by getContent and ignored by setContent. */ underlineStart?: number; /** End of the underline; not filled in by getContent and ignored by setContent. */ underlineEnd?: number; } /** Result of ContentEditManager#getContent. */ interface TextDetails { /** Box content with one HTML-escaped

element per paragraph. */ xmlString: string; /** One span per paragraph. */ spanObjects: SpanObject[]; } /** Box content, one

per paragraph (HTML-escaped). */ declare function getDocumentContent(box: ContentBox): Promise; /** CreateNewTextArea + InsertText; enters content editing mode first when not in it. */ declare function addNewParagraph(text: string, options: AddNewParagraphOptions): Promise; /** Replaces the whole box with content (DeleteChars + InsertText, recorded as one history entry). */ declare function setContent(box: ContentBox, content: string): Promise; /** content is HTML split into

paragraphs (the getDocumentContent format) or plain text. */ declare function updateDocumentContent(box: ContentBox, content: string): Promise; /** * Finds and replaces in the text boxes of these pages (all pages by default) and returns the number of replacements; one call is one history entry. Enters content editing mode first when not in it. * The box's full text is mapped character by character to engine positions in the Worker; replacements within a box go from back to front so earlier positions are unaffected. */ declare function searchAndReplaceText(options: SearchAndReplaceOptions): Promise; /** Font names settable for content: the standard 14 fonts (the engine takes built-in fonts by name). */ declare function getContentEditingFonts(): string[]; /** * Returns the Worker folder; same as the top-level getWorkerPath (content editing shares the document Worker). * @returns The Worker folder. * @deprecated Use the top-level getWorkerPath. */ declare function getWorkerPath(): string; /** * Sets the Worker folder; same as the top-level setWorkerPath. * @param path Folder URL or path. * @deprecated Use the top-level setWorkerPath. */ declare function setWorkerPath(path: string): void; /** * Returns the Worker folder, which also holds the content editing resources. * @returns The Worker folder. * @deprecated Use the top-level getWorkerPath. */ declare function getResourcePath(): string; /** * Sets the Worker folder, which also holds the content editing resources. * @param path Folder URL or path. * @deprecated Use the top-level setWorkerPath. */ declare function setResourcePath(path: string): void; /** * Starts the shared document Worker early; same as the top-level preloadPDFWorker. * @deprecated Use the top-level preloadPDFWorker. */ declare function preloadWorker(): Promise; /** * ContentBoxEditor: text box editor with live editing. Every insertion and deletion goes to the Worker immediately (DeleteChars / InsertText) and the page is redrawn, * so what you see is the text laid out by the engine. The caret and selection are drawn on the annotation layer at the positions from the engine (GetTextCursorPoints / GetSelectLineRects); * keyboard and IME input go to an invisible text box (placed at the caret so the candidate window follows it). * Positions are character indexes in the full text (one \n between paragraphs). Consecutive typing or deleting merges into one content history entry. * insertHyperlink: places a link annotation opening a URL (SetLinkUri) over the rectangles of the selected text (GetSelectLineRects). */ interface ContentBoxInput { element: HTMLTextAreaElement; composing: boolean; } /** Style of a new paragraph (CreateNewTextArea); color is integer RGB 0–255 (the engine's channel range). */ interface NewParagraphStyle { fontName?: string; fontSize?: number; color?: [number, number, number]; bold?: boolean; italic?: boolean; textAlign?: string; } /** Editor of a text content box: handles caret, selection, typing and deleting while the box is being edited. */ declare class ContentBoxEditor { readonly box: ContentBox; private input; /** The blinking caret (a vertical line element over the page; only its visibility toggles, the annotation layer is not redrawn). */ private caretElement; private blinkTimer; private detachZoom; private text; private caret; private anchor; private caretData; /** Invisible characters (only when the manager has toggleInvisibleCharacters on). */ private invisibles; /** Operations sent to the Worker are queued in order. */ private queue; private opening; private inputState; private last; /** History length when opened: when a new paragraph closes, everything is undone (no input) or merged into one entry. */ private historyStart; /** New paragraph: the box is removed on close when the text is empty. */ private removeIfEmpty; /** contentEditSelectionChange fires for caret / selection changes only after open completes. */ private ready; /** A later pointer gesture invalidates an unfinished native paragraph hit. */ private paragraphRequest; /** * Creates an editor; use ContentBox.startContentEditing instead of calling this. * @param box The box being edited. */ constructor(box: ContentBox); /** Ends editing. */ blur(): Promise; /** The selected range (character indexes, one \n between paragraphs); both are the caret position when nothing is selected. */ getCurrentSelection(): { /** Index of the first selected character. */ startIndex: number; /** Index after the last selected character. */ endIndex: number; }; /** Sets the selection (end defaults to the caret position); the caret is at end. */ setSelection(start: number, end?: number): Promise; /** The current full text (one \n between paragraphs). */ getText(): string; /** Attributes of the selected text (the whole box when nothing is selected), same as ContentEdit.loadTextAttributes. */ getTextAttributes(): Promise; /** Adds a link to the selected text: places a link annotation opening url over the selection bounds (SetLinkUri) and returns it; throws when no text is selected. */ insertHyperlink(url: string): Promise; /** Opens the link address (in a new window). */ loadHyperLinkURL(url: string): void; /** * Inserts at the caret (replacing the selection if any). * The caret / selection is read when this operation's turn comes (not at call time): calling repeatedly without waiting (a script sending type('H'), type('e')...) still applies in call order. */ type(text: string): Promise; /** Deletes backward (Backspace): deletes the selection if any, otherwise the character before the caret (like type, the caret is read when its turn comes). */ deleteBackward(): Promise; /** Deletes forward (Delete) (like type, the caret is read when its turn comes). */ deleteForward(): Promise; /** Select the native paragraph at an unrotated page point (pt), after queued edits. */ selectParagraphAt(x: number, y: number): Promise; private detachInput; /** Queues replacing [start, end) with text (the range is fixed; the caret is not read again). */ private applyEditQueued; /** Replaces [start, end) with text: the Worker returns the new full text and caret; consecutive typing / deleting merges into the previous history entry (only called inside a queued task). */ private applyEdit; /** Sets the selection and gets caret and selection positions (only called inside a queued task). */ private select; /** Range changes announce once; a completed paragraph gesture also announces when repeated. */ private announce; /** Gets invisible characters (only called inside a queued task). */ private readInvisibles; private enqueue; /** Text received by the text box (typing, IME commits) goes to the Worker and the text box is cleared. */ private takeInput; private keyDown; private clipboard; /** Places the text box (the IME candidate window follows it) and the blinking caret at the caret; the caret is hidden with a selection; any caret move restarts blinking from "on". */ private placeInput; private redraw; } /** An image box shown while editing page content. Its editor is ContentImageBoxEditor. */ declare class ContentImageBox extends ContentBox { /** Box kind, always Types.OBJECT. */ readonly type: Types; } /** * ContentImageBoxEditor: image box editor; all operations can be undone. * Engine: RotateImage / HorizontalMirrorImage / VerticalMirrorImage / CutWithRect / SetImageTransparency / GetImageTransparency / ReplaceImageArea / ExtractOriginalImage */ /** Editor of an image content box. Every operation can be undone. */ declare class ContentImageBoxEditor { readonly box: ContentImageBox; /** * Creates an editor; use ContentBox.startContentEditing instead of calling this. * @param box The image box being edited. */ constructor(box: ContentImageBox); /** Rotates clockwise by degree degrees. */ rotate(degree: 90 | 180 | 270): Promise; /** Current rotation angle (degrees). */ getRotation(): Promise; /** Mirrors the image horizontally. */ flipHorizontal(): Promise; /** Mirrors the image vertically. */ flipVertical(): Promise; /** Crops to a rectangle in page coordinates (only the part inside is kept). */ crop(rect: Rect): Promise; /** 0–1 */ setOpacity(opacity: number): Promise; /** * Returns the image opacity. * @returns Opacity from 0 to 1. */ getOpacity(): Promise; /** Replaces the image with another (position and size unchanged): a dataURL, Blob or file bytes. */ replaceImage(image: string | Blob | ArrayBuffer): Promise; /** The original image (PNG); requires the browser's OffscreenCanvas. */ extractImage(): Promise; private info; } /** ContentBox: a text box (IsTextArea); for image boxes see ContentImageBox. */ interface ContentBoxAttributes { rect: Rect; type: Types; } /** Result of getBoxData; text boxes include the full text. */ interface ContentBoxInfo { id: string; pageNumber: number; type: Types; rect: Rect; text?: string; } /** Layout positions in the content text model; charIndex -1 means before the first character. */ interface ContentTextPosition { /** Section index. */ sectionIndex: number; /** Line index within the section. */ lineIndex: number; /** Run index within the line. */ runIndex: number; /** Character index within the run; -1 means before the first character. */ charIndex: number; } /** Text and line rectangles of a selection in a text content box. */ interface ContentTextSelectionGeometry { /** Text of the native layout range (including native CRLF paragraph terminators). */ text: string; /** Native line rectangles in unrotated page points, independent of zoom and view rotation. */ rects: Rect[]; /** Start and end layout positions of the selection. */ range: { /** Start position of the selection. */ start: ContentTextPosition; /** End position of the selection. */ end: ContentTextPosition; }; } /** A text box shown while editing page content. Image boxes are ContentImageBox. */ declare class ContentBox { /** Latest box data from the Worker, refreshed after every operation. */ data: ContentBoxData; /** Page number (1-based) of the box. */ readonly pageNumber: number; protected readonly manager?: ContentEditManager | undefined; protected readonly docViewer?: DocumentViewer | undefined; /** Box kind; Types.TEXT for text boxes. */ readonly type: Types; protected editor: ContentBoxEditor | ContentImageBoxEditor | null; private opening; private textModel; private textSelection; /** data is replaced with the Worker's latest data by ContentEditManager after every operation. */ constructor( /** Latest box data from the Worker, refreshed after every operation. */ data: ContentBoxData, /** Page number (1-based) of the box. */ pageNumber: number, manager?: ContentEditManager | undefined, docViewer?: DocumentViewer | undefined); /** Box id, unique within the document while content editing is active. */ get id(): string; /** * Set a rectangle in unrotated page coordinates (pt), with one content undo entry. * visible (default): move/resize the visible bounds, retaining image crop proportions. * frame: set the complete image/text frame, as the native SetFrame primitive does. * clip: for a cropped image use SetClipRect; otherwise use SetFrame. This preserves * the distinction between an image's frame and clip placement without exposing handles. * Programmatic coordinates are not clamped to tool safe distances. */ setRect(rect: Rect, options?: { /** How the rectangle is applied: 'visible' (default), 'frame' or 'clip' (image boxes only). */ mode?: 'visible' | 'frame' | 'clip'; }): Promise; /** Current character range in this text block, including an inactive block. Detached snapshot. */ getTextSelection(): { /** Index of the first selected character. */ startIndex: number; /** Index after the last selected character. */ endIndex: number; } | null; /** Synchronous selection read from the authoritative Worker text model, never the reading selection. */ getSelectedText(): string; /** * Geometry for the character selection captured at call time, including an inactive block. * Detached native layout snapshot; null when no character range is retained. * This read does not open an editor, alter selection, or apply tool safe distances. */ getTextSelectionGeometry(): Promise; /** Select characters without opening a keyboard editor or changing the selected boxes. */ setTextSelection(start: number, end?: number): Promise; /** Clear characters independently of block multi-selection; active editor collapses at its caret. */ clearTextSelection(): Promise; /** Rectangle (page coordinates) and type. */ getBoxAttributes(): ContentBoxAttributes; /** * Returns a snapshot of the box. * @returns Id, page number, type and rectangle (page coordinates); text boxes also include their full text. */ getBoxData(): Promise; /** * Checks whether an editor is open on the box. * @returns true while the box is being edited. */ isEditing(): boolean; /** * Stacking order (names follow AnnotationManager.bringToFront / bringToBack): bring to front, forward one, send to back, backward one. * Each move of an image box is one history entry. Note: stacking moves of text boxes cannot be undone (the engine records undo only for bring-to-front and only when it actually moves, not the other three, so the step counts would not match; text boxes are never recorded). */ bringToFront(): Promise; /** Moves the box one step forward in the stacking order. */ bringForward(): Promise; /** Moves the box to the back of the stacking order. */ bringToBack(): Promise; /** Moves the box one step backward in the stacking order. */ bringBackward(): Promise; /** * Returns the editor open on this box while it is being edited. * @returns The text or image editor, or null when the box is not being edited. */ getEditor(): ContentBoxEditor | ContentImageBoxEditor | null; /** Opens an editor on the box (stopping editing of other boxes first); fires contentBoxEditStarted. */ startContentEditing(input?: ContentBoxInput): Promise; /** Commits the changes in the editor and closes it; fires contentBoxEditEnded. */ stopContentEditing(options?: { /** Keeps the box's text selection after editing stops. Defaults to false. */ preserveSelection?: boolean; }): Promise; } /** * Safe distance for content editing: the minimum distance of editing boxes from the page edge (page coordinates in pt). * Moving clamps the whole box into the page (keeping the size when it is smaller than the page); resizing clamps each coordinate separately. */ type SafeDistanceType = 'common' | 'text' | 'image'; type Frame = [number, number, number, number]; /** * Core.ContentEditManager: documentViewer.getContentEditManager(). * startContentEditMode opens an editing session for the current page in the Worker (InitEditPage / BeginEdit); other pages open when they are drawn; * text and image boxes map to ContentBox / ContentImageBox and are drawn as dashed boxes on the annotation layer (solid when selected). * After every operation the page's boxes are updated from the Worker's latest list (objects with the same id are reused). endContentEditMode calls EndEdit on opened pages and redraws them. */ interface ContentEditManagerEvents { contentEditModeStarted: []; contentEditModeEnded: []; contentBoxEditStarted: [box: ContentBox]; contentBoxEditEnded: [box: ContentBox]; contentBoxAdded: [box: ContentBox]; contentBoxDeleted: [box: ContentBox]; contentEditSelectionChange: [box: ContentBox | null, detail?: { granularity: 'paragraph'; }]; } type CursorPosition = 'start' | 'end'; /** Manages page content editing: entering and leaving content edit mode, the text and image boxes of each page, selection, formatting, copy and paste. */ declare class ContentEditManager extends EventHandler { private readonly docViewer; /** Names of the events this class triggers. */ static readonly Events: { /** 'contentEditModeStarted': content edit mode was entered. */ readonly CONTENT_EDIT_STARTED: "contentEditModeStarted"; /** 'contentEditModeEnded': content edit mode was left. */ readonly CONTENT_EDIT_ENDED: "contentEditModeEnded"; /** 'contentBoxEditStarted': an editor was opened on a box. */ readonly CONTENT_BOX_EDIT_STARTED: "contentBoxEditStarted"; /** 'contentBoxEditEnded': the editor of a box was closed. */ readonly CONTENT_BOX_EDIT_ENDED: "contentBoxEditEnded"; /** 'contentBoxAdded': a box was added. */ readonly CONTENT_BOX_ADDED: "contentBoxAdded"; /** 'contentBoxDeleted': a box was deleted. */ readonly CONTENT_BOX_DELETED: "contentBoxDeleted"; /** 'contentEditSelectionChange': the selected box, caret or text selection changed. */ readonly CONTENT_BOX_SELECTION_CHANGE: "contentEditSelectionChange"; }; /** Where the caret is placed when editing of a box starts. */ static readonly CursorPositions: { /** At the beginning of the text. */ readonly START: "start"; /** At the end of the text. */ readonly END: "end"; }; private active; /** Page → its boxes (in Worker order); a Promise while the page is opening. */ private readonly pages; private readonly opening; /** Selected boxes (same page); with multiple selection the first is the primary box (the argument of getSelectedContentBox and contentEditSelectionChange). */ private selected; /** Marquee rectangle (page coordinates), drawn on the annotation layer. */ private marquee; private clipboard; private readonly safeDistances; private invisibleCharacters; /** Where boxes are drawn on the page bitmap (the rectangles last given by the Worker). */ private readonly shown; private cursorPosition; /** Pages whose content changed and have not been notified yet. */ private readonly changedPages; private changedTimer; /** * Creates the manager; use `documentViewer.getContentEditManager()` instead of calling this. * @param docViewer The viewer whose document is edited. */ constructor(docViewer: DocumentViewer); /** Pages with content changes accumulate and pagesUpdated fires once after a pause (thumbnails and such refetch from it): not per character while typing. */ private markChanged; private flushChanged; /** * Opens an editing session for the current page (other pages open when drawn); fires contentEditModeStarted. * @example * ```js * const { documentViewer } = instance.Core; * const contentEditManager = documentViewer.getContentEditManager(); * contentEditManager.addEventListener('contentEditModeStarted', () => console.log('Editing page content')); * await contentEditManager.startContentEditMode(); * ``` */ startContentEditMode(): Promise; /** * Stops editing the current box, writes the edited content back to all opened pages, redraws them, and fires contentEditModeEnded. * @param _options Unused; kept for compatibility. * @param _options.dispose Unused; kept for compatibility. * @returns A promise that resolves when the edited content has been written back to all opened pages and contentEditModeEnded has fired. The selection, content edit history and copied boxes are cleared. Does nothing when content edit mode is not active. * @example * ```js * const { documentViewer } = instance.Core; * const contentEditManager = documentViewer.getContentEditManager(); * if (contentEditManager.isInContentEditMode()) * await contentEditManager.endContentEditMode(); * const data = await documentViewer.getDocument().getFileData(); // includes the edited content * ``` */ endContentEditMode(_options?: { /** Accepted for compatibility; has no effect. */ dispose?: boolean; }): Promise; /** Commit opened pages to PDF content without leaving edit mode, clearing ranges or discarding history. */ commitContentEdit(): Promise; /** * Checks whether content edit mode is active. * @returns true between startContentEditMode and endContentEditMode. */ isInContentEditMode(): boolean; /** * Finds a box among the opened pages. * @param id Box id. * @returns The box, or undefined when not found. */ getContentBoxById(id: string): ContentBox | undefined; /** * Returns the rectangle (page coordinates) and type of a box. * @param id Box id. * @returns The attributes, or undefined when the box is not found. */ getContentBoxAttributes(id: string): ContentBoxAttributes | undefined; /** * Checks whether a tool can be used while content edit mode is active. * @param toolName Tool name. * @returns true when the tool is allowed. */ isToolAllowedInContentEditMode(toolName: string): boolean; /** Shows / hides invisible characters in the box being edited (spaces as dots, paragraph ends as ¶, drawn on the annotation layer; only for the box being edited). */ toggleInvisibleCharacters(): void; /** * Checks whether invisible characters are shown in the box being edited (see toggleInvisibleCharacters). * @returns True when shown; false by default. */ isShowingInvisibleCharacters(): boolean; /** * Gets where the caret is placed when editing of a box starts. * @returns 'start' (the default) or 'end'. */ getDefaultCursorPosition(): CursorPosition; /** * Sets where the caret is placed when editing of a box starts. * @param position 'start' or 'end'. */ setDefaultCursorPosition(position: CursorPosition): void; /** * Character position for the default caret position: 0 at the beginning, the full text length at the end. * @param text The text of the box. * @returns 0 when the default position is 'start', otherwise the length of text. */ calculateDefaultCursorPosition(text: string): number; /** * Load the page's real text/image models without switching the keyboard editor or selection. * @param pageNumber The page number (1-based). * @returns A promise that resolves with the page's boxes once the page is open for editing. It rejects with INVALID_SOURCE when content edit mode is not active or the page number is invalid. * @example * ```js * const { documentViewer } = instance.Core; * const contentEditManager = documentViewer.getContentEditManager(); * await contentEditManager.startContentEditMode(); * const boxes = await contentEditManager.loadContentBoxes(1); * console.log(boxes.map(box => box.id)); * ``` */ loadContentBoxes(pageNumber: number): Promise; /** * Gets the boxes of a page that is open for editing. * @param pageNumber The page number (1-based). * @returns A copy of the page's boxes in drawing order; empty for pages not opened yet (see loadContentBoxes). */ getContentBoxes(pageNumber: number): ContentBox[]; /** * Gets the selected box; with multiple selection, the first one. * @returns The selected box, or null when none is selected. */ getSelectedContentBox(): ContentBox | null; /** * Gets all selected boxes; they are always on the same page. * @returns A copy of the selected boxes; empty when none is selected. */ getSelectedContentBoxes(): ContentBox[]; /** * Selects these boxes (replacing the previous selection; an empty array clears it); multiple selection only accepts boxes on the page of the first one. Fires contentEditSelectionChange when the selection changes, * with the first box as argument (null when none); use getSelectedContentBoxes for all boxes. The same selection does not fire again. * @param boxes The boxes to select; duplicates and boxes on other pages than the first box are dropped. The annotation layers are redrawn when the selection changes. */ selectContentBoxes(boxes: ContentBox[]): void; /** * Selects one box (null clears the selection); fires contentEditSelectionChange. * @param box The box to select, or null to clear the selection. */ select(box: ContentBox | null): void; /** * Safe distance (pt, page coordinates): minimum distance of editing boxes from the page edge; defaults are 6 for text and 0 for images. type defaults to common: setting common sets both text and image. * @param type 'text', 'image' or 'common'. Defaults to 'common'. * @returns The safe distance in PDF points. */ getSafeDistance(type?: SafeDistanceType): number; /** * Sets the safe distance and returns the effective value; not changed unless it is a non-negative number. Boxes are clamped to the page when dragging, resizing, creating (addParagraph / addImage) and pasting. * @param value The distance in PDF points; negative or non-finite values leave it unchanged. * @param type 'text', 'image', or 'common' (the default), which sets both text and image. * @returns The safe distance of type after the call. */ setSafeDistance(value: number, type?: SafeDistanceType): number; /** * Finds the box at a point by its rectangle (later-drawn boxes are on top and checked first). Only pages open for editing are searched. * @param pageNumber The page number (1-based). * @param x Horizontal position in page coordinates. * @param y Vertical position in page coordinates. * @returns The box, or undefined when there is none at the point. */ getContentBoxAt(pageNumber: number, x: number, y: number): ContentBox | undefined; /** * Gets the box being edited. * @returns The box whose editor is open, or undefined when none is being edited. */ editing(): ContentBox | undefined; /** Argument → content box; throws when not found. */ private targetBox; /** * Toggles bold on the whole box (or the selected text when the box is being edited). * @param target A content box or box id. */ toggleBoldContents(target: Annotation$1 | ContentBox | string): Promise; /** * Toggles italic on the whole box (or the selected text when the box is being edited). * @param target A content box or box id. */ toggleItalicContents(target: Annotation$1 | ContentBox | string): Promise; /** * Toggles underline on the whole box (or the selected text when the box is being edited). * @param target A content box or box id. */ toggleUnderlineContents(target: Annotation$1 | ContentBox | string): Promise; /** * Toggles strikeout on the whole box (or the selected text when the box is being edited). * @param target A content box or box id. */ toggleStrikeContents(target: Annotation$1 | ContentBox | string): Promise; /** * Sets the paragraph alignment of the whole box (or the selected text when the box is being edited). * @param target A content box or box id; other annotations are rejected with INVALID_SOURCE. * @param alignment Left / Start, Center, End / JustifyRight, Justify / JustifyAll, or left / center / right / justify (case-insensitive). Other values reject with INVALID_SOURCE. */ alignContents(target: Annotation$1 | ContentBox | string, alignment: string): Promise; /** * Sets the text color of the whole box (or the selected text when the box is being edited). * @param target A content box or box id. * @param color '#rrggbb' or 'rgb(r, g, b)' with channels 0-255. */ setTextColor(target: Annotation$1 | ContentBox | string, color: string): Promise; /** * Sets several text attributes at once; one undo step. * @param attributes The attributes; `fontStyle` sets bold and italic together. * @param contentBox The text content box. * @param range Optional character range (ComPDFKit extension): `{ startIndex, endIndex }`, or layout positions * `{ start, end }` such as `contentBox.getTextSelectionGeometry().range`. Without it the selected text of the open editor, otherwise the whole box. */ setContentBoxAttributes(attributes: TextAttributes, contentBox: ContentBox, range?: ContentTextRange): Promise; /** * Box content: xmlString has one p per paragraph, spanObjects one per paragraph (text and paragraph number only). * @param target A content box or box id; rejects with INVALID_SOURCE when not found. * @returns A promise that resolves with xmlString (one HTML-escaped p element per paragraph) and spanObjects (one span per paragraph, text and paragraph index only). * @example * ```js * const { documentViewer } = instance.Core; * const contentEditManager = documentViewer.getContentEditManager(); * const [box] = await contentEditManager.loadContentBoxes(1); // content edit mode must be active * const { spanObjects } = await contentEditManager.getContent(box); * console.log(spanObjects.map(span => span.text).join('\n')); * ``` */ getContent(target: Annotation$1 | ContentBox | string): Promise; /** * Replaces the whole box with new content: XML split by p, plain text, or spanObjects (spans with the same paragraph number join into one paragraph). * New text keeps the original style, also when isInheritingContentBoxStyles is false (there is no non-inheriting form here). * @param target A content box or box id; rejects with INVALID_SOURCE when not found. * @param content The new content: a string (XML with p elements, or plain text), or span objects joined into paragraphs by paragraphIndex. * @param _isInheritingContentBoxStyles Unused; kept for compatibility. The new text always keeps the box's style. * @example * ```js * const { documentViewer } = instance.Core; * const contentEditManager = documentViewer.getContentEditManager(); * const [box] = await contentEditManager.loadContentBoxes(1); // content edit mode must be active * await contentEditManager.setContent(box, [ * { text: 'New first paragraph', paragraphIndex: 0 }, * { text: 'New second paragraph', paragraphIndex: 1 }, * ]); * ``` */ setContent(target: Annotation$1 | ContentBox | string, content: string | SpanObject[], _isInheritingContentBoxStyles?: boolean): Promise; /** * Checks whether any box is being edited. * @returns True when an editor is open on a box. */ hasActiveContentBoxEditor(): boolean; /** * Checks whether a box is being edited. * @param arg The box to check. Annotations always return false (there are no placeholder annotations for content boxes). * @returns True when the box's editor is open. */ isContentBoxEditorActive(arg: Annotation$1 | ContentBox): boolean; /** * Starts editing a box: opens its editor and fires contentBoxEditStarted. * @param target A content box or box id; rejects with INVALID_SOURCE when not found. */ startEditingContentBox(target: Annotation$1 | ContentBox | string): Promise; /** Stops editing the current box (committing is asynchronous; listen to contentBoxEditEnded to wait). */ stopEditingContentBox(): void; /** * Gets the font names that can be used for content (same as ContentEdit.getContentEditingFonts). * @returns The font names. */ getFontFamilyCatalog(): string[]; private replacing; /** * Whether replaceText is running (from start to end, failure included); use it to ignore content changes caused by the replacement itself. * @returns True while replaceText runs. */ isReplacingText(): boolean; /** * Replaces the text of search results (from DocumentViewer#search) with replacement as one history entry. Enters content editing mode first when not in it (and stays in it). * Page by page: finds all hits of the same search term in the page's text boxes, matches each result to a hit by position, and replaces from back to front within each box (earlier positions are unaffected). * options.resultIndexInPage is used only when searchResults has a single result: it states directly which hit on its page it is (0-based); * caseSensitive / wholeWord are the search modes, both false by default. * The search term is the resultStr of the first result. Where text read from boxes differs from the page text layer (such as missing spaces) results may not match; unmatched results are skipped. * @param searchResults The search results to replace; the first result's resultStr is the text searched for. Rejects when empty or when the first result has no text. * @param replacement The replacement text. * @param options Optional: `caseSensitive` and `wholeWord` match the search modes (both false by default); `resultIndexInPage` (0-based) states which hit on its page a single result is. * @param options.caseSensitive Case-sensitive matching. Defaults to false. * @param options.wholeWord Whole-word matching. Defaults to false. * @param options.resultIndexInPage With a single result: which hit (0-based) on its page it is. */ replaceText(searchResults: SearchResult[], replacement: string, options?: { /** Case-sensitive matching. Defaults to false. */ caseSensitive?: boolean; /** Whole-word matching. Defaults to false. */ wholeWord?: boolean; /** With a single result: which hit (0-based) on its page it is. */ resultIndexInPage?: number; }): Promise; /** * Runs a box operation on a page open for editing: operations that change page content update the page's boxes and redraw them, and those that add undo steps are recorded in content edit history. Mostly used by content boxes and tools. * @param pageNumber The page number (1-based). * @param op The operation name. * @param args The operation arguments; for box operations the first is the box index. Defaults to none. * @returns A promise that resolves with the operation's result value. */ command(pageNumber: number, op: string, args?: unknown[]): Promise; /** * After content changes (operations, undo, redo), replaces the page's boxes with the latest list and redraws only the changed areas of the page; fires contentBoxAdded / contentBoxDeleted for boxes that appear or disappear and drops deleted boxes from the selection. Mostly used internally. * @param pageNumber The page number (1-based). * @param result The operation result holding the page's boxes. * @param touched Index of the box whose area is redrawn even when its rectangle is unchanged; defaults to result.touched. */ apply(pageNumber: number, result: ContentEditResult, touched?: number | undefined): void; /** * Creates a new text box at rect (page coordinates, clamped to the page by the safe distance). Recorded in content edit history; fires contentBoxAdded. * @param pageNumber The page number (1-based); the page must be open for editing. * @param rect The box rectangle [x1, y1, x2, y2] in page coordinates. * @param text The initial text. Defaults to an empty string. * @param style Optional font name, font size, color ([r, g, b]), bold, italic and text alignment. * @returns A promise that resolves with the new box, or undefined when no box was created. */ addParagraph(pageNumber: number, rect: [number, number, number, number], text?: string, style?: NewParagraphStyle): Promise; /** * Creates a new image box that puts the pixels into rect (page coordinates, clamped to the page by the safe distance). Recorded in content edit history; fires contentBoxAdded. * @param pageNumber The page number (1-based); the page must be open for editing. * @param rect The box rectangle [x1, y1, x2, y2] in page coordinates. * @param image The image width, height and RGBA pixel data. * @param image.width Image width in pixels. * @param image.height Image height in pixels. * @param image.pixels RGBA pixel data. * @returns A promise that resolves with the new box, or undefined when no box was created. */ addImage(pageNumber: number, rect: [number, number, number, number], image: { /** Image width in pixels. */ width: number; /** Image height in pixels. */ height: number; /** RGBA pixel data. */ pixels: ArrayBuffer; }): Promise; /** * Deletes these boxes: page by page from back to front, one request per page; the whole call is one history entry. * The box being edited stops editing first; deleted boxes leave the selection and contentBoxDeleted fires. * @param boxes The boxes to delete; duplicates are ignored. */ deleteContentBoxes(boxes: ContentBox[]): Promise; /** * Copies these boxes: records them for pasteContentBoxes, replacing the previous copy; does not change the page and is not recorded in history. Cleared when content editing ends. * @param boxes The boxes to copy; duplicates are ignored. An empty array clears the copy. * @returns A promise that resolves when the boxes have been copied. */ copyContentBoxes(boxes: ContentBox[]): Promise; private copying; private copyContentBoxesNow; /** * The currently copied boxes: source page, type and box (page coordinates) of each. A snapshot; changing it does not affect the copy; a copy in progress is not included. * @returns The source page, type ('text' or 'object') and rectangle of each copied box; empty when nothing is copied. */ getCopiedContentBoxes(): { /** Source page number (1-based). */ pageNumber: number; /** Box kind ('text' or 'object'). */ type: string; /** Box rectangle in page coordinates. */ frame: Frame; }[]; /** Clears the copied boxes: pasteContentBoxes then pastes nothing. */ clearCopiedContentBoxes(): Promise; /** * Pastes the copied boxes onto page pageNumber, returns the new boxes and selects them. * Without point: each box is offset 5pt to the bottom-right of its original position (in-place duplicate), and each further paste of the same copy on the same page adds another 5pt; with point (page coordinates): the top-left of the group is placed at that point, keeping relative positions. * Positions are clamped by the safe distance; the whole paste is one history entry. Note: pasted text boxes may be taller than the originals (the engine reflows the content); the text is unchanged. * @param pageNumber The page to paste onto (1-based). * @param point Optional position in page coordinates for the top-left of the pasted group. * @param point.x Horizontal position in page coordinates. * @param point.y Vertical position in page coordinates. * @returns A promise that resolves with the pasted boxes; empty when content edit mode is not active or nothing is copied. */ pasteContentBoxes(pageNumber: number, point?: { /** Horizontal position in page coordinates. */ x: number; /** Vertical position in page coordinates. */ y: number; }): Promise; /** How many times this copy has been pasted on each page (for successive offsets). */ private readonly pasteCounts; private releaseClipboard; /** * Combined bounds of the selected boxes (page coordinates); null when nothing is selected. Used to position overlays. * @returns The bounds [x1, y1, x2, y2] in page coordinates, or null when nothing is selected. */ getSelectionFrame(): Frame | null; /** The box being edited: the selection (translucent) and invisible characters when on; the caret is the editor's own blinking element. */ private drawSelection; private openPage; private create; } /** Line ending styles of lines and polylines. */ declare enum LineEndType { /** No line ending. */ NONE = "None", /** Open arrow pointing outward. */ OPEN_ARROW = "OpenArrow", /** Open arrow pointing back along the line. */ R_OPEN_ARROW = "ROpenArrow", /** Closed (filled) arrow pointing outward. */ CLOSED_ARROW = "ClosedArrow", /** Closed (filled) arrow pointing back along the line. */ R_CLOSED_ARROW = "RClosedArrow", /** Short line perpendicular to the line. */ BUTT = "Butt", /** Filled square. */ SQUARE = "Square", /** Filled diamond. */ DIAMOND = "Diamond", /** Filled circle. */ CIRCLE = "Circle", /** Short slash at 60 degrees to the line. */ SLASH = "Slash" } type CaptionSnapPosition = 'start' | 'center' | 'end'; declare class LineAnnotation extends MarkupAnnotation { /** Whether the start and end line endings are written in the file (/LE); unwritten ones read as None. Accurate after reading or committing (ComPDFKit extension). */ getLineEndsInFile(): [boolean, boolean]; /** Display units (read-only, derived from the scale; feet-inches are ft' and in"); an empty array when not a measurement annotation (DisplayUnits). */ get DisplayUnits(): string[]; /** Unit system Metric / Imperial / Typographic (read-only); an empty string when not a measurement annotation. */ get System(): string; /** Display format Decimal / Fraction (read-only, depends on precision and unit); an empty string when not a measurement annotation. */ get DisplayFormat(): string; /** Values of the caption snap position (see setCaptionSnapPosition). */ static readonly CaptionSnapPositions: { /** Outside the start point. */ readonly START: "start"; /** In the middle of the line. */ readonly CENTER: "center"; /** Outside the end point. */ readonly END: "end"; }; elementName: string; /** Result text style (changed in the style panel; an empty string / null means unchanged: the engine default Helvetica 9 black); see MeasureTextStyle in utils/measurement-caption.ts. */ Font: string; /** Font size of the measurement result text in points, as a string; an empty string keeps the default. */ FontSize: string; /** Color of the measurement result text; null keeps the default. */ TextColor: Color | null; /** * Creates a line annotation. * @param init Initial property values. */ constructor(init?: AnnotationInit); /** Border style: 'solid' (default) or 'dash' (see border-style.ts). */ get Style(): string; set Style(style: string); /** Dash lengths (pt), comma separated, '3' by default; an array is joined into a string. */ get Dashes(): string | null; set Dashes(dashes: string | number[] | null); draw(ctx: CanvasRenderingContext2D, pageMatrix: Matrix): void; /** * Distance measurement line (matching the engine-generated appearance): with leader lines, the line moves along the normal by offset + length, with a leader at each end from offset to offset + length + extension; * without leader lines, ±11 ticks are drawn at both ends. The result text is above the line, centered (moved outside the line for start / end, computed like the Worker's patchLineCaptions). */ private drawMeasured; /** Start point of the line (page coordinates, PDF points). */ Start: Point; /** End point of the line (page coordinates, PDF points). */ End: Point; setRect(rect: Rect): void; /** * Gets the start point. * @returns The start point in page coordinates. */ getStartPoint(): Point; /** * Sets the start point. Call adjustRect afterwards to update the bounding box. * @param x X in PDF points. * @param y Y in PDF points. */ setStartPoint(x: number, y: number): void; /** * Gets the end point. * @returns The end point in page coordinates. */ getEndPoint(): Point; /** * Sets the end point. Call adjustRect afterwards to update the bounding box. * @param x X in PDF points. * @param y Y in PDF points. */ setEndPoint(x: number, y: number): void; /** Line ending style (SetLineType); drawn directly by the main thread (drawLineEnding). */ StartStyle: LineEndType; /** Line ending style at the end point. */ EndStyle: LineEndType; /** * Gets the line ending style at the start point. * @returns The line ending style. */ getStartStyle(): LineEndType; /** * Sets the line ending style at the start point. * @param style The line ending style. */ setStartStyle(style: LineEndType): void; /** * Gets the line ending style at the end point. * @returns The line ending style. */ getEndStyle(): LineEndType; /** * Sets the line ending style at the end point. * @param style The line ending style. */ setEndStyle(style: LineEndType): void; /** Leader lines of a measurement line: the distance the line moves along the normal, and the lengths of the leaders past and away from the end points (setLeadLength / setLeadExtension / setLeadOffset). */ leaderLength: number; /** Distance in PDF points between the end points and the start of the leader lines. */ leaderOffset: number; /** Length in PDF points by which the leader lines extend past the line. */ leaderExtension: number; private captionSnapPosition; /** Both ends after moving leaderLength along the normal (matching the engine appearance: positive values move left looking from start to end, i.e. up for a horizontal line). */ getLeaderPoints(): { /** The moved start point. */ Start: Point; /** The moved end point. */ End: Point; }; /** Leader handle: the midpoint of the moved segment (drag it to change leaderLength). */ getLeaderLineControlHandlePoint(): Point; /** * Position of a measurement line's result text along the line: center in the middle, start / end moved outside the start / end point (caption-offset-h, /CO in the file). * The engine only places it in the middle; the Worker moves it after generating the appearance and grows the rectangle to enclose it. */ getCaptionSnapPosition(): CaptionSnapPosition; /** Unknown values log a warning and keep the previous one. */ setCaptionSnapPosition(position: CaptionSnapPosition): void; /** Length between the end points (pt). */ getLineLength(): number; /** Direction from start to end (radians, page coordinates with y down). */ getAngle(): number; /** Moves the end along the original direction to this length; the bounding box is recomputed. */ setLineLength(length: number): void; /** Rotates by radians around the bounding box center (or center); Rotation follows. */ rotate(radians: number, center?: { /** X of the rotation center in PDF points. */ x: number; /** Y of the rotation center in PDF points. */ y: number; }): void; /** The bounding box is that of both ends, padded by the line width. */ adjustRect(): void; getRectPadding(): number; /** The measurement result text is measured and written back by the Worker (UpdateAnnotMeasure, on commit), not recomputed locally. */ adjustContents(): void; } /** Core.Annotations.IPathAnnotation: a retained intermediate base class whose path methods are shared by Polyline / Polygon / FreeText / Arc (setVertices / getVertices). */ declare class IPathAnnotation extends MarkupAnnotation { elementName: string; /** Internal: vertices (/Vertices). */ protected path: Point[]; setRect(rect: Rect): void; /** * Gets the vertices. * @returns The vertices in page coordinates (the internal array, not a copy). */ getPath(): Point[]; /** * Replaces the vertices. Call adjustRect afterwards to update the bounding box. * @param points The vertices in page coordinates. */ setPath(points: Point[]): void; /** * Gets one vertex. * @param index Zero-based vertex index. * @returns The vertex. */ getPathPoint(index: number): Point; /** * Moves one vertex. * @param index Zero-based vertex index. * @param x X in PDF points. * @param y Y in PDF points. */ setPathPoint(index: number, x: number, y: number): void; /** * Appends a vertex. * @param x X in PDF points. * @param y Y in PDF points. */ addPathPoint(x: number, y: number): void; /** Removes the last vertex. */ popPath(): void; /** Rotates by radians around the bounding box center (or center); Rotation follows and the bounding box is recomputed from the points. */ rotate(radians: number, center?: { /** X of the rotation center in PDF points. */ x: number; /** Y of the rotation center in PDF points. */ y: number; }): void; /** The bounding box is that of the points, padded by the line width (getRectPadding). */ adjustRect(): void; getRectPadding(): number; } declare class PolygonAnnotation extends IPathAnnotation { /** Display units (read-only, derived from the scale; feet-inches are ft' and in"); an empty array when not a measurement annotation (DisplayUnits). */ get DisplayUnits(): string[]; /** Unit system Metric / Imperial / Typographic (read-only); an empty string when not a measurement annotation. */ get System(): string; /** Display format Decimal / Fraction (read-only, depends on precision and unit); an empty string when not a measurement annotation. */ get DisplayFormat(): string; elementName: string; /** * Result text style of area measurements (Font / FontSize / TextColor of the style panel): stored in captionStyle of the result text options (written to /DA and read back from it); * without measurement, reads give defaults and writes are ignored; when the font size is unset, the automatically computed size is read. */ get Font(): string; set Font(font: string); /** Font size of the measurement result text with unit, such as '9pt'; setting a positive size fixes the size of the result text. */ get FontSize(): string; set FontSize(size: string); /** Color of the measurement result text; setting it changes the result text style. */ get TextColor(): Color; set TextColor(color: { /** Red, 0 to 255. */ R: number; /** Green, 0 to 255. */ G: number; /** Blue, 0 to 255. */ B: number; } | null); /** Width and height of the bounding box (for the automatic font size). */ private captionSize; private setCaptionStyle; /** * Creates a polygon annotation. * @param init Initial property values. */ constructor(init?: AnnotationInit); private cloudIntensity; /** Cloud intensity, integers only (truncated on set; negative and NaN become 0); see normalizeCloudIntensity. */ get CloudIntensity(): number; set CloudIntensity(intensity: number); /** Cloud intensity (Intensity, same as CloudIntensity). */ get Intensity(): number; set Intensity(intensity: number); private intent; /** * Intent: PolygonCloud for cloudy polygons, PolygonDimension for measurement polygons (the engine writes /IT itself on save; here it is derived from state); * an explicitly set value wins, and an empty string returns to the derived value. /IT is not read separately from the file. */ get Intent(): string; set Intent(intent: string); /** Border style: 'solid' (default), 'dash'; 'cloudy' when the cloud intensity is above 0 (see border-style.ts). Setting cloudy without intensity uses the default 2; setting anything else removes the cloud. */ get Style(): string; set Style(style: string); /** Dash lengths (pt), comma separated, '3' by default; an array is joined into a string. */ get Dashes(): string | null; set Dashes(dashes: string | number[] | null); /** Same as Style. */ getBorderStyle(): string; /** * Sets the border style (same as setting Style). * @param style 'solid' or 'dash'. */ setBorderStyle(style: string): void; /** * Gets the cloudy border intensity. * @returns The intensity; 0 means no cloudy border. */ getCloudIntensity(): number; /** Whether the polygon is an axis-aligned rectangle: four vertices (or five with the ends joined) whose edges run along the axes. */ isRectangularPolygon(): boolean; /** * Sets the cloudy border intensity. * @param intensity The intensity; 0 means no cloudy border. */ setCloudIntensity(intensity: number): void; /** * Result text options of area measurements (see utils/measurement-caption.ts); undefined when not an area measurement. * Font, size and color go into the appearance; the position matches the engine: the text box is centered on the center of the shape's bounding box (which may fall outside an irregular shape), * plus captionOffset, kept inside the shape's bounding box; captionRect is computed from the current shape and text. With isEnabled false no text is drawn in the appearance. */ getMeasurementCaptionOptions(): MeasurementCaptionOptions | undefined; /** Merges field by field; when captionRect is given directly (without captionOffset), it is converted to an offset by its center (as when dragging the result text). */ setMeasurementCaptionOptions(options: MeasurementCaptionOptionsInput): void; /** Which items the result text of area measurements (with Measure) shows: perimeter, area; both by default; undefined when not an area measurement. */ getMeasurementDisplayOptions(): MeasurementDisplayOptions | undefined; /** Changes only the given keys (inapplicable ones are ignored); then updateAnnotation commits and the result text and appearance are rewritten. */ setMeasurementDisplayOptions(options: MeasurementDisplayOptions): void; private storedCaptionOptions; /** * Moving a cloud as a whole rounds the displacement: the rectangle and vertices land on integers, so the engine (which stores integer rectangles) and the main thread's rectangle and appearance bitmap do not differ by 1 pt, * and the selection box does not grow slightly when the move finishes (resizing is unchanged). */ setRect(rect: Rect): void; /** With cloud intensity above 0 the border is drawn as a cloud (also while drawing and before the appearance bitmap arrives). */ draw(ctx: CanvasRenderingContext2D, pageMatrix: Matrix): void; /** Result text of area measurements: drawn at the center of the text box (font, size and color from the result text options, as in the engine appearance). */ private drawCaption; private drawShape; } /** A measurement annotation or a measurement tool: anything that carries `Measure` data. */ type MeasurementItem = (Annotation$1 | Tool) & { Measure: MeasureData | null; }; /** Events of {@link MeasurementManager} and the arguments their listeners receive. */ interface MeasurementManagerEvents { /** A scale was created, applied, replaced or deleted. Receives the same object as {@link MeasurementManager.getScales}. */ scaleUpdated: [scales: Record]; /** A measurement tool was used before any scale exists; nothing is drawn. Listen to it to ask the user for a scale. */ createAnnotationWithNoScale: []; } /** * Manages the scales of measurement annotations and measurement tools. * * Measurement items are grouped by their scale string (such as `1 in = 1 ft`). Applying a scale to an * annotation re-measures it; applying a scale to a tool affects the annotations it creates afterwards. * The calibration tool and the annotations it draws are not measurement items. * * Get the instance with `documentViewer.getMeasurementManager()`. * * @example * ```js * const { documentViewer, Scale } = instance.Core; * const measurementManager = documentViewer.getMeasurementManager(); * * measurementManager.addEventListener('scaleUpdated', (scales) => { * console.log(Object.keys(scales)); // ['1 in = 1 ft'] * }); * * // Use 1 inch on the page for 1 foot in the world for every measurement tool. * await measurementManager.createAndApplyScale({ * scale: new Scale([[1, 'in'], [1, 'ft']]), * applyTo: [], * }); * ``` */ declare class MeasurementManager extends EventHandler { private readonly docViewer; /** Names of the events this class triggers. */ static readonly Events: { /** 'scaleUpdated': fired when scales are created, changed or deleted. */ readonly SCALE_UPDATED: "scaleUpdated"; /** 'createAnnotationWithNoScale': fired when a measurement tool cannot create an annotation because no scale is set. */ readonly CREATE_ANNOTATION_WITH_NO_SCALE: "createAnnotationWithNoScale"; }; private styleSyncing; /** * The document viewer creates its measurement manager; use `documentViewer.getMeasurementManager()` instead of calling this. * @param docViewer The document viewer whose measurement items are managed. */ constructor(docViewer: DocumentViewer); /** * Gets every scale in use and the measurement items that use it. * Measurement tools that have no scale yet are given the first scale. * @returns An object whose keys are scale strings (such as `1 in = 1 ft`) and whose values are the annotations and tools using that scale. * @example * ```js * const scales = measurementManager.getScales(); * for (const [scale, items] of Object.entries(scales)) * console.log(scale, items.length); * ``` */ getScales(): Record; /** * Applies a scale to measurement annotations and tools, and triggers `scaleUpdated`. * When no scale exists yet, the scale is applied to every measurement tool and `applyTo` is ignored. * When items already use the same scale, the scale takes their precision. * @param options * @param options.scale The scale to apply. * @param options.applyTo The annotations and tools to apply it to. Items without measurement data are skipped. * @example * ```js * const [annotation] = annotationManager.getSelectedAnnotations(); * await measurementManager.createAndApplyScale({ * scale: new instance.Core.Scale([[1, 'cm'], [2, 'm']]), * applyTo: [annotation], * }); * ``` */ createAndApplyScale({ scale, applyTo }: { scale: Scale; applyTo: Array; }): Promise; /** * Gets the scales that will no longer be used after {@link createAndApplyScale} is called with the same options. * Call it first to tell the user which scales are about to disappear. * @param options The options you will pass to {@link createAndApplyScale}. * @param options.scale The scale to apply. * @param options.applyTo The annotations and tools to apply it to. * @returns The scale strings that no item will use any more. */ getOldScalesToDeleteAfterApplying({ scale, applyTo }: { scale: Scale; applyTo: Array; }): string[]; /** * Replaces a scale with another one on every annotation and tool that uses it, and triggers `scaleUpdated`. * @param oldScale The scale to replace. * @param newScale The scale to use instead. * @example * ```js * const { Scale } = instance.Core; * await measurementManager.replaceScale(new Scale('1 in = 1 ft'), new Scale('1 in = 2 ft')); * ``` */ replaceScale(oldScale: Scale, newScale: Scale): Promise; /** * Replaces several scales with one scale on every annotation and tool that uses them, and triggers `scaleUpdated`. * @param oldScales The scales to replace. * @param newScale The scale to use instead. */ replaceScales(oldScales: Scale[], newScale: Scale): Promise; /** * Deletes a scale and triggers `scaleUpdated`. * Annotations using the scale are deleted; tools using it switch to the first remaining scale. * The last remaining scale cannot be deleted: a warning is logged and nothing changes. * @param scale The scale to delete. */ deleteScale(scale: Scale): Promise; /** * Gets the precision used by the items that use a scale. * @param scale The scale to look up. * @returns The precision, such as `0.01`, or `undefined` when no item uses the scale. */ getScalePrecision(scale: Scale): number | undefined; /** * Makes `setStyles` on a measurement tool also restyle the annotations that use the same scale. Off by default. */ enableAnnotationAndToolStyleSyncing(): void; /** Stops `setStyles` on a measurement tool from restyling existing annotations. */ disableAnnotationAndToolStyleSyncing(): void; /** * Tells whether style syncing between measurement tools and annotations is on. * @returns `true` after {@link enableAnnotationAndToolStyleSyncing}, otherwise `false`. */ isAnnotationAndToolStyleSyncingEnabled(): boolean; /** * Sets the measured length of a distance measurement, in the world unit of its scale. * The left end of the line stays where it is and the other end moves along the line; the result is kept inside the page. * The change is committed like `annotationManager.updateAnnotation`. * ComPDFKit extension. * @param annotation A distance measurement line. * @param length The new length in the world unit of the annotation's scale (for `1 in = 1 ft`, in feet). * @example * ```js * const [line] = annotationManager.getSelectedAnnotations(); * if (line instanceof instance.Core.Annotations.LineAnnotation && line.Measure) * await measurementManager.setMeasuredLength(line, 3); * ``` */ setMeasuredLength(annotation: LineAnnotation, length: number): Promise; /** * Turns a distance measurement around its start point to the given angle, keeping its length; the end point is kept inside the page. * ComPDFKit extension. * @param annotation A distance measurement line. * @param degrees The angle from the positive x axis, counter-clockwise as seen on the page. * @example * ```js * // Point the line straight up from its start point. * await measurementManager.setMeasuredAngle(line, 90); * ``` */ setMeasuredAngle(annotation: LineAnnotation, degrees: number): Promise; /** * Sets the measured width (horizontal side) and / or height (vertical side) of a rectangular area measurement, in the world unit of its scale. * The top-left corner stays where it is; the result is kept inside the page. Polygons that are not axis-aligned rectangles are left unchanged. * ComPDFKit extension. * @param annotation A rectangular area measurement (a polygon whose vertices are the corners of an axis-aligned rectangle). * @param size The new size in the world unit of the annotation's scale. * @param size.width The new horizontal side; omit to keep it. * @param size.height The new vertical side; omit to keep it. * @example * ```js * // Make the rectangle 5 units wide and keep its height. * await measurementManager.setMeasuredSize(rectangle, { width: 5 }); * ``` */ setMeasuredSize(annotation: PolygonAnnotation, size: { width?: number; height?: number; }): Promise; /** Real length of 1 pt; logs a warning and returns undefined when it is not a measurement annotation or the scale is invalid. */ private factorOf; /** Unrotated page width and height (the space of annotation coordinates). */ private pageSize; private tools; private apply; } /** Core.DisplayModeManager: documentViewer.getDisplayModeManager() (no virtual layout: the full layout only renders visible pages anyway) */ type ManagerViewer = DisplayModeViewer & { trigger: (event: 'displayModeUpdated', args: [DisplayMode]) => unknown; }; /** Holds the viewer's current display mode. Obtain it with `documentViewer.getDisplayModeManager()`. */ declare class DisplayModeManager { private readonly docViewer; private mode; /** * Creates the manager with Continuous mode; the document viewer creates it. * @param docViewer The viewer whose layout is managed. */ constructor(docViewer: ManagerViewer); /** * Returns the current display mode. * @returns The display mode object. */ getDisplayMode(): DisplayMode; /** Changes the layout and fires displayModeUpdated through the viewer; the viewer then re-lays out and recomputes visible pages */ setDisplayMode(mode: DisplayMode): void; /** * Checks whether virtual display mode is enabled. * @returns Always false; there is no virtual layout. */ isVirtualDisplayEnabled(): boolean; /** No virtual layout; kept for the interface */ enableVirtualDisplayMode(): void; /** No virtual layout; kept for the interface. */ disableVirtualDisplayMode(): void; } /** Password callback: call checkPassword with the user's input; called again on a wrong password */ type PasswordCallback = (checkPassword: (password: string) => void) => void; /** setCustomLoadDocumentHandler: call defaultLoad after rewriting the source or options */ type LoadDocumentHandler = (src: DocumentSource | Document, options: LoadDocumentOptions, defaultLoad: (src: DocumentSource | Document, options: LoadDocumentOptions) => Promise) => Promise; /** setDocumentXFDFRetriever: gets XFDF by documentId on load and uses it instead of the annotations stored in the PDF */ type DocumentXFDFRetriever = (documentId: string) => Promise; /** Options for loadDocument. */ interface LoadDocumentOptions { /** A wrong string reports PASSWORD_REQUIRED; the function form can ask repeatedly */ password?: string | PasswordCallback; /** 0–1, (download progress + Worker load progress) / 2, never decreasing; reports 1 exactly once at the end on success */ onLoadingProgress?: (percent: number) => void; /** On load failure, called back first, then rejects */ onError?: (error: ComPDFKitError) => void; /** License; the first load with a license triggers initialization, later ones reuse it */ licenseKey?: string; /** Shorthand for licenseKey */ l?: string; /** Takes precedence over the file name inferred from the source */ filename?: string; /** Business id of the document (Document.getDocumentId(), the argument of setDocumentXFDFRetriever) */ documentId?: string; /** An explicitly passed non-pdf type is rejected before reading; the format is decided by the file header */ extension?: string; /** Request headers for URL sources */ customHeaders?: Record; /** Send cookies for cross-origin URL sources */ withCredentials?: boolean; /** Aborts the load when signaled. */ signal?: AbortSignal; } /** How the zoom level is chosen. */ declare enum FitMode { /** Zoom so the page width fills the viewport. */ FitWidth = "FitWidth", /** Zoom so the whole page fits in the viewport. */ FitPage = "FitPage", /** Keep the zoom level that was set explicitly. */ Zoom = "Zoom" } /** Style of one view watermark text: fontSize in pt (20 by default), color a CSS color or Color, opacity 0–100 (100 by default) */ interface WatermarkTextStyle { fontSize?: number; fontFamily?: string; color?: string | Color; opacity?: number; } /** * View watermark (drawn on screen only, not written to the file; use Document.addWatermark for that): diagonal along the page diagonal, header / footer at left, center and right * of the top and bottom edges, custom draws itself (page coordinates); with shouldDrawOverAnnotations true it is drawn above annotations */ interface WatermarkOptions { /** Draws the watermark above annotations instead of below them. */ shouldDrawOverAnnotations?: boolean; /** Text drawn along the page diagonal, with its style. */ diagonal?: WatermarkTextStyle & { /** Text to draw. */ text?: string; }; /** Text at the left, center and right of the top edge, with its style. */ header?: WatermarkTextStyle & { /** Text at the left of the top edge. */ left?: string; /** Text at the center of the top edge. */ center?: string; /** Text at the right of the top edge. */ right?: string; }; /** Text at the left, center and right of the bottom edge, with its style. */ footer?: WatermarkTextStyle & { /** Text at the left of the bottom edge. */ left?: string; /** Text at the center of the bottom edge. */ center?: string; /** Text at the right of the bottom edge. */ right?: string; }; /** Draws a custom watermark; the context uses page coordinates. */ custom?: (ctx: CanvasRenderingContext2D, pageNumber: number, pageWidth: number, pageHeight: number) => void; } /** Options for startSemanticDiff. */ interface SemanticDiffOptions { /** Color of text deleted / replaced in this (before) version, A is opacity; (255, 73, 73, 0.4) by default */ beforeColor?: Color; /** Color of text added / replaced in the other (after) version; (21, 205, 131, 0.4) by default */ afterColor?: Color; } interface TextSearchOptions { /** false by default: stops at one match and continues on the next call; true searches all pages */ fullSearch?: boolean; /** Each match (resultCode FOUND, in page order) */ onResult?: (result: SearchResult) => void; /** A page finished (resultCode PAGE; only when the mode includes PAGE_STOP, including pages without matches) */ onPageEnd?: (result: SearchResult) => void; /** Reached the last page (resultCode DONE; not called when canceled by clearSearchResults, or when a non-full search stops at one match) */ onDocumentEnd?: (result: SearchResult) => void; onError?: (error: unknown) => void; /** Search only these pages (inclusive, 1-based) */ startPage?: number; endPage?: number; } /** Stream returned by search: matches arrive one by one, getAll() gets them all at once */ type SearchStream = ReadableStream & { /** Reads the whole stream and resolves with all matches; repeated calls give the same array. */ getAll: () => Promise; }; /** The annotation an action is about to act on, and how. */ interface AnnotationPermissionTarget { /** The target annotation. */ annotation: Annotation$1; /** What the action does: select it, fill in a form field, activate it, or edit it. */ intent: 'select' | 'fill' | 'activate' | 'edit'; } /** Events fired by DocumentViewer, with their listener arguments. */ interface ViewerEvents { /** Synchronous veto at real action entry; Core itself has no document-permission policy/cache. */ beforePermissionAction: [ request: ({ /** What is about to happen: using a tool, content editing, or copying text. */ action: 'tool' | 'contentEdit' | 'copy'; } | ({ /** Acting on an annotation. */ action: 'annotation'; } & AnnotationPermissionTarget)) & { /** Name of the tool involved, when there is one. */ toolName?: string; /** Call to block the action. */ preventDefault: () => void; } ]; /** A document is about to load. */ beforeDocumentLoaded: []; /** * A document finished loading and is shown. * @example * ```js * const { documentViewer } = instance.Core; * documentViewer.addEventListener('documentLoaded', () => { * console.log(documentViewer.getDocument().getFilename()); * }); * ``` */ documentLoaded: []; /** The document was closed. */ documentUnloaded: []; /** * The annotations of the document have been loaded. * @example * ```js * const { documentViewer, annotationManager } = instance.Core; * documentViewer.addEventListener('annotationsLoaded', () => { * console.log(annotationManager.getAnnotationsList().length); * }); * ``` */ annotationsLoaded: []; /** A page finished rendering; receives the page number and its canvas. */ pageComplete: [pageNumber: number, canvas: HTMLCanvasElement]; /** * The current page changed. * @example * ```js * const { documentViewer } = instance.Core; * documentViewer.addEventListener('pageNumberUpdated', (pageNumber) => { * console.log(`Current page: ${pageNumber}`); * }); * ``` */ pageNumberUpdated: [pageNumber: number]; /** The page structure changed (forwarded from Document.pagesUpdated; view and annotations already updated to the new page order) */ pagesUpdated: [changes: PageChanges]; /** The document outline changed (forwarded from Document bookmarksUpdated) */ bookmarksUpdated: []; /** The set of visible pages changed. */ visiblePagesChanged: [pageNumbers: number[]]; /** User bookmarks changed: all bookmarks (page index → text) and this change's additions, modifications and deletions (page indexes) */ userBookmarksChanged: [ bookmarks: Record, changes: { /** Page indexes (0-based) whose bookmark was added. */ added: number[]; /** Page indexes (0-based) whose bookmark text changed. */ updated: number[]; /** Page indexes (0-based) whose bookmark was removed. */ removed: number[]; } ]; /** * The zoom level changed. * @example * ```js * const { documentViewer } = instance.Core; * documentViewer.addEventListener('zoomUpdated', (zoom) => { * console.log(`Zoom: ${Math.round(zoom * 100)}%`); * }); * ``` */ zoomUpdated: [zoom: number]; /** The view rotation changed, for one page when a page number is given. */ rotationUpdated: [rotation: number, pageNumber?: number]; /** The fit mode changed. */ fitModeUpdated: [mode: FitMode]; /** The display mode changed. */ displayModeUpdated: [mode: DisplayMode]; /** displayPageLocation was called; receives the page number and the horizontal and vertical offsets. */ displayPageLocation: [pageNumber: number, x: number, y: number]; /** Page rendering started after a period with nothing rendering. */ beginRendering: []; /** All pending page renders finished. */ finishedRendering: []; /** * The text selection changed; quads are null when the selection was cleared. * @example * ```js * const { documentViewer } = instance.Core; * documentViewer.addEventListener('textSelected', (quads, text, pageNumber) => { * if (quads) * console.log(pageNumber, text); * }); * ``` */ textSelected: [quads: Quad[] | null, text: string, pageNumber?: number]; /** A search started (true) or stopped (false). */ searchInProgress: [inProgress: boolean]; /** Fired by the UI when a one-by-one search (fullSearch: false) reaches the end (same name as the UI searchText event, argument always true) */ endOfDocumentResult: [reached: boolean]; /** The list of search results changed. */ searchResultsChanged: [results: SearchResult[]]; /** The active search result changed. */ activeSearchResultChanged: [result: SearchResult]; /** The current tool changed; receives the new and the previous tool. */ toolModeUpdated: [next: Tool, prev: Tool]; /** A tool's settings changed. */ toolUpdated: [tool: Tool]; /** Left button or primary pointer pressed in the viewer. */ mouseLeftDown: [e: PointerEvent]; /** Left button or primary pointer released in the viewer. */ mouseLeftUp: [e: PointerEvent]; /** Right button pressed in the viewer. */ mouseRightDown: [e: PointerEvent]; /** Right button released in the viewer. */ mouseRightUp: [e: PointerEvent]; /** Pointer moved in the viewer. */ mouseMove: [e: PointerEvent]; /** Pointer entered the viewer. */ mouseEnter: [e: PointerEvent]; /** Pointer left the viewer. */ mouseLeave: [e: PointerEvent]; /** Click in the viewer. */ click: [e: PointerEvent]; /** Double click in the viewer. */ dblClick: [e: PointerEvent]; /** Short press and release without moving. */ tap: [e: PointerEvent]; /** Touch or pen held in place for a long press. */ longTap: [e: PointerEvent]; /** Key pressed while the viewer has focus. */ keyDown: [e: KeyboardEvent]; /** Key released while the viewer has focus. */ keyUp: [e: KeyboardEvent]; /** Budget warning: appearance / canvas / text caches approaching their limits */ budgetPressure: [ info: { /** Which cache: annotation appearances, page bitmaps or page text. */ kind: 'appearance' | 'canvas' | 'text'; /** Bytes in use. */ used: number; /** Budget in bytes. */ limit: number; } ]; /** startSemanticDiff finished: difference annotations of both sides and the number of differences */ compareAnnotationsLoaded: [doc1Annotations: Annotation$1[], doc2Annotations: Annotation$1[], diffCount: number]; } /** What the setSubmitFormHandler handler receives: submit() continues the submission, cancel() cancels it */ interface SubmitFormOptions { submit: () => void; cancel: (reason?: unknown) => void; } /** Function of setInternalAnnotationsTransform: xfdf is the document's annotations, callback returns the changed ones */ type InternalAnnotationsTransform = (xfdf: string, callback: (xfdf: string) => void, options?: Record) => void; declare class DocumentViewer extends EventHandler { /** The FitMode enum, for `DocumentViewer.FitMode.FitWidth` and the like. */ static readonly FitMode: typeof FitMode; /** Names of the events this class triggers. */ static readonly Events: { /** Name of the `beforePermissionAction` event (see ViewerEvents). */ readonly BEFORE_PERMISSION_ACTION: "beforePermissionAction"; /** Name of the `beforeDocumentLoaded` event (see ViewerEvents). */ readonly BEFORE_DOCUMENT_LOADED: "beforeDocumentLoaded"; /** Name of the `documentLoaded` event (see ViewerEvents). */ readonly DOCUMENT_LOADED: "documentLoaded"; /** Name of the `documentUnloaded` event (see ViewerEvents). */ readonly DOCUMENT_UNLOADED: "documentUnloaded"; /** Name of the `annotationsLoaded` event (see ViewerEvents). */ readonly ANNOTATIONS_LOADED: "annotationsLoaded"; /** Name of the `pageComplete` event (see ViewerEvents). */ readonly PAGE_COMPLETE: "pageComplete"; /** Name of the `pageNumberUpdated` event (see ViewerEvents). */ readonly PAGE_NUMBER_UPDATED: "pageNumberUpdated"; /** Name of the `pagesUpdated` event (see ViewerEvents). */ readonly PAGES_UPDATED: "pagesUpdated"; /** Name of the `visiblePagesChanged` event (see ViewerEvents). */ readonly VISIBLE_PAGES_CHANGED: "visiblePagesChanged"; /** Name of the `userBookmarksChanged` event (see ViewerEvents). */ readonly USER_BOOKMARKS_CHANGED: "userBookmarksChanged"; /** Name of the `zoomUpdated` event (see ViewerEvents). */ readonly ZOOM_UPDATED: "zoomUpdated"; /** Name of the `rotationUpdated` event (see ViewerEvents). */ readonly ROTATION_UPDATED: "rotationUpdated"; /** Name of the `fitModeUpdated` event (see ViewerEvents). */ readonly FIT_MODE_UPDATED: "fitModeUpdated"; /** Name of the `displayModeUpdated` event (see ViewerEvents). */ readonly DISPLAY_MODE_UPDATED: "displayModeUpdated"; /** Name of the `displayPageLocation` event (see ViewerEvents). */ readonly DISPLAY_PAGE_LOCATION: "displayPageLocation"; /** Name of the `beginRendering` event (see ViewerEvents). */ readonly BEGIN_RENDERING: "beginRendering"; /** Name of the `finishedRendering` event (see ViewerEvents). */ readonly FINISHED_RENDERING: "finishedRendering"; /** Name of the `textSelected` event (see ViewerEvents). */ readonly TEXT_SELECTED: "textSelected"; /** Name of the `searchInProgress` event (see ViewerEvents). */ readonly SEARCH_IN_PROGRESS: "searchInProgress"; /** Name of the `searchResultsChanged` event (see ViewerEvents). */ readonly SEARCH_RESULTS_CHANGED: "searchResultsChanged"; /** Name of the `activeSearchResultChanged` event (see ViewerEvents). */ readonly ACTIVE_SEARCH_RESULT_CHANGED: "activeSearchResultChanged"; /** Name of the `toolModeUpdated` event (see ViewerEvents). */ readonly TOOL_MODE_UPDATED: "toolModeUpdated"; /** Name of the `toolUpdated` event (see ViewerEvents). */ readonly TOOL_UPDATED: "toolUpdated"; /** Name of the `mouseLeftDown` event (see ViewerEvents). */ readonly MOUSE_LEFT_DOWN: "mouseLeftDown"; /** Name of the `mouseLeftUp` event (see ViewerEvents). */ readonly MOUSE_LEFT_UP: "mouseLeftUp"; /** Name of the `mouseRightDown` event (see ViewerEvents). */ readonly MOUSE_RIGHT_DOWN: "mouseRightDown"; /** Name of the `mouseRightUp` event (see ViewerEvents). */ readonly MOUSE_RIGHT_UP: "mouseRightUp"; /** Name of the `mouseMove` event (see ViewerEvents). */ readonly MOUSE_MOVE: "mouseMove"; /** Name of the `mouseEnter` event (see ViewerEvents). */ readonly MOUSE_ENTER: "mouseEnter"; /** Name of the `mouseLeave` event (see ViewerEvents). */ readonly MOUSE_LEAVE: "mouseLeave"; /** Name of the `click` event (see ViewerEvents). */ readonly CLICK: "click"; /** Name of the `dblClick` event (see ViewerEvents). */ readonly DBL_CLICK: "dblClick"; /** Name of the `tap` event (see ViewerEvents). */ readonly TAP: "tap"; /** Name of the `longTap` event (see ViewerEvents). */ readonly LONG_TAP: "longTap"; /** Name of the `keyDown` event (see ViewerEvents). */ readonly KEY_DOWN: "keyDown"; /** Name of the `keyUp` event (see ViewerEvents). */ readonly KEY_UP: "keyUp"; /** Name of the `compareAnnotationsLoaded` event (see ViewerEvents). */ readonly COMPARE_ANNOTATIONS_LOADED: "compareAnnotationsLoaded"; }; private document; /** The load in progress; a new load or closeDocument aborts it */ private loading; private customLoadHandler; /** * Also accepts a Document from Core.createDocument (not downloaded or opened again). A later load replaces an earlier one: * the earlier one ends with CANCELLED and its document is released, without firing documentLoaded. * @param src A URL, bytes, Blob or File, or a Document created with Core.createDocument. * @param options Load options such as `password`, `onLoadingProgress`, `signal` and `documentId`. * @returns A Promise that resolves once the document is open and documentLoaded has fired (annotations keep loading in the background). It rejects when loading fails, when the viewer is unmounted, or with CANCELLED when a later load supersedes it. * @example * ```js * const { documentViewer } = instance.Core; * await documentViewer.loadDocument('https://example.com/files/sample.pdf', { * password: 'secret', * onLoadingProgress: (percent) => console.log(`${Math.round(percent * 100)}%`), * }); * console.log(documentViewer.getPageCount()); * ``` */ loadDocument(src: DocumentSource | Document, options?: LoadDocumentOptions): Promise; private defaultLoad; /** * Returns the loaded document. * @returns The document, or null when none is loaded. * @example * ```js * const { documentViewer } = instance.Core; * documentViewer.addEventListener('documentLoaded', () => { * const doc = documentViewer.getDocument(); * console.log(doc.getFilename(), doc.getPageCount()); * }); * ``` */ getDocument(): Document | null; /** Aborts the load in progress; with a document, fires documentUnloaded and releases the document in the Worker */ closeDocument(): Promise; private unload; /** * Intercepts loadDocument: the handler receives the source, the options and the default load function, and calls it after changing either. * @param handler The handler, or null to remove it. */ setCustomLoadDocumentHandler(handler: LoadDocumentHandler | null): void; /** * Set before loadDocument: when loading annotations, the XFDF it returns is used instead of the annotations stored in the PDF (for example when annotations are stored on a server) * @param retriever Receives the document id and resolves to the XFDF to load; null to read annotations from the PDF again. */ setDocumentXFDFRetriever(retriever: DocumentXFDFRetriever | null): void; private unmounted; /** Closes the document, removes all listeners and unbinds the DOM; loadDocument rejects afterwards */ unmount(): Promise; /** Removes page content from the view (page containers and canvases); re-rendered on demand on updateView / scrolling */ removeContent(): void; private userBookmarks; private bookmarkShortcutsVisible; private bookmarkToggleOn; private bookmarkToggleOff; private readonly bookmarkShortcuts; /** * User bookmarks (page index, 0-based → text), unrelated to the document outline * @returns A copy of the bookmarks, keyed by 0-based page index. */ getUserBookmarks(): Record; /** * An object (page index → text) replaces them all; an array (page indexes) bookmarks these pages (text '-' by default) and removes the rest. Fires userBookmarksChanged on change * @param bookmarks An object mapping 0-based page indexes to text, or an array of 0-based page indexes. */ setUserBookmarks(bookmarks: Record | number[]): void; /** * Adds or replaces the user bookmark of a page. Fires userBookmarksChanged. * @param pageIndex Page index (0-based). * @param text Bookmark text. */ addUserBookmark(pageIndex: number, text: string): void; /** * Removes the user bookmark of a page. Fires userBookmarksChanged when it existed. * @param pageIndex Page index (0-based). */ removeUserBookmark(pageIndex: number): void; /** * Small bookmark icon at the top-right of each page (click to add / remove this page's bookmark); hidden by default * @param visible True to show the icons, false to hide them. */ setBookmarkIconShortcutVisibility(visible: boolean): void; /** * Called when a bookmark is added by clicking the bookmark icon (argument is the page index) * @param fn Receives the page index (0-based). Falsy values are ignored. */ setBookmarkShortcutToggleOnFunction(fn: (pageIndex: number) => void): void; /** * Sets the function called when a bookmark is removed by clicking the bookmark icon. * @param fn Receives the page index (0-based). */ setBookmarkShortcutToggleOffFunction(fn: (pageIndex: number) => void): void; /** Bookmark icon in the page container (when on): created if missing, filled / unfilled by whether bookmarked (class filled / unfilled) */ private updateBookmarkShortcut; private arrowKeyNavigation; /** Left / right arrow keys turn pages (off by default; not when focus is in an input or text is being edited) */ enableArrowKeyNavigation(): void; /** Stops the left and right arrow keys from turning pages. */ disableArrowKeyNavigation(): void; /** * Checks whether arrow keys turn pages. * @returns true after enableArrowKeyNavigation; false by default. */ isArrowKeyNavigationEnabled(): boolean; /** With arrow-key paging on: ← previous page, → next page (not when focus is in an input or editable element) */ private arrowKeyPage; private grayscale; private grayscaleAnnotations; /** Draws pages in grayscale (CSS filter, display only) */ enableGrayscaleMode(): void; /** Draws pages in color again. */ disableGrayscaleMode(): void; /** * Checks whether pages are drawn in grayscale. * @returns true after enableGrayscaleMode; false by default. */ isGrayscaleModeEnabled(): boolean; private automaticLinking; /** Pages already searched for URLs */ private readonly linkedPages; /** * Checks whether URLs in page text are turned into links. * @returns true by default. */ isAutomaticLinkingEnabled(): boolean; /** Turns URLs in page text into clickable links the first time the pointer moves over a page. Links are not saved to the file. */ enableAutomaticLinking(): void; /** Stops searching from now on; links already added stay */ disableAutomaticLinking(): void; /** The page structure changed: searched pages are recorded by new page numbers; links on deleted pages go with them, links on pages whose content changed are removed and searched again later */ private automaticLinksPagesChanged; /** Draws annotation layers in grayscale */ enableGrayscaleAnnotationsMode(): void; /** Draws annotation layers in color again. */ disableGrayscaleAnnotationsMode(): void; /** * Checks whether annotation layers are drawn in grayscale. * @returns true after enableGrayscaleAnnotationsMode; false by default. */ isGrayscaleAnnotationsModeEnabled(): boolean; private applyGrayscale; private printAnnotationsInColor; /** Annotations stay in color when printing (printing belongs to the UI layer; only the switch is stored here) */ enableAlwaysPrintAnnotationsInColor(): void; /** Turns off the switch that keeps annotations in color when printing. */ disableAlwaysPrintAnnotationsInColor(): void; /** * Returns the switch that keeps annotations in color when printing. * @returns true after enableAlwaysPrintAnnotationsInColor; false by default. */ isAlwaysPrintAnnotationsInColorEnabled(): boolean; private stylusMode; /** Stylus mode: drawing tools accept only the pen, and fingers scroll as usual */ enableStylusMode(): void; /** Turns off stylus mode; drawing tools accept touch input again. */ disableStylusMode(): void; /** * Checks whether stylus mode is on. * @returns true after enableStylusMode; false by default. */ isStylusModeEnabled(): boolean; /** In stylus mode a finger pressed with a drawing tool: not passed to the tool */ private fingerSkipped; private memoryRestricted; /** Memory constrained: the page bitmap cache drops to the lowest tier (restored when turned off) */ enableMemoryRestrictedMode(): void; /** Restores the page bitmap caching level that was in effect before enableMemoryRestrictedMode. */ disableMemoryRestrictedMode(): void; /** * Checks whether memory restricted mode is on. * @returns true after enableMemoryRestrictedMode. */ isMemoryRestrictedModeEnabled(): boolean; private viewportRenderMode; /** Renders only the part of the page in the viewport (previously only when the whole page was too large) */ enableViewportRenderMode(): void; /** Turns off viewport render mode and redraws all pages. */ disableViewportRenderMode(): void; /** * Checks whether viewport render mode is on. * @returns true after enableViewportRenderMode; false by default. */ isInViewportRenderMode(): boolean; /** IME input for Office documents (not for PDF): logs a warning without a document */ enableCompositionInput(): void; /** * Composition input applies to Office documents only; for PDF this does nothing. * @throws Error when no document is loaded. */ enableCompositionInputAsync(): Promise; /** Composition input applies to Office documents only; this does nothing. */ disableCompositionInput(): void; /** * Checks whether composition input is active. * @returns Always false. */ isCompositionActive(): boolean; /** * Watermark render quality. Watermarks are drawn as vectors, so only the value is stored; throws when out of range * @param quality A number greater than 0 and at most 10. Defaults to 1. */ setWatermarkRenderQuality(quality?: number): void; /** * How many pages one search pass processes (we give results page by page; only the value is stored) * @param size Number of pages, rounded up; values not greater than 0 are ignored with a warning. */ setSearchPageBatchSize(size: number): void; /** Does nothing */ setRenderBatchSize(): void; private pageVisibilityCallback; /** * Called when a page becomes visible (argument is the page number; called again when the same page leaves and comes back) * @param callback Receives the page number (1-based); null removes it. */ setPageVisibilityCallback(callback: ((pageNumber: number) => void) | null): void; private annotationImportOptions; /** * Import options for loading the document's annotations (our annotations are read directly from the Worker; only the value is stored) * @param options The import options; a shallow copy is stored. */ setAnnotationImportOptions(options: Record): void; private visiblePagesFirst; /** When loading annotations, annotations on visible pages are read first (drawn as soon as read), then the rest */ enableLoadingAnnotationsFromVisiblePages(): void; /** Loads annotations in page order again, without reading visible pages first. */ disableLoadingAnnotationsFromVisiblePages(): void; /** We read annotations of all pages on load anyway (continuing with the rest when visible pages go first), so nothing to do here */ downloadRemainingAnnotations(): void; private internalTransform; private pagesUpdatedTransform; /** * Changes the XFDF of the document's annotations before they load: transform(xfdf, callback, options), callback returns the changed XFDF * @param transform The transform function, or null to remove it. */ setInternalAnnotationsTransform(transform: InternalAnnotationsTransform | null): void; /** * Changes the XFDF of annotations on inserted / merged pages before they are read (as above) * @param transform The transform function, or null to remove it. */ setPagesUpdatedInternalAnnotationsTransform(transform: InternalAnnotationsTransform | null): void; /** Unbinds listeners and clears the page DOM; the viewer is not used afterwards */ dispose(): void; /** * The page structure changed: annotations move to the new page numbers (removed on deleted pages, read on new pages); page containers, bitmaps, page text, search results and selection all start over, * the current page stays within the page count, and pagesUpdated fires after re-layout */ private pagesChanged; /** Drops all page bitmaps of this document and re-renders visible pages (the old image stays until the new one arrives); fires pagesUpdated (all pages contentChanged, source 'refresh'). Call after changing layers or separations; thumbnails are refetched from it */ refreshAll(): void; /** Internal: only redraws, without firing pagesUpdated (viewport render mode only changes how pages are drawn, not their content) */ private repaintAll; /** * Partial redraw of tile pages (every content edit comes here, and rendering can only queue on the main Worker): previously the whole page was invalidated and the base image and all visible tiles redrawn, * measured ~220 ms per typed character on light pages and ~1.1 s on heavy ones; now only the changed regions are rendered at the tile tier and pasted into the surface, plus a separate piece into the base image at its multiplier. * Tiles requested before the change and not yet arrived carry old content: canceled and their records deleted, requested again with the new version in the next round. Returns false when conditions are not met (switching tiers, surface still hidden, view rotated), redrawing the whole page */ private refreshTileRegions; /** * Renders these regions (unrotated page coordinates, extended by margin pt) at target's multiplier, aligns them to its pixels and pastes them in. target is a canvas covering page device pixels * [left, left + width) × [top, top + height) (multiplier scale = device pixels / pt); with pad > 0, pad more pixels are rendered on each side (clamped to the whole page fullWidth × fullHeight) and then cropped, * keeping the crop edges far enough from the pasted area (glyphs on the crop edge take another path in the engine, see TILE_RENDER_PAD) */ private patchRegions; /** * Drops the cached bitmaps of a page and renders it again. * @param pageNumber Page number (1-based). */ refreshPage(pageNumber: number): void; /** * Cancels rendering in progress for the page (the on-screen canvas stays) * @param pageNumber Page number (1-based). Pages without a view are ignored. */ stopPageRender(pageNumber: number): void; /** * Recomputes visible pages for the current viewport and schedules rendering (arguments accepted for compatibility and ignored) * @param _visiblePages Unused; kept for compatibility. * @param _currentPage Unused; kept for compatibility. */ updateView(_visiblePages?: number[], _currentPage?: number): void; /** Immediately (without waiting for the next frame) recomputes visible pages, fires events and schedules rendering */ updateVisiblePages(): void; /** * Re-lays out after page sizes or rotation change * @param _pageNumbers Unused; kept for compatibility. All pages are laid out again. */ recalculateLayout(_pageNumbers?: number[]): void; /** Annotations of the current document are fully read (resolves after annotationsLoaded) */ getAnnotationsLoadedPromise(): Promise; /** * Sets the scroll container of the viewer; scrolling and resizing it update the visible pages. * @param el The scrollable element that contains the viewer element. */ setScrollViewElement(el: HTMLElement): void; /** * With text selected, a press anywhere outside the page viewing area (toolbar, sidebar and so on) clears the selection. * Exception: presses inside elements marked data-keep-text-selection (text popups) or dialogs (role="dialog") do not clear, so the selection survives until "Copy" is clicked. * Presses in the page viewing area and scroll container are handled by the current tool (which clears it itself) */ private bindDocumentPress; /** * Returns the scroll container element. * @returns The element set with setScrollViewElement. */ getScrollViewElement(): HTMLElement; /** * Page containers flow in this element (see syncFlow); it is set to position: relative without padding (window coordinates use its top-left as origin) and sized by the layout * @param el The element that holds the page containers. */ setViewerElement(el: HTMLElement): void; private containerBackground; /** * Returns the element that holds the page containers. * @returns The element set with setViewerElement. */ getViewerElement(): HTMLElement; /** * Page margin (CSS px), 20 by default: left between pages, above the first page, below the last page and on both sides of pages, the same in all display modes. * Not scaled with zoom. * Re-lays out immediately when set, and recomputes the zoom in fit modes * @param margin Margin in CSS pixels. */ setMargin(margin: number): void; /** * Returns the page margin. * @returns Margin in CSS pixels. Defaults to 20. */ getMargin(): number; /** * Sets the background color of page containers, shown before a page is rendered. * @param color A CSS color. */ setDefaultPageColor(color: string): void; /** The scroll container size changed (called automatically on window resize): recomputes the fit zoom and visible pages */ scrollViewUpdated(): void; /** * Returns the number of pages. * @returns The page count, or 0 when no document is loaded. * @example * ```js * const { documentViewer } = instance.Core; * documentViewer.addEventListener('documentLoaded', () => { * console.log(`The document has ${documentViewer.getPageCount()} pages`); * }); * ``` */ getPageCount(): number; /** * Returns the current page. * @returns The current page number (1-based). * @example * ```js * const { documentViewer } = instance.Core; * console.log(`Page ${documentViewer.getCurrentPage()} of ${documentViewer.getPageCount()}`); * ``` */ getCurrentPage(): number; /** * In continuous modes scrolls the page's top edge to the top of the viewport; in non-continuous modes switches to the group containing the page * @param pageNumber Page number (1-based); rounded and clamped to the page range. Does nothing without a document. * @param _isSmoothScroll Unused; kept for compatibility. * @example * ```js * const { documentViewer } = instance.Core; * // Page numbers start at 1; out-of-range numbers are clamped to the first or last page. * documentViewer.setCurrentPage(documentViewer.getCurrentPage() + 1); * ``` */ setCurrentPage(pageNumber: number, _isSmoothScroll?: boolean): void; /** * Unrotated page width (getPageInfo is the display size including /Rotate; width and height are swapped back at 90° / 270°) * @param pageNumber Page number (1-based). * @returns Width in PDF points. Throws when no document is loaded. */ getPageWidth(pageNumber: number): number; /** * Returns the unrotated page height, ignoring the page's own rotation. * @param pageNumber Page number (1-based). * @returns Height in PDF points. * @throws ComPDFKitError when no document is loaded. */ getPageHeight(pageNumber: number): number; /** * Size of the page in the viewport: full rotation (page /Rotate + view rotation), zoom not applied * @param pageNumber Page number (1-based). * @returns The displayed width and height in PDF points. Throws when no document is loaded. */ getViewportPageInfo(pageNumber: number): { /** Displayed width in PDF points. */ width: number; /** Displayed height in PDF points. */ height: number; }; /** * Zoom of this page: the one set by setPageZoom if any, otherwise the overall zoom * @param pageNumber Page number (1-based). * @returns The zoom level (1 is 100%). */ getPageZoom(pageNumber: number): number; private readonly pageZooms; /** * Sets this page's own zoom (null removes it and follows the overall zoom again). The layout is redone and this page re-rendered * @param pageNumber Page number (1-based). Throws a RangeError when out of range. * @param zoom The zoom level (1 is 100%), or null to follow the overall zoom. */ setPageZoom(pageNumber: number, zoom: number | null): void; private rightToLeft; /** In two-page (facing, cover) modes, lays out pages from right to left */ enableRightToLeftPageRendering(): void; /** Lays out pages from left to right again. */ disableRightToLeftPageRendering(): void; /** * Checks whether two-page modes lay out pages from right to left. * @returns true after enableRightToLeftPageRendering; false by default. */ isRightToLeftPageRenderingEnabled(): boolean; /** Layout inputs changed: re-lay out, place page containers at their new positions, re-render visible pages */ private relayout; private requireDocument; /** * Scrolls a point on the page (display-orientation page space, pt, clamped into the page) to the top-left of the viewport; the second argument is the vertical offset * @param pageNumber Page number (1-based). * @param verticalOffset Distance from the top of the page in points. * @param horizontalOffset Distance from the left of the page in points. * @param _useSmoothScroll Unused; kept for compatibility. * @example * ```js * const { documentViewer } = instance.Core; * // Bring the point 200 pt from the top and 50 pt from the left of page 3 to the top-left of the viewport. * // Note the order: the vertical offset comes before the horizontal offset. * documentViewer.displayPageLocation(3, 200, 50); * ``` */ displayPageLocation(pageNumber: number, verticalOffset: number, horizontalOffset: number, _useSmoothScroll?: boolean): void; /** Goes to the first page. */ displayFirstPage(): void; /** Goes to the last page. */ displayLastPage(): void; /** * Jumps to the bookmark's target (fires displayPageLocation, goes to that page and scrolls to the target position); link bookmarks open their address in a new window * @param bookmark A bookmark from Document.getBookmarks. Invalid destinations are ignored with a warning. * @example * ```js * const { documentViewer } = instance.Core; * const [first] = await documentViewer.getDocument().getBookmarks(); * if (first) * documentViewer.displayBookmark(first); * ``` */ displayBookmark(bookmark: Bookmark): void; /** * Switches to FitMode.Zoom; with x / y (window coordinates) scrolls there, otherwise keeps the page point at the viewport's top-left in place * @param zoom The zoom level (1 is 100%). * @param x Horizontal scroll target in window coordinates (pixels within the viewer element); used only together with y. * @param y Vertical scroll target in window coordinates; used only together with x. * @example * ```js * const { documentViewer } = instance.Core; * documentViewer.zoomTo(1.5); // 150% * documentViewer.zoomTo(documentViewer.getZoomLevel() * 1.25); // zoom in by 25% * ``` */ zoomTo(zoom: number, x?: number, y?: number): void; /** * Zooms while keeping the page point at (offsetX, offsetY) of the viewport in place; switches to FitMode.Zoom. * @param zoom The zoom level (1 is 100%). * @param offsetX Horizontal distance from the left edge of the viewport in CSS pixels. * @param offsetY Vertical distance from the top edge of the viewport in CSS pixels. */ zoomToMouse(zoom: number, offsetX: number, offsetY: number): void; private zoomPreview?; private clearZoomPreview; private updateZoomPreview; /** Merges continuous zooming: gesture zooms closer than ZOOM_BURST_MS enter "in gesture", during which no new tier is requested; ends after ZOOM_BURST_MS of stillness and requests then */ private zoomBursting; private lastGestureZoomAt; private burstTimer; private noteZoomGesture; /** * Continuous zooming started: the first zoom requested tiles at the tier of that moment right away, and the tier keeps changing during the gesture; those (intermediate tiers) not yet arrived are canceled and their records deleted, * leaving the render Workers to the final tier after stopping (measured 45–56 tiles wasted on intermediate tiers in one wheel zoom). Tiles already drawn stay in the surface; the base image stays (standing in during the gesture) */ private dropUnarrivedTiles; /** * Returns the zoom level. * @returns The zoom; 1 is 100%. * @example * ```js * const { documentViewer } = instance.Core; * documentViewer.addEventListener('zoomUpdated', (zoom) => { * console.log(`Zoom: ${Math.round(zoom * 100)}%`); * }); * console.log(documentViewer.getZoomLevel()); // 1 means 100% * ``` */ getZoomLevel(): number; /** Can also be taken from an instance: documentViewer.FitMode.FitWidth */ get FitMode(): typeof FitMode; /** * Sets the fit mode and applies it right away. * @param mode The fit mode. * @example * ```js * const { documentViewer, FitMode } = instance.Core; * documentViewer.setFitMode(FitMode.FitWidth); * ``` */ setFitMode(mode: FitMode): void; /** * Returns the fit mode. * @returns The current fit mode. * @example * ```js * const { documentViewer, FitMode } = instance.Core; * if (documentViewer.getFitMode() !== FitMode.FitPage) * documentViewer.setFitMode(FitMode.FitPage); * ``` */ getFitMode(): FitMode; /** * Rotates the view 90 degrees clockwise. Does not change the document. * @param pageNumber Page to rotate; all pages when omitted. * @example * ```js * const { documentViewer } = instance.Core; * documentViewer.rotateClockwise(); // all pages * documentViewer.rotateClockwise(2); // only page 2 * ``` */ rotateClockwise(pageNumber?: number): void; /** * Rotates the view 90 degrees counterclockwise. Does not change the document. * @param pageNumber Page to rotate; all pages when omitted. */ rotateCounterClockwise(pageNumber?: number): void; /** * View rotation (does not change the document); without pageNumber, sets all pages and clears per-page settings * @param rotation Quarter turns clockwise, as a PageRotation value from 0 to 3; other values are ignored. * @param pageNumber Page number (1-based) to rotate; all pages when omitted. * @example * ```js * const { documentViewer, PageRotation } = instance.Core; * documentViewer.setRotation(PageRotation.E_90); // all pages * documentViewer.setRotation(PageRotation.E_0, 1); // page 1 back to upright * ``` */ setRotation(rotation: PageRotation, pageNumber?: number): void; /** * Returns the view rotation, not including the page's own rotation. * @param pageNumber Page number (1-based); omit for the rotation of all pages. * @returns The rotation. * @example * ```js * const { documentViewer, PageRotation } = instance.Core; * documentViewer.addEventListener('rotationUpdated', (rotation, pageNumber) => { * console.log(pageNumber ? `Page ${pageNumber}` : 'All pages', rotation * 90, 'degrees'); * }); * console.log(documentViewer.getRotation() === PageRotation.E_0); * ``` */ getRotation(pageNumber?: number): PageRotation; /** * View rotation + the page's own rotation * @param pageNumber Page number (1-based). * @returns The combined rotation in quarter turns clockwise (0 to 3). */ getCompleteRotation(pageNumber: number): PageRotation; /** * View rotation of each page * @returns An object mapping each page number (1-based) to its view rotation in quarter turns (0 to 3). */ getPageRotations(): Record; /** * Sets the view rotation of several pages. * @param rotations Page number (1-based) to rotation. */ setPageRotations(rotations: Record): void; private scrollViewElement; private viewerElement; private detachScrollView?; private detachViewer?; private detachDocumentPress?; private pressDocument?; /** Presses on the scroll container (outside pages) go to the same handling as on the viewer element (set by bindInput) */ private outsidePress?; private detachPressure?; private annotationManager?; private annotationHistoryManager?; private toolModeMap?; private measurementManager?; private contentEditManager?; private textManager?; private textHighlightColor; private textSelectionSensitivity; private searchResults; private activeSearchResult; private searchMode; /** Results to highlight (results in HIGHLIGHT mode and those added by displayAdditionalSearchResults) */ private highlightedResults; /** The search in progress; clearSearchResults / a new search replaces it */ private searchRun; /** The previous match of a non-full search (search term and mode, page, how many on that page were given): the same search called again continues from it */ private searchCursor; private searchColors; private contentEditHistoryManager?; private toolMode?; /** Appearance preview of the draft while drawing: the latest one drawn by its own rectangle; no new request while one is in flight, and another is requested on return if the draft changed (see drawDraftPreview) */ private draftPreview; private annotationsLoaded; private annotationsDone; private detachComplete?; private displayModeManager?; private pipeline?; private margin; /** Flow layout: the vertical flex body in the viewer (first child is the spacer block), and the rows laid out (keyed by layout row number) */ private flowBody?; private readonly flowRows; private zoom; private fitMode; private measuredScrollbar; private rotation; private readonly pageRotations; private currentPage; private pinnedScroll?; /** Remembers where we scrolled programmatically: later scroll events at this position do not count as user scrolling (both horizontal and vertical are compared) */ private pinScroll; private pageColor; private visiblePages; private readonly containers; /** Annotation layer canvas of each page (above the page bitmap) and pages waiting to be redrawn */ private readonly annotationLayers; /** Current page bitmap canvas of each page and its position in the container (CSS px): highlights copy its pixels for multiply blending */ /** Page bitmap and its position in the page container; boxWidth / boxHeight are the page container size at that time (positions are converted by it after zooming, so the old bitmap standing in is not misplaced) */ private readonly pageBitmaps; private readonly dirtyLayers; private readonly pageViews; private pendingRenders; /** * Pointer events are bound on the viewer element and keyboard events on its document: first given to the current tool (not without a document), * then forwarded as viewer events of the same name (with the native event). Left button presses capture the pointer, so moves and releases arrive even when dragged outside the viewer. * Multi-touch: when a second touch pointer goes down (except with the pan tool, which recognizes two-finger panning and pinching itself), the tool's multiTouchStart is called (the annotation being drawn is deleted); * afterwards, until all fingers are up, touch pointers are only forwarded as viewer events and not given to the tool, and the UI layer does pinch zoom from them; mouse and pen are unaffected. * tap: press to release within 300 ms, moving no more than 10 px (left button / primary pointer, mouse, touch and pen alike) fires tap (with the release event); longTap: when touch or pen holds still for 500 ms * longTap fires right away (with the press event; the right click of mobile devices); calling preventDefault in a listener keeps this release from the tool; a second finger going down, moving or releasing cancels it. */ private bindInput; /** Fills when the pointer is over a fillable form widget (not in form creation mode, content editing mode, or with annotations hidden) */ private fillWidgetAt; /** * Blue "SIGN HERE" label at the top-left of unsigned signature fields (73 × 22 screen pixels, #1460F3 background, white bold 12px text, * scaled down as a whole when the field is smaller). The text defaults to the fixed English "SIGN HERE"; with SignatureCreateTool.setTextHandler * the handler's text is used, condensed when wider than the label */ private drawSignHereTag; private setCurrent; private setFitModeValue; private setZoom; /** Width of the vertical scrollbar (measured by placing a small overflow-y: auto div in the viewer's document and taking the difference); 0 when it cannot be measured. Cached per document */ private scrollbarWidth; /** Left and right padding of the scroll container (px); 0 when computed styles are unavailable */ private horizontalPadding; /** * FitWidth: the current page (the whole row with multiple columns) together with page margins fills the width; FitPage: also fits the height and takes the smaller. * The width subtracts the page margins on both sides (plus those between columns), the height subtracts 5px; * the vertical scrollbar width is also subtracted; with horizontal overflow the height is offsetHeight (including the horizontal scrollbar), falling back to the parent element when 0; * the scroll container's left and right padding is subtracted too */ private applyFitMode; private afterRotation; /** Puts window coordinates (x, y) at the viewport's top-left */ private scrollToWindow; /** * Sets the viewer element's width and height by the DisplayMode layout, resizes existing page containers and re-flows them (syncFlow); those not in the layout are removed. * Containers are created only for visible and prefetched pages (ensureContainer), so long documents do not have tens of thousands of DOM nodes. */ private applyLayout; private ensureContainer; private sizeContainer; /** * Lays out page containers as a flow (without floats or positioning): a vertical flex body in the viewer, * first a spacer block (standing in for rows above that are not laid out), then the rows: horizontal flex, margin above and to the left, margin between cells; * cell width is the column width and height the row height; page containers are centered vertically in the cell and aligned horizontally by column (centered in one column; in two columns the left aligns right, the right aligns left). * Only the range of rows with page containers is laid out (virtualized); cells in the range without containers stay empty as placeholders. Rows already laid out are updated in place, not reinserted (not interrupting input focus in pages). * Margins do not collapse in flex, so the DOM agrees with the DisplayMode formulas */ private syncFlow; private clearFlow; private removeContainer; /** * Draws a page's annotation layer: the canvas fills the page container (× multiplier), and the transform maps unrotated page space (pt) to canvas pixels (including full rotation and zoom). * Vector types call draw(); the rest use AppearanceManager's appearance bitmaps (requested when missing, redrawn on arrival). */ private drawAnnotationLayer; /** * Whether anything will be drawn on this page's annotation layer (err on the side of yes: annotations count whether shown or not). Every kind drawn by drawAnnotationLayer must have a matching condition here; * add one when adding something drawn on the annotation layer. When conditions change (adding annotations, selecting text, searching, starting content editing...) each already makes this page redraw its annotation layer */ private annotationLayerNeeded; /** Whether the annotation is drawn entirely as canvas vectors (no engine appearance bitmap): ones with custom drawing, arcs, and types in VECTOR_TYPES */ private drawsOnCanvas; /** Cloudy annotations and free text dragged with the new appearance not yet arrived (drawn from appearance bitmaps as usual once it arrives) */ private readonly liveClouds; /** Padding of the text box within the bitmap when the appearance bitmap of a callout text box was generated: dragging the arrow or knee changes the annotation rectangle, and cropping the old bitmap must use the padding at generation time, not the current one */ private readonly bitmapPadding; /** * Draws cloudy borders and the box and callout of callout text boxes live by the current shape (while dragging, or after release until the new version's appearance arrives). Rectangles and polygons are drawn by draw (clouds included); * text boxes paste the text box part of the previous appearance into the current text box, then draw clouds along it (arc spacing as written to the file, file-appearances.ts). Returns false when not drawn */ private drawLiveCloud; /** Multi-selection: a 1px dashed box per annotation and a 2px outer box; when the whole group can resize, the outer box has 8 handles */ private drawGroupSelection; /** Selection box (dashed) and handles of selected annotations, drawn in device pixels, line width not scaled with zoom */ private drawAnnotationSelection; /** Unrotated page space → display-orientation pixels (s pixels / pt), including full page and view rotation */ private pageTransform; /** * Multiply blending (BlendMode multiply: text highlights, highlighter, PDF appearance /BM Multiply): first the page bitmap under the annotation (the quadrilaterals for highlights, the annotation rectangle for others) * is placed behind what the annotation layer has drawn, then the annotation multiplies with it in the annotation layer, the same as multiplying with the page (annotations drawn underneath earlier are multiplied too); * other annotations still blend normally. Before the page bitmap arrives there are no pixels to place behind; it redraws when the bitmap arrives. */ private copyPageUnder; /** Appearance bitmaps: fetched by zoom tier, drawn when present, requested otherwise (new annotations not yet confirmed by the Worker are fetched after confirmation) */ /** * Draws the appearance bitmap; returns true when drawn. When the current version has not arrived, the annotation's latest existing bitmap (an old version or another zoom tier) stands in, and the current version is fetched; * returns false when there is none (the caller draws vectors) */ /** Appearance preview of drafts: draws the latest one arrived; requests another when the draft changed and no request is in flight */ private drawDraftPreview; /** * Multiplier of appearance bitmaps: device pixels / pt (zoom × canvasMultiplier, three decimals as cache key). Not by zoom tier: * bitmaps are one-to-one with device pixels, without resampling (after resampling lines get thinner and blurrier and look smaller than while drawing) */ private appearanceScale; /** * Draws the appearance bitmap at (x, y, w, h) (page coordinates, current transform page → device pixels). When the bitmap was rendered at the current multiplier and the page is not rotated, * it is pasted one-to-one aligned to whole device pixels; otherwise scaled into the rectangle (the previous one standing in during zooming) */ private blit; /** Rotation angle when the appearance bitmap was rendered (by annotation id and version): while dragging the rotation of box-rotated annotations, the old bitmap is drawn rotated by the angle difference */ private readonly bitmapRotations; /** * Draws the appearance bitmap; when a box-rotated annotation (rectangle, ellipse, stamp, free text) is now at a different angle than when the bitmap was rendered (rotating by dragging, new bitmap not yet arrived), * the bitmap is drawn at the bounding box size of that time, rotated around the center by the angle difference, without stretching */ private blitTurned; private drawAppearance; /** * The form widget's bitmap does not match the current rectangle size (resizing by dragging handles, new appearance not yet arrived): pasted at the bitmap's own size and cropped to the new rectangle, * without stretching text and check marks (they do not stretch with the box in the engine's new appearance either). Check boxes, radio buttons, buttons and signature fields are centered, text types left-aligned, multiline and lists top-aligned, others vertically centered. * Returns false when sizes match, pasted as usual */ private blitWidgetUnstretched; /** Requests the current version's appearance bitmap when it is missing and not being requested (new ones wait for Worker confirmation), and redraws this page on arrival */ private requestAppearance; private clearView; /** Recomputes visible pages in the next frame (scrolling, zooming and so on are merged per frame here) */ private requestUpdate; /** * Runs a visible page update right away (without waiting for the next frame): wheel / pinch call zoomToMouse in a rAF callback, and the layout changes this frame; * through requestUpdate images would only be swapped next frame, and even cached images would show a frame of the old image stretched first. Cache hits are drawn in a microtask, before this frame paints */ private updateNow; /** Read only: regions of visible pages, prefetched pages and pages needing partial rendering */ private measureVisible; /** Write only: fires visible page / current page events, schedules rendering, drops pages that left the view */ private applyVisible; /** Intersection of the viewport (extended proportionally) and the page, display-orientation page space pt; null when not intersecting */ private regionOf; /** * Zoom for whole-page rendering: when still, rendered at exact zoom × multiplier, bitmaps 1:1 with device pixels (rounding up by √2 tiers would show 90% from the 100% tier image scaled down by 1.11, with soft text). * Tiers are only used in transitions: borrowing the nearest cached image to stretch during continuous zooming, previews, tile base images, idle prerendering. * When the exact-zoom bitmap exceeds the whole-page bitmap limit, "the largest zoom that just fits" is used instead: the requested zoom does not change while zooming within that range (still a stable key) */ private tierZoom; /** Zoom used for a page's render key: whole pages and tiles both by tier (whole pages also capped by the bitmap limit; tiles not, as a bitmap is only one tile large) */ private renderZoom; /** * Whether this page renders as tiles: the whole-page bitmap at exact zoom exceeds TILE_MODE_MIN_PIXELS, or viewport render mode is on (forcing only the viewport part). * Not split with separations on (separation rendering is always a whole-page bitmap); whole-page rendering with a capped multiplier is used instead */ private isTileMode; /** Upper limit of automatic retries after render failures (same page, tier / rotation / region) */ private static readonly RENDER_RETRIES; private readonly renderRetries; /** Render failures have no callback: while a request is in flight, check every so often, and when the request is gone without the image arriving, trigger an update so renderPage retries */ private renderWatch; private watchRenders; /** During continuous zooming: no requests, only the cached whole-page image closest in size to the target (if closer than the one shown) is put up */ private showNearest; /** Lost while the request was in flight (render failures have no callback): the whole-page / base image / tile request is gone but the image has not arrived */ private lostRequest; /** tileRect: for tile-mode pages the intersection of viewport and page (display-orientation page space pt), null when not intersecting (only the whole-page base image is kept); undefined for whole-page rendered pages */ private renderPage; /** * When zooming (or scrolling back) the target tier has no image yet: the cached whole-page image of another tier closest in size to this page is shown first (CSS stretched / shrunk), * and replaced when the real image arrives. Always borrowed when the page has no image yet; when it has one, replaced only when the cached one is closer to the target than the one shown (or the one shown is from before rotation * or of unknown origin) */ private borrowNearest; /** * Fills the container with the whole page (in tile mode it is the whole-page base image, with the tile layer above and the annotation layer on top). zoom is the zoom this bitmap was rendered at: the bitmap is the exact whole-page size rounded up, * so percentages are computed by the exact size (the extra fraction of a pixel is cropped by the container), and the image at the current zoom goes on screen 1:1; stretching to 100% would blur on non-integer screens like 1.75× */ private placeCanvas; private redrawBlendLayer; /** Cancels all in-flight requests of this page (whole page / preview / base image / tiles), leaving the image on screen */ private cancelRequests; /** * Cancels this cell's request. Cells of a batch share one request (the Worker renders a batch at once), so the whole batch is canceled and the ids of the batch's other cells are cleared too * (those not drawn are batched again next round, without counting retries). */ private cancelTileRequest; private cancelView; /** Switches this page's "still something left to draw" state: fires beginRendering at start (the first), finishedRendering at end (the last) */ private setViewPending; /** Zoomed out so far that tiles are no longer used, or viewport render mode turned off: put away the tile layer and keep the whole-page base image as the current image */ private leaveTileMode; private dropTileEntries; /** This page's surfaces from bottom to top (the old tier's below) */ private surfaceNodes; /** Detaches and releases all surfaces of this page (shrunk to 0×0, so iOS canvas memory does not wait for GC) */ private releaseSurfaces; /** Puts the whole-page base image, tile layer and annotation layer into the page container in this order (other existing children of the container are replaced as placeCanvas agrees) */ private attachTileLayer; /** * This page's surface at this tier: reused when it already covers the visible range (and the prefetch extension when allowed); otherwise created anew (visible range extended by TILE_RING + 1 rings, the extension reduced first when over the pixel limit), * copying the overlapping part of the old surface at the same tier. When the tier changes, the old surface stays behind (prevSurface) and is removed once the new tier's visible tiles are complete */ private ensureSurface; /** Hidden first; shown after ms if (the surface at the same tier is) still hidden. Without ms: a region change at the same tier, continuing the timer started by the previous surface */ private hideSurface; private showSurface; private renderTilePage; /** A tile arrived: drawn into this page's surface synchronously (not through a delivery canvas; the bitmap is drawn in directly), then check whether this page is done */ private tileArrived; /** * Whether a tile-mode page is "done": the base image arrived and all visible tiles arrived (or were given up after the retry limit). When done, the old tier's tiles are removed and pageComplete fires; * back to "not done" when new tiles need waiting for (scrolling, zooming) */ private updateTilePending; private renderSettled; private static readonly IDLE_PRERENDER_MS; /** Render scale of the low tier (device pixels / pt) */ private static readonly IDLE_PRERENDER_SCALE; private static readonly IDLE_PRERENDER_SHARE; private static readonly IDLE_PRERENDER_INFLIGHT; private idleTimer; private idlePoll; private readonly idleIds; private idleQueue; private idleZoom; private stopIdlePrerender; private armIdlePrerender; private startIdlePrerender; /** Number of pages low-tier whole-page images can hold: 80% of the total budget (budgetPages), and how much room is left now (room, minus what is used) */ private prerenderBudget; private pumpIdlePrerender; /** Makes the page re-render on the next updateVisiblePages, keeping the on-screen canvas */ private invalidateView; /** Cancels rendering and removes the canvas (the cache stays, so scrolling back shows it instantly) */ private dropPage; /** * Page under the pointer and PDF coordinates (bottom-left origin, y upward, pt) * @param e A mouse or pointer event, or any object with clientX and clientY. * @returns The page number (1-based; the current page when the pointer is on no page) and the point in PDF coordinates. Throws when no document is loaded. */ getPDFCoordinatesFromMouseEvent(e: Pick): { /** Horizontal position in PDF coordinates. */ x: number; /** Vertical position in PDF coordinates. */ y: number; /** Page under the pointer (1-based). */ pageNumber: number; }; /** Position of the last pointer move (screen coordinates), for pasting at the mouse position */ private lastPointer; /** * Page and page coordinates under the last pointer position (used for pasting at the mouse position). null when the pointer has not moved over the viewer yet, or the last position is on no page * (the internal getLastMouseLocation falls back to the current page when not on a page; pasting annotations relies on it) * @returns The page number (1-based) and the point in page coordinates, or null. */ getViewerCoordinatesFromMouseLocation(): { /** Horizontal position in page coordinates. */ x: number; /** Vertical position in page coordinates. */ y: number; /** Page under the pointer (1-based). */ pageNumber: number; } | null; /** * Page under the pointer and page coordinates (unrotated page, top-left origin, pt); by the current page when on no page * @param e A mouse or pointer event, or any object with clientX and clientY. * @returns The page number and the point in page coordinates. */ getViewerCoordinatesFromMouseEvent(e: Pick): { /** Horizontal position in page coordinates. */ x: number; /** Vertical position in page coordinates. */ y: number; /** Page under the pointer (1-based); the current page when the pointer is on no page. */ pageNumber: number; }; /** * The part of this page actually rendered; tiles replaced the viewport rectangle of partial rendering, so it equals getViewportRegionRect * @param pageNumber Page number (1-based). * @returns The visible region in page coordinates (points), or null when the page is not visible. */ getExactViewportRegionRect(pageNumber: number): Rect | null; /** * Intersection of the viewport and the page, display-orientation page space (pt); null when not visible * @param pageNumber Page number (1-based). * @returns The visible region, or null when the page is not visible. */ getViewportRegionRect(pageNumber: number): Rect | null; /** * Selected text; with a page number only that page * @param pageNumber Page number (1-based); all pages when omitted. * @returns The selected text, or an empty string when nothing is selected. * @example * ```js * const { documentViewer } = instance.Core; * documentViewer.addEventListener('textSelected', (quads, text, pageNumber) => { * if (quads) * console.log(`Selected on page ${pageNumber}:`, text); * }); * const allSelectedText = documentViewer.getSelectedText(); * ``` */ getSelectedText(pageNumber?: number): string; /** * Quads of the selected text on one page (one quad per line, page coordinates). * @param pageNumber Page to read the selection of (1-based). * @returns The quads, or an empty array when nothing is selected on that page. * @example * ```js * // Highlight the text the user selected on the current page * const { documentViewer, annotationManager, Annotations } = instance.Core; * const pageNumber = documentViewer.getCurrentPage(); * const quads = documentViewer.getSelectedTextQuads(pageNumber); * if (quads.length) { * const highlight = new Annotations.TextHighlightAnnotation({ PageNumber: pageNumber }); * highlight.setQuads(quads); * highlight.StrokeColor = new Annotations.Color(255, 230, 0); * await annotationManager.addAnnotation(highlight); * } * ``` */ getSelectedTextQuads(pageNumber: number): Quad[]; /** * Quads of the selected text on every page that has a selection, grouped by page number (one quad per line, page coordinates). * @returns An object mapping page numbers (1-based) to their quads; empty when nothing is selected. * @example * ```js * const selected = instance.Core.documentViewer.getSelectedTextQuads(); * for (const [pageNumber, quads] of Object.entries(selected)) * console.log(`Page ${pageNumber}: ${quads.length} lines`); * ``` */ getSelectedTextQuads(): Record; /** * Quads of the selected text: an array for that page with a page number, otherwise grouped by page number. * @param pageNumber Page to read the selection of (1-based); omit for every page. * @returns The quads of that page, or an object mapping page numbers to quads when pageNumber is omitted. */ getSelectedTextQuads(pageNumber?: number): Record | Quad[]; /** * Checks whether any text is selected. * @returns true when the selection contains characters. */ isTextSelected(): boolean; /** * Selects the text between two points (page coordinates, with page numbers): each takes the nearest character, with the endpoint decided by the left / right half of the character; page text not loaded is loaded first * @param pt1 Start point in page coordinates, with its page number (1-based). * @param pt2 End point in page coordinates, with its page number (1-based). */ select(pt1: Point & { /** Page number (1-based) of the point. */ pageNumber: number; }, pt2: Point & { /** Page number (1-based) of the point. */ pageNumber: number; }): void; /** * Clears the text selection. * @example * ```js * const { documentViewer } = instance.Core; * if (documentViewer.isTextSelected()) * documentViewer.clearSelection(); * ``` */ clearSelection(): void; /** * Draws this page's text selection onto canvas, as the page is displayed (with its view and page rotation). * @param canvas The canvas to draw on; it covers the whole displayed page, so its width is the displayed page width (the page height after a quarter turn). * @param pageNumber Page number (1-based). */ drawSelection(canvas: HTMLCanvasElement, pageNumber: number): void; /** * Background color of selected text * @param color A CSS color. */ setTextHighlightColor(color: string): void; /** * How far (screen pixels) the pointer may be from characters and still select them; must be positive * @param sensitivity Distance in screen pixels; values not greater than 0 are ignored with a warning. */ setTextSelectionSensitivity(sensitivity: number): void; /** * Returns how far the pointer may be from characters and still select them. * @returns Distance in screen pixels. */ getTextSelectionSensitivity(): number; /** Fills the selection (quads in page coordinates) with the background color; the current transform is page → canvas */ private fillSelection; /** * Drag handles at both ends of the selection (10px #4982E6 drops; the start one at the bottom-left of the line start pointing up-right, the end one at the bottom-right of the line end pointing up-left). * Fixed screen size, so converted to page units by zoom */ private drawSelectionHandles; /** * Search (run page by page in the background, results arriving in page order, reversed with SEARCH_UP): * - with fullSearch (false by default) true, searches all pages; with false, stops at one match, and calling again with the same term and mode continues after the last match; * reaching the end gives DONE, and calling again starts over; without any callbacks the found result is shown (displaySearchResult) * - callbacks all receive result objects: onResult is FOUND, onPageEnd is PAGE (only when the mode includes PAGE_STOP), onDocumentEnd is DONE * Clears the previous results first, fires searchInProgress(true), searchResultsChanged for each page with results, and searchInProgress(false) when stopped. * With HIGHLIGHT in the mode, results are highlighted on the page * @param pattern The text or regular expression to find. An empty pattern only clears the previous results. * @param mode SearchMode bit flags, such as HIGHLIGHT, CASE_SENSITIVE, WHOLE_WORD, REGEX, SEARCH_UP and PAGE_STOP. * @param options `fullSearch`, the page range `startPage` / `endPage` (1-based, inclusive) and the callbacks `onResult`, `onPageEnd`, `onDocumentEnd` and `onError`. * @example * ```js * const { documentViewer, Search } = instance.Core; * documentViewer.textSearchInit('invoice', Search.Mode.HIGHLIGHT | Search.Mode.AMBIENT_STRING, { * fullSearch: true, * onResult: result => console.log(result.pageNumber, result.resultStr, result.ambientStr), * onDocumentEnd: () => console.log('Search finished'), * }); * ``` */ textSearchInit(pattern: string, mode: SearchMode, options?: TextSearchOptions): void; /** * Streaming search: returns a ReadableStream of only matches (resultCode FOUND, in page order), readable one by one with its reader, * or all at once with getAll() (repeated calls give the same array). modeOptions is a SearchMode or an array (bitwise OR); searchOptions limits the page range (inclusive, 1-based). * Like textSearchInit({ fullSearch: true }) it clears the previous results, fires searchInProgress, records results and highlights by mode; * when canceled by clearSearchResults before finishing, the stream closes right away (getAll does not wait forever). An empty stream without a document * @param pattern The text or regular expression to find. * @param modeOptions A SearchMode value or an array of them; 0 when omitted. * @param searchOptions Optional page range. * @param searchOptions.startPage First page to search (1-based, inclusive); the first page when omitted. * @param searchOptions.endPage Last page to search (1-based, inclusive); the last page when omitted. * @returns A stream of matches with an extra getAll() method. * @example * ```js * const { documentViewer, Search } = instance.Core; * // All matches at once * const results = await documentViewer.search('total', Search.Mode.WHOLE_WORD).getAll(); * console.log(`${results.length} matches`); * // Or one by one, limited to pages 1 to 5 * const reader = documentViewer.search('total', 0, { startPage: 1, endPage: 5 }).getReader(); * for (let r = await reader.read(); !r.done; r = await reader.read()) * console.log(r.value.pageNumber, r.value.resultStr); * ``` */ search(pattern: string, modeOptions?: number | number[], searchOptions?: { /** First page to search (1-based, inclusive). */ startPage?: number; /** Last page to search (1-based, inclusive). */ endPage?: number; }): SearchStream; /** * Replaces the text in search results (from search / getPageSearchResults) with replacement (calls ContentEditManager#replaceText); * throws when the results are empty or the first result has no text. Enters content editing mode (and stays in it); one entry in edit history * @param searchResults The results to replace. * @param replacement The new text. */ replace(searchResults: SearchResult[], replacement: string): Promise; /** * Stops the search in progress (the Worker stops between pages) and clears results and highlights * @example * ```js * const { documentViewer } = instance.Core; * documentViewer.clearSearchResults(); * ``` */ clearSearchResults(): void; /** * Returns the active search result. * @returns The result, or undefined when there is none. */ getActiveSearchResult(): SearchResult | undefined; /** * Makes it the current result: switches to the current result color, goes to that page and scrolls the match box to the middle of the viewport (setActiveSearchResult scrolls); fires activeSearchResultChanged. * To decide how to scroll yourself, use displaySearchResult(result, scrollFn) * @param result A search result. */ setActiveSearchResult(result: SearchResult): void; /** Sets the current result, redraws, fires the event (no scrolling) */ private activateSearchResult; /** Default scrolling: the center of the bounding rectangle of the match boxes goes to the middle of the viewport, scroll positions clamped above 0 */ private scrollToSearchResult; /** * Shows a result: adds it to the results, makes it current and scrolls to it (the second argument is a custom scroll function (pageNumber, quads) => void used instead of the default; * pass an empty function to not scroll) * @param result A search result. * @param scroll Optional function called with the page number (1-based) and the match quads instead of the default scrolling. */ displaySearchResult(result: SearchResult, scroll?: (pageNumber: number, quads: SearchResult['quads']) => void): void; /** * Adds a result to highlight along (as displayAdditionalSearchResults) * @param result A search result. */ displayAdditionalSearchResult(result: SearchResult): void; /** * Adds results obtained elsewhere to highlight along * @param results Search results; ones already present are not added twice. */ displayAdditionalSearchResults(results: SearchResult[]): void; /** * Results: only that page's with a page number, otherwise all (in arrival order) * @param pageNumber Page number (1-based); all pages when omitted. * @returns A new array of the results. */ getPageSearchResults(pageNumber?: number): SearchResult[]; /** * Returns the mode of the last search. * @returns The search mode flags. */ getCurrentSearchMode(): SearchMode; /** * Highlight colors of results and the current result * @param colors The colors to change; omitted ones keep their current value. * @param colors.searchResult CSS color of search result highlights. * @param colors.activeSearchResult CSS color of the active search result. */ setSearchHighlightColors(colors: { /** CSS color of search result highlights. */ searchResult?: string; /** CSS color of the active search result. */ activeSearchResult?: string; }): void; /** Search result highlights on this page (current transform page → canvas): results in HIGHLIGHT mode and those added by displayAdditionalSearchResults; the current result is always drawn */ private fillSearchResults; /** Shows annotations and makes them interactive (default) */ enableAnnotations(): void; /** Annotations are not drawn and cannot be clicked (none found under the pointer); annotations in the document are unchanged */ disableAnnotations(): void; private annotationsEnabled; /** * View watermark: drawn on every page (not written to the file), carried over to documents opened later; null removes it * @param options The watermark (diagonal, header, footer text or a custom draw function), or null to remove it. */ setWatermark(options: WatermarkOptions | null): Promise; /** * Returns the view watermark set with setWatermark. * @returns The watermark options, or null when none is set. */ getWatermark(): Promise; private watermark; /** * Whether documents opened in this view read layers and render by layer (see Document.setLayersEnabled); documents opened later are set the same way * @param enabled False to disable layers, true to enable them. */ setLayersEnabled(enabled: boolean): void; private layersEnabled; /** The view watermark is drawn in the annotation layer (before or after annotations), in page coordinates (rotating with the page) */ private drawWatermark; /** * Snaps to the nearest point on the page's vector content (unrotated page coordinates, pt): mode is a SnapModes value or array (DEFAULT = endpoints + midpoints + intersections by default); * combined modes take the nearest of endpoints / midpoints / intersections first, and points on lines only when there are none. Only within getSnapDefaultOptions().radiusThreshold (screen pixels); * when found, carries mode and modeName (the SnapModes key name); returned unchanged when not found. Segments are read by the Worker from the page content stream itself (the engine's snap export is unusable) * @param pageNumber Page number (1-based). Throws when no document is loaded. * @param x Horizontal position in page coordinates. * @param y Vertical position in page coordinates. * @param mode A SnapModes value or an array of them; SnapModes.DEFAULT when omitted. * @returns A Promise that resolves to the snapped point, or to the original point when nothing is in range. */ snapToNearest(pageNumber: number, x: number, y: number, mode?: number | number[]): Promise<{ /** Horizontal position of the snapped point. */ x: number; /** Vertical position of the snapped point. */ y: number; /** SnapModes value that matched; absent when nothing was found. */ mode?: number; /** Key name of that SnapModes value; absent when nothing was found. */ modeName?: string; }>; /** * Compares text page by page with the document in another viewer: a highlight annotation for text deleted / replaced in this one, and for text added / replaced in the other * (those with the same custom data TextDiffID are the same difference); previous difference annotations on both sides are deleted first; fires compareAnnotationsLoaded when done * @param otherViewer The viewer holding the other document. Both viewers need a loaded document; the comparison waits for their annotations to load. * @param options Optional `beforeColor` and `afterColor` of the highlights. * @returns A Promise that resolves to the difference annotations on both sides and the number of differences. */ startSemanticDiff(otherViewer: DocumentViewer, options?: SemanticDiffOptions): Promise<{ /** Difference annotations added to this viewer's document. */ doc1Annotations: Annotation$1[]; /** Difference annotations added to the other viewer's document. */ doc2Annotations: Annotation$1[]; /** Number of differences. */ diffCount: number; }>; /** Deletes the difference annotations of this comparison (both sides) */ stopSemanticDiff(): Promise; /** Viewers on both sides of startSemanticDiff (stopSemanticDiff clears both from either side) */ private diffPeers; /** * Asks listeners of beforePermissionAction whether an action may proceed; a listener calls preventDefault() to deny it. * @param action The kind of action: switching to a tool, content editing or copying. * @param toolName The tool name, for 'tool' actions. * @returns True when no listener prevented the action. */ requestPermissionAction(action: 'tool' | 'contentEdit' | 'copy', toolName?: string): boolean; /** * Asks listeners of beforePermissionAction whether an annotation action may proceed; a listener calls preventDefault() to deny it. * @param action 'annotation'. * @param target The annotation and the intent (select, fill, activate or edit). * @returns True when no listener prevented the action. */ requestPermissionAction(action: 'annotation', target: AnnotationPermissionTarget): boolean; /** * Switches the current tool: the old tool switchOut, the new tool switchIn, fires toolModeUpdated(new, old) * @param tool The tool to switch to, such as one from getTool. Nothing happens when it is already current or a beforePermissionAction listener prevents it. * @example * ```js * const { documentViewer, Tools } = instance.Core; * documentViewer.setToolMode(documentViewer.getTool(Tools.ToolNames.RECTANGLE)); * // Back to the default edit tool * documentViewer.setToolMode(documentViewer.getTool(Tools.ToolNames.EDIT)); * ``` */ setToolMode(tool: Tool): void; /** * Who handles touch gestures: native browser scrolling under the edit tool (pan-x pan-y, no browser zoom of the whole page), all other tools handle everything themselves (none): * the pan tool pans and pinch-zooms itself, and finger drags with drawing tools draw instead of scrolling */ private applyTouchAction; /** * AnnotationEdit by default * @returns The current tool. * @example * ```js * const { documentViewer } = instance.Core; * documentViewer.addEventListener('toolModeUpdated', (newTool, oldTool) => { * console.log(`${oldTool.name} -> ${newTool.name}`); * }); * console.log(documentViewer.getToolMode().name); // 'AnnotationEdit' by default * ``` */ getToolMode(): Tool; /** * Returns a tool by name. * @param name Tool name, such as a ToolNames value. * @returns The tool, or undefined when there is no tool with that name. * @example * ```js * const { documentViewer, Annotations, Tools } = instance.Core; * const rectangleTool = documentViewer.getTool(Tools.ToolNames.RECTANGLE); * rectangleTool.setStyles({ StrokeColor: new Annotations.Color(255, 0, 0), StrokeThickness: 3 }); * documentViewer.setToolMode(rectangleTool); * ``` */ getTool(name: string): Tool | undefined; /** * One tool instance per ToolNames entry * @returns An object mapping tool names to tools (the same object on every call). */ getToolModeMap(): Record; /** The history manager is created along with it, so annotations read on load also have "before change" properties */ private openURIHandler?; private submitFormHandler?; /** * Opens an address (for URI actions): given to the handler when set (prefixing https:// to invalid addresses), otherwise Core.openURI * @param url The address to open. * @param newWindow Whether to open it in a new window. */ openURI(url: string, newWindow?: boolean): void; /** * Sets the function that opens links from URI actions instead of the default. * @param handler Receives the address (https:// is added to invalid addresses) and whether to open a new window. */ setOpenURIHandler(handler: (url: string, newWindow?: boolean) => void): void; /** * Before a SubmitForm action submits: given to the handler when set to decide submit() or cancel(), otherwise submitted directly * @param url The submission address. * @param capability Optional callbacks notified of the outcome. * @param capability.resolve Called when the submission goes ahead. * @param capability.reject Called with the reason when the submit-form handler cancels it. */ submitForm(url: string, capability?: { /** Continues the submission. */ resolve: () => void; /** Cancels the submission. */ reject: (reason?: unknown) => void; }): void; /** * Sets the function that decides whether a submit-form action goes ahead. * @param handler Receives the address and an object whose submit() continues and cancel() cancels the submission. */ setSubmitFormHandler(handler: (url: string, options: SubmitFormOptions) => void): void; private callHandler; /** * Returns the annotation manager of this viewer, creating it on first use. * @returns The annotation manager. * @example * ```js * const { documentViewer } = instance.Core; * const annotationManager = documentViewer.getAnnotationManager(); * documentViewer.addEventListener('annotationsLoaded', () => { * console.log(annotationManager.getAnnotationsList().length); * }); * ``` */ getAnnotationManager(): AnnotationManager; /** * Returns the annotation undo and redo history of this viewer. * @returns The annotation history manager. */ getAnnotationHistoryManager(): AnnotationHistoryManager; /** * Returns the display mode manager of this viewer. * @returns The display mode manager. * @example * ```js * const { documentViewer, DisplayMode, DisplayModes } = instance.Core; * const displayModeManager = documentViewer.getDisplayModeManager(); * displayModeManager.setDisplayMode(new DisplayMode(documentViewer, DisplayModes.Facing)); * ``` */ getDisplayModeManager(): DisplayModeManager; /** * Returns the content edit manager of this viewer. * @returns The content edit manager. * @example * ```js * const { documentViewer } = instance.Core; * const contentEditManager = documentViewer.getContentEditManager(); * await contentEditManager.startContentEditMode(); * ``` */ getContentEditManager(): ContentEditManager; /** * Returns the content editing undo and redo history of this viewer. * @returns The content edit history manager. */ getContentEditHistoryManager(): ContentEditHistoryManager; /** * Returns the measurement manager of this viewer. * @returns The measurement manager. */ getMeasurementManager(): MeasurementManager; /** * With separations on, the density (0–100) of each ink at a point (page coordinates); empty when off. Asks the Worker, so it is asynchronous * @param pageNumber Page number (1-based). * @param x Horizontal position in page coordinates. * @param y Vertical position in page coordinates. * @returns A Promise that resolves to one entry per ink, or an empty array when separations are off or no document is loaded. */ getColorSeparationsAtPoint(pageNumber: number, x: number, y: number): Promise>; /** * Returns the text manager of this viewer (page text cache and selection), creating it on first use. * @returns The text manager. */ getTextManager(): TextManager; /** Selection changed: redraws the affected pages and fires textSelected(quads, text, pageNumber) (quads null when cleared) */ private selectionChanged; } /** * Core.Annotations.ControlHandle: base class of selection control handles, in plain JS. (x, y) is the handle center (page coordinates), width / height are screen pixels; * hit testing and drawing convert by the scale of pageMatrix (page → canvas), so the handle size does not change with zoom. */ /** Base class of selection control handles. The position is in page coordinates; the size is in screen pixels, so handles keep their size when zooming. */ declare class ControlHandle { x: number; y: number; width: number; height: number; /** * Creates a control handle. * @param x X of the handle center in page coordinates. * @param y Y of the handle center in page coordinates. * @param width Width in screen pixels; 8 by default. * @param height Height in screen pixels; 8 by default. */ constructor(x?: number, y?: number, width?: number, height?: number); /** (x, y) are page coordinates. */ testSelection(_annotation: Annotation$1, x: number, y: number, pageMatrix: Matrix): boolean; /** ctx is the annotation layer (device coordinates); the handle is drawn as a small solid square (7 screen pixels, #1460F3); override this method to change the drawing. */ draw(ctx: CanvasRenderingContext2D, _annotation: Annotation$1, pageMatrix: Matrix): void; } /** * Core.Annotations.SelectionModel: hit testing and control handles per annotation type, in plain JS. Handles are the corners and edge midpoints of the rectangle (when resizable; only the corners when keeping the ratio or rotated at an angle), * the same as the selection tool actually uses; (x, y) are page coordinates, pageMatrix is page → canvas. */ /** Hit testing, control handles and selection box drawing of a selected annotation. Each annotation class has its own selection model. */ declare class SelectionModel { readonly annotation: Annotation$1; private readonly modifiable; private readonly selected; readonly viewer: DocumentViewer | null; /** How many screen pixels the selection box is padded (per annotation); the default when unset (4 on all sides for boxed annotations and form widgets; 0 for vertex types and notes); the selection box and handles are padded together; pass undefined to restore the default. */ static setSelectionModelPaddingHandler(handler: ((annotation: Annotation$1) => number) | undefined): void; /** * Creates a selection model. * @param annotation The selected annotation. * @param modifiable Whether the annotation can be modified (handles are shown only then). * @param selected Whether the annotation is selected. * @param viewer The document viewer, used for zoom and page sizes. */ constructor(annotation: Annotation$1, modifiable: boolean, selected: boolean, viewer?: DocumentViewer | null); /** * Whether the annotation can be modified. * @returns True when modifiable. */ canModify(): boolean; /** * Whether the annotation is selected. * @returns True when selected. */ isSelected(): boolean; /** * Gets the resize handles of the bounding box (and the rotation handle when rotatable); none when the annotation cannot be modified or resized. * @returns The control handles. */ getControlHandles(): ControlHandle[]; /** * Finds the control handle at a point. * @param annotation The annotation. * @param x X in page coordinates. * @param y Y in page coordinates. * @param pageMatrix Transform from page coordinates to canvas coordinates. * @returns The handle at the point, or null when none. */ testControlHandles(annotation: Annotation$1, x: number, y: number, pageMatrix: Matrix): ControlHandle | null; /** * Whether a point hits the annotation (inside its bounding box, with a small tolerance). * @param annotation The annotation. * @param x X in page coordinates. * @param y Y in page coordinates. * @param pageMatrix Transform from page coordinates to canvas coordinates. * @returns True when the point hits the annotation. */ testSelection(annotation: Annotation$1, x: number, y: number, pageMatrix: Matrix): boolean; /** Solid selection box (#1460F3, padded like getControlHandles) plus handles (ctx is the annotation layer, device coordinates); override this method to change the drawing. */ draw(ctx: CanvasRenderingContext2D, annotation: Annotation$1, pageMatrix: Matrix): void; } /** * Display units, unit system and display format of measurement annotations (DisplayUnits / System / DisplayFormat, read-only here): * all derived from the measure dictionary (scale + precision), the same data that is written to /Measure in the file. */ /** Annotation.MeasurementUnits. */ declare const MEASUREMENT_UNITS: { /** Millimeters. */ readonly MM: "mm"; /** Centimeters. */ readonly CM: "cm"; /** Meters. */ readonly M: "m"; /** Kilometers. */ readonly KM: "km"; /** Inches. */ readonly IN: "in"; /** Feet. */ readonly FT: "ft"; /** Yards. */ readonly YD: "yd"; /** Miles. */ readonly MI: "mi"; /** Points (1/72 inch). */ readonly PT: "pt"; /** Inches written with a double prime. */ readonly DOUBLE_PRIME_IN: "in\""; /** Feet written with a prime. */ readonly PRIME_FT: "ft'"; /** Feet and inches. */ readonly FT_IN: "ft-in"; }; /** Annotation.MeasurementSystems */ declare const MEASUREMENT_SYSTEMS: { /** Metric units (mm, cm, m, km). */ readonly METRIC: "Metric"; /** Imperial units (in, ft, yd, mi). */ readonly IMPERIAL: "Imperial"; /** Typographic points. */ readonly TYPOGRAPHIC: "Typographic"; }; /** Annotation.MeasurementDisplayFormats */ declare const MEASUREMENT_DISPLAY_FORMATS: { /** Decimal number. */ readonly DECIMAL: "Decimal"; /** Fraction. */ readonly FRACTION: "Fraction"; /** Rounded value. */ readonly ROUND: "Round"; /** Truncated value. */ readonly TRUNCATE: "Truncate"; }; /** * Core.Annotations.Annotation: the annotation base class; property names start with a capital letter. * Changing a property only writes to the pending overlay and the view updates immediately; annotationManager.updateAnnotation(annot) commits it to the Worker. * Flags map to GetAnnotFlag / SetAnnotFlag; dates to Get/SetAnnotCreationDate; Icon to Get/SetAnnotDictName('Name'). */ /** Rich text style: character position → CSS style from there on (font-weight font-style text-decoration color font-family font-size). */ type RichTextStyle = Record>; interface AnnotationInit { PageNumber?: number; X?: number; Y?: number; Width?: number; Height?: number; [key: string]: unknown; } /** Listener arguments depend on the event. */ type AnnotationListener = (...args: any[]) => void; /** Base class of all annotations. Property names start with a capital letter; changes are applied to the view immediately and committed to the document with AnnotationManager.updateAnnotation. */ declare class Annotation$1 { /** Display units of measurement annotations (values of DisplayUnits, Annotation.MeasurementUnits). */ static readonly MeasurementUnits: { /** Millimeters. */ readonly MM: "mm"; /** Centimeters. */ readonly CM: "cm"; /** Meters. */ readonly M: "m"; /** Kilometers. */ readonly KM: "km"; /** Inches. */ readonly IN: "in"; /** Feet. */ readonly FT: "ft"; /** Yards. */ readonly YD: "yd"; /** Miles. */ readonly MI: "mi"; /** Points (1/72 inch). */ readonly PT: "pt"; /** Inches written with a double prime. */ readonly DOUBLE_PRIME_IN: "in\""; /** Feet written with a prime. */ readonly PRIME_FT: "ft'"; /** Feet and inches. */ readonly FT_IN: "ft-in"; }; /** Unit system of measurement annotations (values of System). */ static readonly MeasurementSystems: { /** Metric units (mm, cm, m, km). */ readonly METRIC: "Metric"; /** Imperial units (in, ft, yd, mi). */ readonly IMPERIAL: "Imperial"; /** Typographic points. */ readonly TYPOGRAPHIC: "Typographic"; }; /** Display format of measurement annotations (values of DisplayFormat). */ static readonly MeasurementDisplayFormats: { /** Decimal number. */ readonly DECIMAL: "Decimal"; /** Fraction. */ readonly FRACTION: "Fraction"; /** Rounded value. */ readonly ROUND: "Round"; /** Truncated value. */ readonly TRUNCATE: "Truncate"; }; /** Each subclass specifies its own selection model. */ /** * Selection model class (a prototype property; each class's default is set in selection/model-of.ts): when selected, new selectionModel(annotation, canModify, true, docViewer) * and its draw draws the selection box. Replace it with another class on a subclass prototype or a single annotation (for example one whose draw draws nothing); hit testing and handles still follow the built-in rules. */ selectionModel: typeof SelectionModel; /** XFDF element name of this annotation type (such as 'square'); 'annotation' in the base class. */ elementName: string; /** Unique annotation name (the /NM entry); used to look the annotation up and to link replies and groups. */ Id: string; /** Page the annotation is on (1-based). */ PageNumber: number; private previousPageNumber; /** Left edge of the bounding box in PDF points (page coordinates). */ X: number; /** Top edge of the bounding box in PDF points (page coordinates). */ Y: number; /** Width of the bounding box in PDF points. */ Width: number; /** Height of the bounding box in PDF points. */ Height: number; /** Rotation of the annotation in degrees, counterclockwise. */ Rotation: number; /** Author of the annotation (the /T entry). */ Author: string; /** Subject of the annotation; defaults to the subject of the annotation class. */ Subject: string; /** Stroke (border or line) color; defaults to black. */ StrokeColor: Color; /** Fill color; null means no fill (the engine clears the fill color on commit). A color written with opacity 0 is also treated as no fill. */ FillColor: Color | null; /** Stroke width in PDF points; defaults to 1. */ StrokeThickness: number; /** Opacity from 0 (transparent) to 1 (opaque); defaults to 1. */ Opacity: number; /** Icon name (the /Name entry), used by notes, stamps and file attachments. */ Icon: string; /** Whether the annotation cannot be moved by the user. */ NoMove: boolean; /** Whether the annotation cannot be resized by the user. */ NoResize: boolean; /** Whether the annotation does not rotate with the page (the /F NoRotate flag). */ NoRotate: boolean; /** Whether the annotation is not displayed (the /F NoView flag). */ NoView: boolean; /** Whether the annotation keeps its size regardless of zoom (the /F NoZoom flag). */ NoZoom: boolean; /** Whether the annotation cannot be deleted or have its properties changed (the /F Locked flag). */ Locked: boolean; /** Whether the contents of the annotation cannot be changed (the /F LockedContents flag). */ LockedContents: boolean; /** Whether the annotation cannot be interacted with (the /F ReadOnly flag). */ ReadOnly: boolean; /** Whether the annotation is hidden (the /F Hidden flag). */ Hidden: boolean; /** Whether the annotation is printed (the /F Print flag); defaults to true. */ Printable: boolean; /** Whether the annotation is shown in annotation lists; defaults to true. */ Listable: boolean; /** The /F Invisible bit (1): only meaningful for unknown annotation types; use Hidden to hide annotations. */ Invisible: boolean; /** The /F ToggleNoView bit (256). */ ToggleNoView: boolean; /** Cannot be deleted: AnnotationManager deleteAnnotation(s) skips it (memory only, not written to the file). */ NoDelete: boolean; /** Whether parts drawn outside the rectangle can be clicked too (hit testing here only uses the rectangle; currently only the value is stored). */ IsClickableOutsideRect: boolean; /** Whether the annotation was added since the last exportAnnotationCommand. */ IsAdded: boolean; /** Changed since the last exportAnnotationCommand. */ IsModified: boolean; /** Deleted since the last exportAnnotationCommand (set by deleteAnnotation(s), cleared when added to the document again). */ IsDeleted: boolean; /** Creation date, or null when unknown. */ DateCreated: Date | null; /** Last modification date, or null when unknown; updated by setModified. */ DateModified: Date | null; /** Id of the parent annotation of a reply or group. */ InReplyTo: string; /** 'group' means a group; otherwise a reply. */ ReplyType: string | null; /** Whether resizing keeps the width-to-height ratio. */ MaintainAspectRatio: boolean; /** Name of the tool that created it (written when a tool creates it, not saved to the PDF). */ ToolName: string; /** * Blend mode for drawing onto the page (canvas globalCompositeOperation name): 'multiply' multiplies with the page * (text highlights, ink with intent InkHighlight); normal blending by default. */ BlendMode: string | undefined; /** * Creates an annotation. * @param init Initial property values (such as PageNumber, X, Y, Width, Height) written onto the annotation. * @example * ```js * const { annotationManager, Annotations } = instance.Core; * // Positions and sizes are PDF points, measured from the top-left corner of the page; PageNumber starts at 1. * const annot = new Annotations.EllipseAnnotation({ PageNumber: 2, X: 72, Y: 72, Width: 144, Height: 72 }); * annot.StrokeColor = new Annotations.Color('#0066cc'); * annot.StrokeThickness = 2; * annot.Opacity = 0.8; * annot.Author = annotationManager.getCurrentUser(); * annot.setContents('Check this area'); * await annotationManager.addAnnotation(annot); * ``` */ constructor(init?: AnnotationInit); /** * The unrotated box as { x, y, width, height } (getUnrotatedDimensions, a runtime method not declared in the d.ts; same as getUnrotatedBox, * optionally given a rectangle in place of the annotation's own, derived by the annotation's Rotation). */ getUnrotatedDimensions(rect?: Rect): { /** Left edge in PDF points. */ x: number; /** Top edge in PDF points. */ y: number; /** Width in PDF points. */ width: number; /** Height in PDF points. */ height: number; }; /** * Internal: writes init onto the annotation. Fields declared in subclasses get their defaults after the base constructor and would overwrite init, * so subclasses that declare their own fields call this again in their own constructors. */ protected assign(init?: AnnotationInit): void; /** Internal: content (/Contents). */ protected contents: string; /** * Gets the bounding box. * @returns The bounding box in page coordinates (PDF points). */ getRect(): Rect; /** Geometric annotations (lines, ink, polygons, text markup) override it to move their points proportionally into the new rectangle. */ setRect(rect: Rect): void; /** Like setRect, but swaps reversed coordinates (setRect here already normalizes them, so both give the same result). */ setRectWithNormalization(rect: Rect): void; /** Resizes to the new rectangle (use it instead of setRect when internal properties must change too; here each class's setRect already carries points / paths along, so it is setRect). */ resize(rect: Rect): void; /** Moves to the new rectangle (same as resize). */ move(rect: Rect): void; /** Stroke color (alias of StrokeColor). */ get Color(): Color; set Color(color: Color); /** Whether the rotation handle is shown when selected (property form of hasRotationControlEnabled / enableRotationControl / disableRotationControl). */ get RotationControlEnabled(): boolean; set RotationControlEnabled(enabled: boolean); /** * Gets the left edge of the bounding box. * @returns X in PDF points. */ getX(): number; /** * Sets the left edge of the bounding box. * @param x X in PDF points. */ setX(x: number): void; /** * Gets the top edge of the bounding box. * @returns Y in PDF points. */ getY(): number; /** * Sets the top edge of the bounding box. * @param y Y in PDF points. */ setY(y: number): void; /** * Gets the width of the bounding box. * @returns Width in PDF points. */ getWidth(): number; /** * Sets the width of the bounding box. * @param width Width in PDF points. */ setWidth(width: number): void; /** * Gets the height of the bounding box. * @returns Height in PDF points. */ getHeight(): number; /** * Sets the height of the bounding box. * @param height Height in PDF points. */ setHeight(height: number): void; /** * Gets the text contents (/Contents) of the annotation. * @returns The contents; an empty string when none. * @example * ```js * const { annotationManager } = instance.Core; * annotationManager.getAnnotationsList() * .filter(annot => annot.getContents()) * .forEach(annot => console.log(`${annot.Author}: ${annot.getContents()}`)); * ``` */ getContents(): string; /** * Sets the text contents (/Contents) of the annotation. * @param text New contents. * @example * ```js * const { annotationManager } = instance.Core; * const annot = annotationManager.getAnnotationById('my-annotation-id'); * annot.setContents('Approved'); * await annotationManager.updateAnnotation(annot); * ``` */ setContents(text: string): void; /** Custom data (stored in the annotation dictionary and saved with the file); an empty string when the key is missing. */ /** Shows the rotation handle when selected (the AnnotationManager rotation option must be on too; only point-defined annotations can rotate, see rotatable in tools/annotation-select-tool.ts). */ hasRotationControlEnabled(): boolean; /** Shows the rotation handle when the annotation is selected. */ enableRotationControl(): void; /** Hides the rotation handle when the annotation is selected. */ disableRotationControl(): void; private rotationControl; /** * Gets a custom data value stored on the annotation. * @param key Custom data key. * @returns The value; an empty string when the key is missing. * @example * ```js * const { annotationManager } = instance.Core; * const pending = annotationManager.getAnnotationsList() * .filter(annot => annot.getCustomData('status') === 'pending'); * ``` */ getCustomData(key: string): string; /** * Commit with updateAnnotation after changing. * @example * ```js * const { annotationManager } = instance.Core; * const annot = annotationManager.getAnnotationById('my-annotation-id'); * annot.setCustomData('status', 'pending'); * annot.setCustomData('ticket', JSON.stringify({ id: 42 })); // values are strings * await annotationManager.updateAnnotation(annot); * ``` */ setCustomData(key: string, value: string): void; /** * Removes a custom data entry; commit with updateAnnotation afterwards. * @param key Custom data key. */ deleteCustomData(key: string): void; /** * Gets the replies to this annotation (linked annotations that are not group members). * @returns The reply annotations. */ getReplies(): Annotation$1[]; /** * Whether this annotation is a reply to another annotation (has InReplyTo and is not a group member). * @returns True for a reply. */ isReply(): boolean; /** * Links a reply to this annotation (no effect if already linked). Does not add it to the document. * @param reply The reply annotation. */ addReply(reply: Annotation$1): void; /** * Gets the annotations grouped under this one. * @returns The group members. */ getGroupedChildren(): Annotation$1[]; /** * Gets the page the annotation is on. * @returns The page number (1-based). */ getPageNumber(): number; /** * Sets the page the annotation is on. * @param n The page number (1-based). */ setPageNumber(n: number): void; /** * Previous interactive page transition, or the page at first query if none was recorded. * Plain PageNumber writes do not imply a pointer transition. Page remapping resets this baseline. * Viewer state only: not part of the PDF or annotation undo properties. */ getPreviousPageNumber(): number; /** Record the origin before a pointer page transition; null resets the first-query baseline. */ setPreviousPageNumber(pageNumber: number | null): void; /** Invisible when hidden (/F Hidden) or not viewed (NoView). */ isVisible(): boolean; /** * Whether this annotation is a member of a group (has InReplyTo and ReplyType 'group'). * @returns True for a group member. */ isGrouped(): boolean; /** Has this class name in its class chain (such as 'MarkupAnnotation', 'WidgetAnnotation'). */ /** The most specific class name (the last of types). */ getType(): string; /** * Whether the annotation class or one of its base classes has the given name (such as 'MarkupAnnotation' or 'WidgetAnnotation'). * @param type Class name to check. * @returns True when the name is in the class chain. */ isType(type: string): boolean; /** * Whether this is a form field widget; false in the base class. * @returns True for widget annotations. */ isWidget(): boolean; /** Internal annotation (not listed or exported); there are no such annotations here. */ isInternal(): boolean; /** Appears when printing: not hidden, printable, not a reply. */ isPrintVisible(): boolean; /** State of the latest review state reply (a hidden note with State); an empty string when none. */ getStatus(): string; /** Marks as changed; keepDate does not update the modification date. */ setModified(_keepAppearance?: boolean, _keepSerialized?: boolean, keepDate?: boolean): void; /** Recomputes the bounding box from the content; unchanged in the base class (geometric types compute from their points). */ adjustRect(): void; /** Margin by which the bounding box exceeds the geometry; 0 in the base class. */ getRectPadding(): number; /** Appearance resources are all ready (our appearances are in the Worker, so always true). */ resourcesLoaded(): boolean; /** * Whether this is a content editing placeholder; always false (content editing does not use annotations). * @returns Always false. */ isContentEditPlaceholder(): boolean; /** * Whether the annotation is in content editing focus mode; always false (content editing does not use annotations). * @param _contentEditManager Unused. * @returns Always false. */ isInContentEditFocusMode(_contentEditManager?: unknown): boolean; /** * Id of the content editing element this annotation represents; always undefined (content editing does not use annotations). * @returns Always undefined. */ getContentEditAnnotationId(): string | undefined; /** * Type of the content editing element this annotation represents; always undefined (content editing does not use annotations). * @returns Always undefined. */ getContentEditType(): string | undefined; private noZoomPoint; /** * Gets the point of the bounding box that stays fixed while zooming a NoZoom annotation. * @returns A copy of the point; x and y are fractions of the width and height (0 to 1), default { x: 0, y: 0 }. */ getNoZoomReferencePoint(): { /** Horizontal position as a fraction of the width (0 to 1). */ x: number; /** Vertical position as a fraction of the height (0 to 1). */ y: number; }; /** * Sets the point of the bounding box that stays fixed while zooming a NoZoom annotation. Values outside 0 to 1 are rejected with a warning. * @param point x and y as fractions of the width and height (0 to 1). * @param point.x Horizontal position as a fraction of the width (0 to 1). * @param point.y Vertical position as a fraction of the height (0 to 1). */ setNoZoomReferencePoint(point: { x: number; y: number; }): void; private richText; /** * Gets the rich text style of the contents. * @returns A copy of the style (character position to CSS style), or null when none. */ getRichTextStyle(): RichTextStyle | null; /** * Replaces the rich text style of the contents and marks the annotation as modified. * @param style Character position to CSS style, or null to remove the rich text style. */ setRichTextStyle(style: RichTextStyle | null): void; /** Applies style to the characters in [start, end) (break points are added at both ends of the range first, then segments are merged). */ updateRichTextStyle(style: Record, start?: number, end?: number): void; /** Position and rotation of the bounding box in the viewport. */ getViewportProperties(viewer: DocumentViewer): Readonly<{ /** Left edge in viewport units. */ x: number; /** Top edge in viewport units. */ y: number; /** Width in viewport units. */ width: number; /** Height in viewport units. */ height: number; /** Rotation in degrees relative to the display orientation. */ rotation: number; }>; /** Sets the bounding box from a viewport position, size (clamped into the page) and rotation. */ setViewportProperties(props: { /** Left edge in viewport units. */ x: number; /** Top edge in viewport units. */ y: number; /** Width in viewport units. */ width: number; /** Height in viewport units. */ height: number; /** Rotation in degrees relative to the display orientation; defaults to 0. */ rotation?: number; }, viewer: DocumentViewer): void; /** Point-defined annotations: viewport coordinates of each point; others log a warning and return an empty array. */ getViewportPath(viewer: DocumentViewer): ReadonlyArray>; /** * Point-defined annotations: sets all points from viewport coordinates (points are fitted into the page). Other annotations log a warning. * @param points New points in viewport coordinates. * @param viewer The document viewer used to convert the coordinates. */ setViewportPath(points: Array<{ /** X in viewport units. */ x: number; /** Y in viewport units. */ y: number; }>, viewer: DocumentViewer): void; /** * Point-defined annotations: gets one point in viewport coordinates. * @param index Zero-based point index. * @param viewer The document viewer used to convert the coordinates. * @returns The point, or null when the annotation is not point-defined or the index is out of range. */ getViewportPathPoint(index: number, viewer: DocumentViewer): Readonly<{ /** X in viewport units. */ x: number; /** Y in viewport units. */ y: number; }> | null; /** * Point-defined annotations: moves one point to a position in viewport coordinates. Invalid indexes and other annotations log a warning. * @param index Zero-based point index. * @param point New position in viewport coordinates. * @param point.x X in viewport units. * @param point.y Y in viewport units. * @param viewer The document viewer used to convert the coordinates. */ setViewportPathPoint(index: number, point: { x: number; y: number; }, viewer: DocumentViewer): void; /** Vector drawing on the main thread; types that need appearance bitmaps are handled by AppearanceManager. */ /** * Draws onto ctx with the page coordinate transform already set (unrotated page space, pt). The base class draws nothing: * types that need appearance bitmaps are drawn from AppearanceManager's bitmaps. */ draw(_ctx: CanvasRenderingContext2D, _pageMatrix: Matrix): void; /** Adds a listener (annotations are EventHandlers; form widgets fire focus / blur of WidgetAnnotation.Events). */ addEventListener(name: string, fn: AnnotationListener, options?: { /** Remove the listener after it is called once. */ once?: boolean; }): void; /** Removes a listener; without fn, removes all listeners of this event. */ removeEventListener(name: string, fn?: AnnotationListener): void; /** Removes all event listeners of this annotation. */ removeAllEventListeners(): void; /** Fires an event with arguments spread by position. */ trigger(name: string, args?: unknown[]): void; /** Like trigger, awaiting the Promise returned by each listener in turn. */ triggerAsync(name: string, args?: unknown[]): Promise; /** The XFDF element of this annotation (such as ); asynchronous (exported by the Worker); the annotation must be added to the document first. */ serialize(): Promise; /** Changes this annotation from an XFDF element (or a whole XFDF containing it): the element's name is replaced with this annotation's Id and imported, updating in place. */ deserialize(xfdf: string): Promise; } /** Stores actions by trigger name ('U' mouse up, 'D' mouse down, ...) and runs them in order on trigger: GoTo navigates, URI opens, Named navigates or prints, Hide shows or hides fields, ResetForm resets. GoToR is not executed. */ declare class Dispatcher { private readonly actions; private readonly documentViewer?; /** * Creates a dispatcher. * @param init Optional initial state. * @param init.actions Initial actions keyed by trigger name. * @param init.documentViewer Viewer used when `trigger` is called without one. */ constructor(init?: { actions?: Record; documentViewer?: DocumentViewer; }); /** * Appends an action to the list run for a trigger. * @param trigger Trigger name, such as 'U' (mouse up) or 'D' (mouse down). * @param action The action to add. */ addAction(trigger: string, action: Action): void; /** * Returns all actions keyed by trigger name. * @returns The live map of trigger names to their action lists. */ getActions(): Record; /** * Runs every action registered for a trigger, in order. Does nothing when no viewer is available. * @param triggerName Trigger name, such as 'U' or 'D'. * @param target The annotation that fired the trigger, or null. * @param event The originating DOM event, or null. * @param viewer Viewer to run the actions against; defaults to the viewer given to the constructor. */ trigger(triggerName: string, target: Annotation$1 | null, event: Event | null, viewer?: DocumentViewer): void; } /** Engine GetDestination / SetDestination. */ /** Go-to action: navigates to a page, or to a position on a page, in the current document. */ declare class GoTo extends Action { /** The destination class, exposed so callers can create `new Actions.GoTo.Dest(...)`. */ static Dest: typeof Dest; /** Action type name, always 'GoTo'. */ elementName: string; /** The target destination (1-based page number, fit mode, position and zoom). */ dest: Dest; /** * Creates a go-to action. * @param init Optional initial values. * @param init.dest Initial destination; defaults to page 1 with fit mode 'Fit'. */ constructor(init?: { dest?: DestInit; }); /** Goes to the target page; when a position is given, scrolls that point to the top-left of the viewport. */ onTriggered(_target: Annotation$1 | null, _event: Event | null, viewer: DocumentViewer): void; } /** * Core.Actions.GoToR: opens a location in another PDF (dest, filename, newWindow). * The engine only knows the type; the Worker reads and writes the target file and location from the file bytes (file-actions.ts). Triggering only fires an event and never opens the other file. * dest page numbers start at 1; coordinates are the target file's raw PDF coordinates. */ interface GoToROptions { dest?: DestInit; filename?: string; newWindow?: boolean; } /** Remote go-to action: opens a location in another PDF file. Triggering it does not open the other file. */ declare class GoToR extends Action { /** Action type name, always 'GoToR'. */ elementName: string; private readonly target; private readonly file; private readonly window; /** * Creates a remote go-to action. * @param options Target location, file name and whether to open a new window. */ constructor(options?: GoToROptions); /** Target location in the other file. Page numbers start at 1; coordinates are that file's PDF coordinates. */ get dest(): Dest; /** Path or name of the target PDF file; undefined when not set. */ get filename(): string | undefined; /** Whether the target file should open in a new window; undefined when not specified. */ get newWindow(): boolean | undefined; } /** * Core.Actions.Hide: shows or hides fields (fields are looked up by name; hidden when hide is true, shown otherwise; missing fields log a warning). * The engine cannot read the target fields or /H, so they are filled from the /A dictionary when the file is read (worker/document/file-actions.ts). */ /** Hide action: shows or hides form fields by name. */ declare class Hide extends Action { /** Action type name, always 'Hide'. */ elementName: string; private readonly targets; private readonly hiding; /** * Creates a hide action. * @param init Optional initial values. * @param init.fields Names of the target fields. * @param init.hide true to hide the fields, false to show them. Defaults to true. */ constructor(init?: { fields?: string[]; hide?: boolean; }); /** Names of the target fields. */ get fields(): string[]; /** true hides, false shows. */ get hide(): boolean; onTriggered(_target: Annotation$1 | null, _event: Event | null, viewer: DocumentViewer): void; } /** * Core.Actions.JavaScript: the script of an action (javascript). There is no script engine (form calculation and * format scripts are not supported), so scripts are never executed. Scripts are read from and written to the file's /JS (worker/document/file-actions.ts). */ /** JavaScript action. The script is kept and saved with the document but is never executed. */ declare class JavaScript extends Action { /** Action type name, always 'JavaScript'. */ elementName: string; private script; /** * Creates a JavaScript action. * @param init Optional initial values. * @param init.javascript The script source. */ constructor(init?: { javascript?: string; }); /** * Replaces the script when a string is given; other values are ignored. * @param init Values to apply. * @param init.javascript The new script source. */ set(init?: { javascript?: string; }): void; /** The script source; an empty string when none is set. */ get javascript(): string; onTriggered(_target: Annotation$1 | null, _event: Event | null, _viewer: DocumentViewer): void; } /** * Named action: the four page-navigation names run directly; Print goes to FieldManager.print (the handler set with setPrintHandler); others log a warning. * Names on buttons are read by the engine (GetBtnActionNamedAction); names on links are filled from the file (worker/document/file-actions.ts). */ /** Name of a named action. 'NextPage', 'PrevPage', 'FirstPage', 'LastPage' and 'Print' are executed; other names only log a warning. */ type NamedActionName = 'NextPage' | 'PrevPage' | 'FirstPage' | 'LastPage' | 'Print' | (string & {}); /** Named action: page navigation or printing identified by a predefined name. */ declare class Named extends Action { /** Action type name, always 'Named'. */ elementName: string; /** The action name, such as 'NextPage' or 'Print'; an empty string when not set. */ action: NamedActionName; /** * Creates a named action. * @param init Optional initial values. * @param init.action The action name. */ constructor(init?: { action?: NamedActionName; }); onTriggered(target: Annotation$1 | null, event: Event | null, viewer: DocumentViewer): void; } /** * Core.Actions.ResetForm: resets the form. With fields, only those fields (and their children) are reset; with exclude, all other fields are reset; * with neither, everything is reset. Missing fields log a warning. The field list is read from and written to the file's /Fields and /Flags (worker/document/file-actions.ts). */ /** Reset-form action: resets all form fields, the listed fields, or all fields except the listed ones. */ declare class ResetForm extends Action { /** Action type name, always 'ResetForm'. */ elementName: string; private readonly names; private readonly excluding; /** * Creates a reset-form action. * @param init Optional initial values. * @param init.fields A field name or list of field names; omit to reset every field. * @param init.exclude When true, the listed fields are kept and all other fields are reset. */ constructor(init?: { fields?: string[] | string; exclude?: boolean; }); /** Names of the fields to reset (fields to keep when exclude is set); null when not given. */ get fields(): string[] | null; /** Whether `fields` lists fields to keep rather than fields to reset. */ get exclude(): boolean; onTriggered(_target: Annotation$1 | null, _event: Event | null, viewer: DocumentViewer): void; } /** * Core.Actions.SubmitForm: submits the form. Field values are written as XFDF or an HTML form according to format (fdf is not supported and falls back to HTML). * AnnotationManager.setBeforeSubmitFormActionCallback is asked first (returning false cancels), then DocumentViewer.setSubmitFormHandler * (submitted directly when not set), then the data is POSTed to url and the server response is passed to setSubmitFormActionCallback. * The address, fields and flags are read from and written to the file's /F, /Fields and /Flags (worker/document/file-actions.ts). */ /** Data format used when submitting a form. 'fdf' is not supported and falls back to 'html'. */ type SubmitFormFormat = 'xfdf' | 'html' | 'fdf'; /** Initial values for a submit-form action. */ interface SubmitFormInit { /** Address the form data is sent to. */ url?: string; /** Names of the fields to submit (or to leave out when `exclude` is true); empty submits all fields. */ fields?: string[]; /** Data format; defaults to 'xfdf'. */ format?: SubmitFormFormat | (string & {}); /** Whether fields without a value are submitted. Defaults to false. */ includeEmpty?: boolean; /** Flag names from SUBMIT_FORM_FLAGS, or the raw flag bits. */ flags?: string | string[] | number; /** HTTP method name. Defaults to 'POST'. */ method?: string; /** Whether `fields` lists fields to leave out. Defaults to false. */ exclude?: boolean; } /** Submit-form action: sends form field values to a URL as XFDF or as an HTML form. */ declare class SubmitForm extends Action { /** Action type name, always 'SubmitForm'. */ elementName: string; private address; private names; private kind; private empty; private verb; private excluding; private readonly options; /** * Creates a submit-form action. * @param init Optional initial values. */ constructor(init?: SubmitFormInit); /** * Applies the given values; omitted or falsy values leave the current ones unchanged. * @param init Values to apply. */ set(init?: SubmitFormInit): void; /** Address the form data is sent to; an empty string when not set. */ get url(): string; /** Names of the listed fields; empty when all fields are submitted. */ get fields(): string[]; /** Data format, such as 'xfdf' (default) or 'html'. */ get format(): string; /** Whether fields without a value are submitted. */ get includeEmpty(): boolean; /** HTTP method name recorded on the action, such as 'POST' (default) or 'GET'. */ get method(): string; /** Whether `fields` lists fields to leave out rather than fields to submit. */ get exclude(): boolean; /** The remaining submit flags (names from SUBMIT_FORM_FLAGS). Assign a flag name, a list of names (each is turned on) or the raw bits. */ get flags(): WidgetFlags; set flags(value: string | string[] | number); onTriggered(_target: Annotation$1 | null, _event: Event | null, viewer: DocumentViewer): void; } /** On execution, DocumentViewer.openURI opens the link in a new window (override with setOpenURIHandler). */ /** URI action: opens a link in a new window through DocumentViewer.openURI. */ declare class URI extends Action { /** Action type name, always 'URI'. */ elementName: string; /** The link to open; an empty string when not set. */ uri: string; /** * Creates a URI action. * @param init Optional initial values. * @param init.uri The link to open. */ constructor(init?: { uri?: string; }); onTriggered(_target: Annotation$1 | null, _event: Event | null, viewer: DocumentViewer): void; } /** * Core.Actions: GoTo (with GoTo.Dest) / GoToR / URI / Named / JavaScript / ResetForm / SubmitForm / Hide / Dispatcher. * The Action base class is internal and not exported. JavaScript is not executed (there is no script engine). */ /** * Arc annotation: an arc through three points (start, control point, end), set with setPath / getPath. * Arc measurements drawn by ArcMeasurementCreateTool are also ArcAnnotation objects (with Measure set); in the PDF they are stored as a three-point ink annotation with measurement data. */ declare class ArcAnnotation extends IPathAnnotation { /** Display units (read-only, derived from the scale; feet-inches are ft' and in"); an empty array when not a measurement annotation (DisplayUnits). */ get DisplayUnits(): string[]; /** Unit system Metric / Imperial / Typographic (read-only); an empty string when not a measurement annotation. */ get System(): string; /** Display format Decimal / Fraction (read-only, depends on precision and unit); an empty string when not a measurement annotation. */ get DisplayFormat(): string; /** XFDF element name of the annotation: 'arc'. */ elementName: string; /** Result text style of arc measurements (changed in the style panel; an empty string / null means unchanged: the engine default Helvetica 9 black); see MeasureTextStyle in utils/measurement-caption.ts. */ Font: string; /** Font size of the measurement result text in points, as a string; an empty string keeps the default. */ FontSize: string; /** Color of the measurement result text; null keeps the default. */ TextColor: Color | null; /** * Creates an arc annotation. * @param init Initial property values. */ constructor(init?: AnnotationInit); /** * Gets which values the result text of an arc measurement shows: `radius`, `arcLength` and `angle` (by default only the angle). * @returns The display options, or `undefined` when the annotation is not an arc measurement. */ getMeasurementDisplayOptions(): MeasurementDisplayOptions | undefined; /** * Sets which values the result text of an arc measurement shows; only the given keys change. Call `annotationManager.updateAnnotation` afterwards. * @param options Any of `radius`, `arcLength` and `angle`. */ setMeasurementDisplayOptions(options: MeasurementDisplayOptions): void; private metrics; /** Radius of the arc (page units, pt, read-only; returned as a number). */ get Radius(): number; /** Arc length (pt, read-only). */ get Length(): number; /** Swept angle (degrees, read-only). */ get Angle(): number; /** Annotation type name (read-only). */ get Type(): string; /** Border style: 'solid' (default) or 'dash' (see border-style.ts). */ get Style(): string; set Style(style: string); /** Dash lengths (pt), comma separated, '3' by default; an array is joined into a string. */ get Dashes(): string | null; set Dashes(dashes: string | number[] | null); /** The arc through the three points (start, a point on the arc, end). */ draw(ctx: CanvasRenderingContext2D, pageMatrix: Matrix): void; /** The bounding box is that of the arc itself (not of the three points), padded by the line width. */ adjustRect(): void; } /** Core.Annotations.Border: maps to the engine's GetAnnotBorderStyle / SetAnnotBorderStyle / GetAnnotBorderWidth. */ type BorderStyle = 'solid' | 'dash' | 'beveled' | 'inset' | 'underline'; /** Border of an annotation: color, width, style and dash pattern. */ declare class Border { /** Border color; black by default. */ color: Color; /** Border width in PDF points; 1 by default. */ width: number; /** Border style; 'solid' by default. */ style: BorderStyle; /** Dash pattern in PDF points (used with the 'dash' style). */ dashes: number[]; /** * Creates a border. * @param init Initial color, width, style and dashes. */ constructor(init?: Partial>); } /** Core.Annotations.CanvasHelper: drawing helpers for custom annotation draw(), using the current strokeStyle / fillStyle / lineWidth of ctx, in plain JS. */ /** Drawing helpers for custom annotation drawing; they use the current stroke style, fill style and line width of the context. */ declare class CanvasHelper { readonly ctx: CanvasRenderingContext2D; /** * Creates a helper drawing into a canvas context. * @param ctx The canvas context to draw into. */ constructor(ctx: CanvasRenderingContext2D); /** Clears the whole canvas (unaffected by the current transform). */ clear(): void; /** * Strokes a line between two points. * @param from Start point. * @param to End point. */ drawLine(from: Point, to: Point): void; /** * Strokes a line between two points given by coordinates. * @param x1 X of the start point. * @param y1 Y of the start point. * @param x2 X of the end point. * @param y2 Y of the end point. */ drawLineXY(x1: number, y1: number, x2: number, y2: number): void; /** * Strokes a rectangle (reversed corners are normalized). * @param rect The rectangle. */ drawRectangle(rect: Rect): void; /** * Strokes a circle. * @param center Center point. * @param radius Radius. */ drawCircle(center: Point, radius: number): void; /** * Strokes a circle given by center coordinates. * @param x X of the center. * @param y Y of the center. * @param radius Radius. */ drawCircleXY(x: number, y: number, radius: number): void; /** * Strokes a polygon or polyline through the points; does nothing without points. * @param points The vertices. * @param closed Whether to close the path back to the first point; defaults to true. */ drawPolygon(points: Point[], closed?: boolean): void; /** Cloudy edge: semicircular arcs along each edge of the closed polygon, with a diameter of about intensity × 10. */ drawClouds(points: Point[], intensity: number): void; /** * Fills text at a position. * @param text The text. * @param x X of the text baseline start. * @param y Y of the text baseline. * @param font Font to use (name and size in pixels); the current context font when omitted. */ drawText(text: string, x: number, y: number, font?: Font): void; /** * Measures text. * @param text The text. * @param font Font to use (name and size in pixels); the current context font when omitted. * @returns Width and height of the text in pixels. */ measureText(text: string, font?: Font): { /** Width in pixels. */ width: number; /** Height in pixels (ascent plus descent). */ height: number; }; } declare class CaretAnnotation extends MarkupAnnotation { elementName: string; } /** * Custom hooks on Core.Annotations: replace draw / serialize / deserialize on a class prototype and draw of control handles per class; * the last handler argument is { annotation (or controlHandle), originalXxx }; restoreXxx puts the original back. * - Drawing: classes with a custom draw are drawn by the main thread with draw instead of the engine appearance bitmap; with generateAppearance (on by default) the custom drawing is rendered before saving onto * a canvas at least 2× and written as the appearance in the file (AnnotationManager writes it through the custom appearance /AP) * - Serialization: our XFDF is exported by the Worker; exportAnnotations and serialize pass each element (a string) to the handler to change; * deserialization: after import the handler is called on the imported annotations (elements are strings; originalDeserialize does nothing since the engine already imported them) */ type Ctor = abstract new (...args: never[]) => T; type DrawHandler = (ctx: CanvasRenderingContext2D, pageMatrix: Matrix, rotation: number | undefined, options: { annotation: Annotation$1; originalDraw: (ctx: CanvasRenderingContext2D, pageMatrix: Matrix, rotation?: number) => void; }) => void; type SerializeHandler = (element: string, pageMatrix: Matrix | undefined, options: { annotation: Annotation$1; originalSerialize: () => string; }) => string; type DeserializeHandler = (element: string, pageMatrix: Matrix | undefined, options: { annotation: Annotation$1; originalDeserialize: () => void; }) => void; type HandleDrawHandler = (ctx: CanvasRenderingContext2D, annotation: Annotation$1, pageMatrix: Matrix, options: { controlHandle: ControlHandle; originalDraw: (ctx: CanvasRenderingContext2D, annotation: Annotation$1, pageMatrix: Matrix) => void; }) => void; /** * Replaces the drawing of an annotation class. Annotations of the class are then drawn by the handler instead of their appearance, and by default the custom drawing is written as the appearance when saving. * @param cls The annotation class. * @param handler Draws the annotation; receives the context, the page matrix, the rotation and an object with the annotation and its original draw function. null restores the original drawing. * @param options Appearance options. * @param options.generateAppearance Whether to write the custom drawing as the appearance when saving. * @param options.canvasMultiplier Resolution multiplier of the appearance canvas. */ declare function setCustomDrawHandler(cls: Ctor, handler: DrawHandler | null, options?: { /** Write the custom drawing as the appearance when saving; true by default. */ generateAppearance?: boolean; /** Resolution multiplier of the canvas the appearance is rendered on; the runtime canvas multiplier by default. */ canvasMultiplier?: number; }): void; /** * Restores the original drawing of an annotation class. * @param cls The annotation class. */ declare function restoreDraw(cls: Ctor): void; /** * Sets a handler that changes the exported XFDF element of each annotation of a class. * @param cls The annotation class. * @param handler Receives the XFDF element string, the page matrix and an object with the annotation and its original serialize function; returns the element to export. null removes the handler. */ declare function setCustomSerializeHandler(cls: Ctor, handler: SerializeHandler | null): void; /** * Removes the custom serialize handler of an annotation class. * @param cls The annotation class. */ declare function restoreSerialize(cls: Ctor): void; /** * Sets a handler called on each imported annotation of a class with its XFDF element. * @param cls The annotation class. * @param handler Receives the XFDF element string, the page matrix and an object with the annotation and its original deserialize function. null removes the handler. */ declare function setCustomDeserializeHandler(cls: Ctor, handler: DeserializeHandler | null): void; /** * Removes the custom deserialize handler of an annotation class. * @param cls The annotation class. */ declare function restoreDeserialize(cls: Ctor): void; /** * Replaces the drawing of a control handle class. * @param cls The control handle class. * @param handler Draws the handle; receives the context, the annotation, the page matrix and an object with the control handle and its original draw function. null restores the original drawing. */ declare function setCustomControlHandleDrawHandler(cls: Ctor, handler: HandleDrawHandler | null): void; declare class EllipseAnnotation extends MarkupAnnotation { /** Display units (read-only, derived from the scale; feet-inches are ft' and in"); an empty array when not a measurement annotation (DisplayUnits). */ get DisplayUnits(): string[]; /** Unit system Metric / Imperial / Typographic (read-only); an empty string when not a measurement annotation. */ get System(): string; /** Display format Decimal / Fraction (read-only, depends on precision and unit); an empty string when not a measurement annotation. */ get DisplayFormat(): string; elementName: string; /** * Result text style of area measurements (Font / FontSize / TextColor of the style panel): stored in captionStyle of the result text options (kept in memory only); * without measurement, reads give defaults and writes are ignored; when the font size is unset, the automatically computed size is read. */ get Font(): string; set Font(font: string); /** Font size of the measurement result text with unit, such as '9pt'; setting a positive size fixes the size of the result text. */ get FontSize(): string; set FontSize(size: string); /** Color of the measurement result text; setting it changes the result text style. */ get TextColor(): Color; set TextColor(color: { /** Red, 0 to 255. */ R: number; /** Green, 0 to 255. */ G: number; /** Blue, 0 to 255. */ B: number; } | null); /** Width and height of the bounding box (for the automatic font size). */ private captionSize; private setCaptionStyle; /** Border style: 'solid' (default) or 'dash' (see border-style.ts). */ get Style(): string; set Style(style: string); /** Dash lengths (pt), comma separated, '3' by default; an array is joined into a string. */ get Dashes(): string | null; set Dashes(dashes: string | number[] | null); /** Rotates by radians around center (the center by default; clockwise is positive): the unrotated box stays, the rectangle becomes the rotated bounding box, and Rotation follows. */ rotate(radians: number, center?: { /** X of the rotation center in PDF points. */ x: number; /** Y of the rotation center in PDF points. */ y: number; }): void; draw(ctx: CanvasRenderingContext2D, pageMatrix: Matrix): void; /** Area (squared real units); undefined when not a measurement annotation or the scale is invalid. */ getMeasurementValue(): number | undefined; /** "A = 12.57 sq in" (written like the engine's polygon area; feet-inches use square feet). */ getMeasurementTextWithScaleAndUnits(): string; /** * Result text written to the content and drawn in the middle: the semi-axes are rounded by precision before computing the area, and the value is followed immediately by the unit and ² ('12.3cm²'); * feet-inches use square feet. The format of getMeasurementTextWithScaleAndUnits is unchanged. */ getMeasurementContents(): string; /** Which items the result text of circles (with Measure) shows: radius, perimeter, area; only the area by default; undefined when not a measurement. */ getMeasurementDisplayOptions(): MeasurementDisplayOptions | undefined; /** Changes only the given keys (inapplicable ones are ignored); then updateAnnotation commits and the result text is rewritten. */ setMeasurementDisplayOptions(options: MeasurementDisplayOptions): void; /** Size, scale and display options the content was last measured for. */ private measuredFor; private measureSignature; /** Recomputes the result text when the size, scale or display options changed and writes it to the content (adjustContents); the scale goes to /Measure with the other properties. */ adjustContents(): void; /** Result text options of area measurements (with Measure); undefined when not a measurement. */ getMeasurementCaptionOptions(): MeasurementCaptionOptions | undefined; /** * Changes the result text options of an area measurement (merged into the current options). Does nothing when not a measurement. * @param options The options to change. */ setMeasurementCaptionOptions(options: MeasurementCaptionOptionsInput): void; } /** * Core.Annotations.FileAttachmentAnnotation: CreateAnnot(kFileAttachment); the icon is /Name (Icon: PushPin / Paperclip / Graph / Tag). * Read: there is no dedicated export of attachment contents, so they are read from this annotation's XFDF ( is decoded hex, the file name is in the file attribute). * Write: setFileData records the file, committed with addAnnotation / updateAnnotation; the engine cannot write /FS, so the Worker appends an incremental update to the saved bytes that attaches the file, then reopens. * Appearance: not generated by the engine; the same incremental update writes /AP from the icon and color (utils/attachment-icons.ts), and the main thread draws vectors with the same geometry meanwhile. * Attachments read from the file: the file name and contents come from the exported XFDF, the MIME type (/Subtype of the embedded file stream, absent from XFDF) is read by the Worker from the file bytes, all when getFileData is called. * Note: attachments cannot be added to documents that were encrypted when opened or have a password set. */ interface FileAttachmentMetadata { mimeType: string | null; filename: string | null; fileName: string | null; } declare class FileAttachmentAnnotation extends MarkupAnnotation { elementName: string; /** * Creates a file attachment annotation (PushPin icon, 20 x 20 pt by default). * @param init Initial property values. */ constructor(init?: AnnotationInit); /** Icon (same geometry as the appearance written to the file); drawn before the appearance bitmap arrives and during drag previews. */ draw(ctx: CanvasRenderingContext2D, _pageMatrix: Matrix): void; private filename; private mimeType; /** File name and MIME type (attachments read from the file have a file name only after getFileData / getFullFileMetadata). */ getFileMetadata(): FileAttachmentMetadata; /** * Gets the file name of the attachment. * @returns The file name, or null when unknown. */ getFilename(): string | null; /** * Sets the file name of the attachment. * @param name The file name. */ setFilename(name: string): void; /** * Gets the contents of the attached file. Throws when there is no embedded file. * @returns The file contents (typed with the MIME type when known). */ getFileData(): Promise; /** File contents, file name and MIME type (file name without the path). */ getFullFileMetadata(): Promise<{ /** This annotation. */ annotation: FileAttachmentAnnotation; /** File contents. */ fileData: Blob; /** File name without the path. */ filename: string; /** Same as filename. */ fileName: string; /** MIME type, or null when unknown. */ mimeType: string | null; }>; /** Sets the attachment file: it is written to the document by a later addAnnotation (or updateAnnotation when already in the document). */ setFileData(data: ArrayBuffer | ArrayBufferView | Blob, mimeType?: string, filename?: string): Promise; } /** Core.Annotations.FileAttachmentUtils: attachment utility functions (static at runtime and declared as instance methods in the d.ts; both ways work). */ declare class FileAttachmentUtils { /** Decompresses FlateDecode data (a hex string) into a Blob; mimeType, when given, becomes the Blob type. Throws when the data is corrupt or the environment cannot decompress. */ static decompressWithFlateDecode(fileData: string, mimeType?: string): Promise; /** * Decompresses FlateDecode data (same as the static method). * @param fileData The compressed data as a hex string. * @param mimeType MIME type of the resulting Blob. * @returns The decompressed data. */ decompressWithFlateDecode(fileData: string, mimeType?: string): Promise; } /** Core.Annotations.Forms: Field / FieldManager (EmbeddedJS is not supported). */ /** * Core.Annotations.FreeTextAnnotation: CreateAnnot(kFreetext); GetFreeTextFont / SetFreetextCallout / SetFreetextLineEnding / SetFreetextRectDiff. * With a callout (Intent FreeTextCallout): the annotation rectangle encloses the text box and the callout, getPadding is the text box padding within the rectangle (/RD), * the path is the callout points (start → knee → end, /CL), and getStartStyle is the line ending at the start (/LE). */ type FreeTextIntent = 'FreeText' | 'FreeTextCallout' | 'FreeTextTypewriter'; type FreeTextAutoSize = 'none' | 'auto' | 'fixedWidth' | 'fixedHeight'; declare class FreeTextAnnotation extends IPathAnnotation { /** Values of the Intent property. */ static readonly Intent: { /** Plain text box. */ readonly FreeText: "FreeText"; /** Text box with a callout line. */ readonly FreeTextCallout: "FreeTextCallout"; /** Typewriter text. */ readonly FreeTextTypewriter: "FreeTextTypewriter"; }; /** Values of the auto size type (see setAutoSizeType). */ static readonly AutoSizeTypes: { /** No auto sizing. */ readonly NONE: "none"; /** Width and height follow the text. */ readonly AUTO: "auto"; /** Width is fixed; height follows the text. */ readonly FIXED_WIDTH: "fixedWidth"; /** Height is fixed; width follows the text. */ readonly FIXED_HEIGHT: "fixedHeight"; }; elementName: string; /** * Creates a free text annotation. With Intent 'FreeTextCallout' and no Subject, the subject defaults to the callout subject. * @param init Initial property values. * @example * ```js * const { annotationManager, Annotations } = instance.Core; * const freeText = new Annotations.FreeTextAnnotation({ PageNumber: 1, X: 50, Y: 50, Width: 200, Height: 40 }); * freeText.setContents('Reviewed'); * freeText.FontSize = '16pt'; * freeText.TextColor = new Annotations.Color(0, 0, 255); * freeText.TextAlign = 'center'; * freeText.StrokeThickness = 0; // no border * await annotationManager.addAnnotation(freeText); * ``` */ constructor(init?: AnnotationInit); /** Font name of the text; 'Helvetica' by default. */ Font: string; /** Font size with unit, such as '12pt' (the default); '0pt' means the size is fitted to the text box. */ FontSize: string; /** Horizontal text alignment; 'left' by default. */ TextAlign: 'left' | 'center' | 'right'; /** Text color; black by default. */ TextColor: Color; /** Kind of free text: plain text box, callout (with a leader line) or typewriter. */ Intent: FreeTextIntent; /** Line ending at the callout start (/LE). */ StartStyle: LineEndType; /** Cloudy border intensity (SetBorderEffect; 0 is not cloudy). */ private cloudIntensity; /** Cloud intensity, integers only (truncated on set; negative and NaN become 0); see normalizeCloudIntensity. */ get CloudIntensity(): number; set CloudIntensity(intensity: number); /** Cloud intensity (Intensity, same as CloudIntensity). */ get Intensity(): number; set Intensity(intensity: number); /** Border style: 'solid' (default), 'dash'; 'cloudy' when the cloud intensity is above 0 (see border-style.ts). Setting cloudy without intensity uses the default 2; setting anything else removes the cloud. */ get Style(): string; set Style(style: string); /** Dash lengths (pt), comma separated, '3' by default; an array is joined into a string. */ get Dashes(): string | null; set Dashes(dashes: string | number[] | null); /** * Gets the cloudy border intensity. * @returns The intensity; 0 means no cloudy border. */ getCloudIntensity(): number; /** * Sets the cloudy border intensity and marks the annotation as modified. * @param intensity The intensity (integers only; 0 means no cloudy border). */ setCloudIntensity(intensity: number): void; /** * Gets the date format of a date text annotation, stored in the custom data key `compdfkit_freetext_date`. * @returns The format, such as `'MM/DD/YYYY'`, or an empty string when the annotation is not a date text. */ getDateFormat(): string; /** * Sets the date format of a date text annotation. An empty string removes it. * @param format The format, such as `'MM/DD/YYYY'`. */ setDateFormat(format: string): void; /** Font size follows the text box (FontSize '0pt'). */ isAutoSizeFont(): boolean; /** * Whether an auto size type other than 'none' is set. * @returns True when auto sizing is set. */ isAutoSized(): boolean; /** The font size actually used (with unit): when auto-fitting, the largest size that fits the text box (measuring text width; 12pt without a canvas). */ getCalculatedFontSize(): string; /** Switches to an automatically fitted font size (FontSize '0pt', also in the rich text style). */ switchToAutoFontSize(): void; /** Switches back to a fixed font size, using the currently fitted size. */ switchOutFromAutoFontSize(): void; /** Resizes the text box to fit the text exactly (measuring each line's width with font and size, line height 1.2×, padding around; note: the appearance is laid out by the engine and may differ slightly). */ fitText(): void; rotate(radians: number, center?: { /** X of the rotation center in PDF points. */ x: number; /** Y of the rotation center in PDF points. */ y: number; }): void; /** The bounding box of free text is the text box (and callout), not recomputed from points. */ adjustRect(): void; getRectPadding(): number; /** Display uses the appearance bitmap (text layout by the engine); this draws the box and callout for previews while creating and dragging. */ draw(ctx: CanvasRenderingContext2D, _pageMatrix: Matrix): void; /** * Gets the kind of free text. * @returns The intent. */ getIntent(): FreeTextIntent; /** * Sets the kind of free text. * @param intent The intent. */ setIntent(intent: FreeTextIntent): void; /** * Gets the line ending style at the start of the callout line. * @returns The line ending style. */ getStartStyle(): LineEndType; /** * Sets the line ending style at the start of the callout line. * @param style The line ending style. */ setStartStyle(style: LineEndType): void; /** Padding of the text box within the annotation rectangle (x1 / y1 / x2 / y2 = left / top / right / bottom, pt; /RD). */ getPadding(): Rect; /** * Sets the padding of the text box within the annotation rectangle (/RD). * @param padding Left, top, right and bottom padding in PDF points as x1, y1, x2, y2. */ setPadding(padding: Rect): void; /** Only recorded: the text box size is decided by the user, and the engine does not resize to the text when generating the appearance. */ getAutoSizeType(): FreeTextAutoSize; /** * Records the auto size type. It is only stored: the text box size is not changed. * @param type The auto size type. */ setAutoSizeType(type: FreeTextAutoSize): void; /** With a callout the whole thing moves (text box and callout together); resizing scales proportionally (like path annotations) with the padding unchanged. */ setRect(rect: Rect): void; private padding; /** The text box held during a drag (before the rectangle is recomputed). */ private textBox; private autoSizeType; } /** Core.Annotations.Link: CreateAnnot(kLink); actions come from GetLinkActionType / GetLinkDestination / GetLinkUri and run on click. */ declare class Link extends HTMLAnnotation { elementName: string; /** Automatic link (generated by DocumentViewer from URLs in page text): main thread only, not saved to the file or exported. */ private readonly automatic; /** * Creates a link annotation. * @param init Initial property values; isAutomaticLink marks a link generated from a URL in the page text. */ constructor(init?: AnnotationInit & { /** Marks a link generated from a URL in the page text. */ isAutomaticLink?: boolean; }); /** * Whether this link was generated from a URL in the page text (not saved to the file or exported). * @returns True for an automatic link. */ isAutomaticLink(): boolean; /** Same as isAutomaticLink. */ isAutomatic(): boolean; /** Border style: 'solid' (default) or 'underline' (only a bottom line, written as /BS /S /U); other values are saved as solid. */ StrokeStyle: string; } declare class PolylineAnnotation extends IPathAnnotation { /** Display units (read-only, derived from the scale; feet-inches are ft' and in"); an empty array when not a measurement annotation (DisplayUnits). */ get DisplayUnits(): string[]; /** Unit system Metric / Imperial / Typographic (read-only); an empty string when not a measurement annotation. */ get System(): string; /** Display format Decimal / Fraction (read-only, depends on precision and unit); an empty string when not a measurement annotation. */ get DisplayFormat(): string; elementName: string; /** Result text style (changed in the style panel; an empty string / null means unchanged: the engine default Helvetica 9 black); see MeasureTextStyle in utils/measurement-caption.ts. */ Font: string; /** Font size of the measurement result text in points, as a string; an empty string keeps the default. */ FontSize: string; /** Color of the measurement result text; null keeps the default. */ TextColor: Color | null; /** * Creates a polyline annotation. * @param init Initial property values. */ constructor(init?: AnnotationInit); /** Border style: 'solid' (default) or 'dash' (see border-style.ts). */ get Style(): string; set Style(style: string); /** Dash lengths (pt), comma separated, '3' by default; an array is joined into a string. */ get Dashes(): string | null; set Dashes(dashes: string | number[] | null); draw(ctx: CanvasRenderingContext2D, pageMatrix: Matrix): void; /** Perimeter measurement (matching the engine-generated appearance): a gap at the middle of each segment for its length, and the total above the last segment; both ends of path are already pulled back to the line endings. */ private drawMeasured; /** Line ending style at the first vertex. */ StartStyle: LineEndType; /** Line ending style at the last vertex. */ EndStyle: LineEndType; /** * Gets the line ending style at the first vertex. * @returns The line ending style. */ getStartStyle(): LineEndType; /** * Sets the line ending style at the first vertex. * @param style The line ending style. */ setStartStyle(style: LineEndType): void; /** * Gets the line ending style at the last vertex. * @returns The line ending style. */ getEndStyle(): LineEndType; /** * Sets the line ending style at the last vertex. * @param style The line ending style. */ setEndStyle(style: LineEndType): void; } /** CreateAnnot(kSquare); drawn by the main thread; border GetAnnotBorderStyle / SetBorderEffect(cloudy). */ declare class RectangleAnnotation extends MarkupAnnotation { elementName: string; /** Rotates by radians around center (the center by default; clockwise is positive): the unrotated box stays, the rectangle becomes the rotated bounding box, and Rotation follows. */ rotate(radians: number, center?: { /** X of the rotation center in PDF points. */ x: number; /** Y of the rotation center in PDF points. */ y: number; }): void; /** * Creates a rectangle annotation. * @param init Initial property values. * @example * ```js * const { annotationManager, Annotations } = instance.Core; * const rectangle = new Annotations.RectangleAnnotation({ PageNumber: 1, X: 100, Y: 100, Width: 150, Height: 80 }); * rectangle.StrokeColor = new Annotations.Color(255, 0, 0); * rectangle.FillColor = new Annotations.Color(255, 255, 0); * rectangle.StrokeThickness = 2; * await annotationManager.addAnnotation(rectangle); * ``` */ constructor(init?: AnnotationInit); private cloudIntensity; /** Cloud intensity, integers only (truncated on set; negative and NaN become 0); see normalizeCloudIntensity. */ get CloudIntensity(): number; set CloudIntensity(intensity: number); /** Cloud intensity (Intensity, same as CloudIntensity). */ get Intensity(): number; set Intensity(intensity: number); /** Border style: 'solid' (default), 'dash'; 'cloudy' when the cloud intensity is above 0 (see border-style.ts). Setting cloudy without intensity uses the default 2; setting anything else removes the cloud. */ get Style(): string; set Style(style: string); /** Dash lengths (pt), comma separated, '3' by default; an array is joined into a string. */ get Dashes(): string | null; set Dashes(dashes: string | number[] | null); /** Same as Style. */ getBorderStyle(): string; /** * Sets the border style (same as setting Style). * @param style 'solid' or 'dash'. */ setBorderStyle(style: string): void; /** * Gets the cloudy border intensity. * @returns The intensity; 0 means no cloudy border. */ getCloudIntensity(): number; /** * Sets the cloudy border intensity. * @param intensity The intensity; 0 means no cloudy border. */ setCloudIntensity(intensity: number): void; /** The border is drawn inside the rectangle (the PDF /Rect includes the border), so it is inset by half the line width; when rotated, the unrotated box is drawn rotated around the center. */ draw(ctx: CanvasRenderingContext2D, pageMatrix: Matrix): void; private drawBox; } /** Core.Annotations.TextMarkupAnnotation: base class of highlight / underline / strikeout / squiggly / redaction; Quads map to GetQuadPoints / SetQuadPoints. */ declare class TextMarkupAnnotation extends MarkupAnnotation { elementName: string; /** * Creates a text markup annotation. * @param init Initial property values. */ constructor(init?: AnnotationInit); /** Quadrilaterals of the marked text, in page coordinates. */ Quads: Quad[]; setRect(rect: Rect): void; /** * Gets the quadrilaterals of the marked text. * @returns The quadrilaterals (the internal array, not a copy). */ getQuads(): Quad[]; /** * Replaces the quadrilaterals of the marked text. * @param quads The quadrilaterals in page coordinates. * @example * ```js * const { documentViewer, annotationManager, Annotations } = instance.Core; * const underline = new Annotations.TextUnderlineAnnotation({ PageNumber: 1 }); * underline.setQuads(documentViewer.getSelectedTextQuads(1)); * await annotationManager.addAnnotation(underline); * ``` */ setQuads(quads: Quad[]): void; } /** * CreateAnnot(kRedact); applied through AnnotationManager.applyRedactions (ApplyRedaction). * Field names: OverlayText, Font, FontSize, TextAlign, TextColor, FillDisplayColor; * Erasure marks an erasure redaction (it lives only in memory and is not written to the file, where it is an ordinary redaction). */ declare class RedactionAnnotation extends TextMarkupAnnotation { elementName: string; /** * Creates a redaction annotation. * @param init Initial property values. */ constructor(init?: AnnotationInit); /** The pointer is over it (hovering previews the applied result, with fill color and overlay text; otherwise only a red outline). Memory only, managed by AnnotationManager. */ hovered: boolean; /** * Before applying, draws the outline of the area to be removed; on hover also fills it and writes the overlay text. * One box per area (the bounding rectangle of each quadrilateral, or the annotation rectangle without quadrilaterals); the border width is StrokeThickness, or 2 when unset (0), * border-box: left and right borders outside the area, top and bottom borders inside. */ draw(ctx: CanvasRenderingContext2D, pageMatrix: Matrix): void; /** Bounding rectangle of each area. */ private boxes; /** Hover preview: each area is filled with FillDisplayColor (FillColor when missing), the overlay text is written at the top-left by alignment (padding of 4 screen pixels, clipped to the area). */ private drawPreview; /** Text placed over the redacted area after applying (an empty string means none). */ OverlayText: string; /** Font name of the overlay text; 'Helvetica' by default. */ Font: string; /** Font size of the overlay text with unit; '14pt' by default. */ FontSize: string; /** Horizontal alignment of the overlay text; 'left' by default. */ TextAlign: 'left' | 'center' | 'right'; /** Color of the overlay text; red by default. */ TextColor: Color; /** Fill color shown before applying (FillDisplayColor; FillColor is the color after applying). */ FillDisplayColor: Color | null; /** Erasure: applying erases text and graphics in the area without filling (memory only; an ordinary redaction after saving). */ Erasure: boolean; } /** Eight-direction resize handle of a rectangle (only the four corners when keeping the ratio or rotated at an angle; see resizeHandlesOf in tools/annotation-select-tool.ts). */ /** Resize handle on a corner or edge midpoint of a rectangular selection box. */ declare class BoxControlHandle extends ControlHandle { } /** Rectangle types (Rectangle / Ellipse / Stamp / Widget). */ /** Selection model of rectangular annotations (rectangles, ellipses, stamps, widgets): resize handles on the bounding box. */ declare class BoxSelectionModel extends SelectionModel { } /** Path vertex handle. */ /** Handle on a vertex of a path. */ declare class PathControlHandle extends ControlHandle { } /** Callout vertex handle. */ /** Vertex handle of a callout line. */ declare class CalloutControlHandle extends PathControlHandle { } /** FreeText with a callout. */ /** Selection model of free text annotations with a callout. */ declare class CalloutSelectionModel extends SelectionModel { } /** FileAttachment */ /** Selection model of file attachment annotations. */ declare class FileAttachmentSelectionModel extends SelectionModel { } /** FreeText */ /** Selection model of free text annotations without a callout. */ declare class FreeTextSelectionModel extends BoxSelectionModel { } /** Line end point handle. */ /** Handle on an end point of a line. */ declare class LineControlHandle extends ControlHandle { } /** Measurement leader handle. */ /** Handle that changes the leader length of a distance measurement. */ declare class LineLeaderControlHandle extends LineControlHandle { } /** Line / Arrow / distance measurement: two handles, start and end (LineControlHandle). */ /** Selection model of lines, arrows and distance measurements: a handle on each end point. */ declare class LineSelectionModel extends SelectionModel { /** * Gets the handles: one per end point (plus the rotation handle when rotatable); the bounding box handles when the line cannot be modified point by point. * @returns The control handles. */ getControlHandles(): ControlHandle[]; } /** Polyline / Arc: one handle per point (PathControlHandle). */ /** Selection model of polylines and arcs: a handle on each point. */ declare class PathSelectionModel extends SelectionModel { /** * Gets the handles: one per point (plus the rotation handle when rotatable); the bounding box handles when the path cannot be modified point by point. * @returns The control handles. */ getControlHandles(): ControlHandle[]; } /** Polygon vertex handle. */ /** Handle on a vertex of a polygon. */ declare class PolygonControlHandle extends PathControlHandle { } /** * Polygon: one handle per vertex (PolygonControlHandle); rectangular polygons (rectangular area) use the 8 bounding box handles. */ /** Selection model of polygons: a handle on each vertex; rectangular polygons use the bounding box handles. */ declare class PolygonSelectionModel extends SelectionModel { /** * Gets the handles: one per vertex (plus the rotation handle when rotatable); the bounding box handles for rectangular polygons. * @returns The control handles. */ getControlHandles(): ControlHandle[]; } /** Redaction */ /** Selection model of redaction annotations. */ declare class RedactionSelectionModel extends SelectionModel { } /** Rotation handle: a dot to the right of the selected annotation's center (turning around the center with Rotation); drag it to rotate around the annotation center (present on point-defined and box-rotated annotations, see rotatable / rotationHandleOf in tools/annotation-select-tool.ts); cursor grab. */ /** Rotation handle: dragging it rotates the annotation around its center. */ declare class RotationControlHandle extends ControlHandle { } /** Core.Annotations.RotationUtils: rotation geometry utilities (a set of functions), in plain JS. */ /** Rotation geometry helpers. */ declare const RotationUtils: { /** Rotates a point by angle around center (radians, page coordinates with y down, positive is clockwise). */ getRotatedPointsArray(points: Point[], center: Point, angle: number): Point[]; /** * Converts degrees to radians. * @param degrees Angle in degrees. * @returns Angle in radians. */ getRotationAngleInRadiansByDegrees(degrees: number): number; /** For a rectangle-type annotation rotated by angle: derives the unrotated box from the bounding box rect (centered in the bounding box). */ getUnrotatedDimensionsFromRectangularAnnotations(rect: { /** Left edge. */ x1: number; /** Top edge. */ y1: number; /** Right edge. */ x2: number; /** Bottom edge. */ y2: number; }, angle: number): { /** Left edge of the unrotated box. */ x: number; /** Top edge of the unrotated box. */ y: number; /** Width of the unrotated box. */ width: number; /** Height of the unrotated box. */ height: number; }; /** Bounding box of the unrotated box (x, y, width, height) after rotating by angle around center (the box center by default). */ getRotatedBoundingBoxRectFromRectangularAnnotations(box: { /** Left edge. */ x: number; /** Top edge. */ y: number; /** Width. */ width: number; /** Height. */ height: number; }, angle: number, center?: Point): Rect; }; /** Core.Annotations.SelectionAlgorithm: static hit-testing algorithms in plain JS; (x, y) are page coordinates. */ /** Hit-testing algorithms used by selection models; coordinates are page coordinates. */ declare class SelectionAlgorithm { /** The point is inside the annotation rectangle (expanded by a few screen pixels). */ static boundingRectTest(annotation: Annotation$1, x: number, y: number, pageMatrix: Matrix): boolean; /** Hits are not tested by drawn pixels; same as boundingRectTest. */ static canvasVisibilityTest(annotation: Annotation$1, x: number, y: number, pageMatrix: Matrix): boolean; /** The point is inside the bounding box of one of the text markup's quadrilaterals (page coordinates). */ static textQuadTest(annotation: TextMarkupAnnotation, x: number, y: number): boolean; /** * The point is inside a polygon annotation (page coordinates, even-odd rule, points on edges count); false when not a polygon annotation, canvasVisibilityTest with fewer than 3 points. * When the annotation does not rotate with the page (NoRotate) and the page is rotated, the point is first rotated back opposite to the page rotation (rotation is a multiple of 90°, 0~3). * zoom exists only for signature compatibility; the hit tolerance here is converted by pageMatrix and does not use it. */ static insidePolygonTest(annotation: PolygonAnnotation, x: number, y: number, pageMatrix: Matrix, _zoom: number, rotation?: number): boolean; } /** Sound */ /** Selection model of sound annotations. */ declare class SoundSelectionModel extends FileAttachmentSelectionModel { } /** * Sticky (StickySelectionModel): NoZoom notes are hit-tested and drawn with a selection box at screen size (Width × Height screen pixels, divided by the zoom on the page); * they cannot be resized and have no handles. */ /** Selection model of sticky notes: hit-tested at their screen size, no handles. */ declare class StickySelectionModel extends SelectionModel { /** * Gets the handles; sticky notes have none. * @returns An empty array. */ getControlHandles(): ControlHandle[]; /** * Whether a point hits the note, using its on-screen size (with a small tolerance). * @param annotation The annotation. * @param x X in page coordinates. * @param y Y in page coordinates. * @param pageMatrix Transform from page coordinates to canvas coordinates. * @returns True when the point hits the note. */ testSelection(annotation: Annotation$1, x: number, y: number, pageMatrix: Matrix): boolean; draw(ctx: CanvasRenderingContext2D, annotation: Annotation$1, pageMatrix: Matrix): void; private zoomOf; } /** Text markup end point handle. */ /** Handle on an end of a text markup selection. */ declare class TextControlHandle extends ControlHandle { } /** Text markup (Highlight / Underline / ...). */ /** Selection model of text markup annotations (highlight, underline, strikeout, squiggly). */ declare class TextSelectionModel extends SelectionModel { } interface SoundAudio { blob?: Blob; rate?: number; channels?: number; bits?: number; encoding?: string; } declare class SoundAnnotation extends MarkupAnnotation { elementName: string; /** Audio format and data (blob is available after prepareAudioBlob; the data is raw samples, not WAV). */ audio: SoundAudio; /** * Whether the annotation has audio data. * @returns True when audio data is present. */ hasAudioData(): boolean; /** Reads the audio data into audio.blob; does nothing without audio. */ prepareAudioBlob(): Promise; } /** CreateAnnot(kHighlight); drawn by the main thread, no appearance fetched. */ declare class TextHighlightAnnotation extends TextMarkupAnnotation { elementName: string; /** * Multiplied with the page. * @example * ```js * const { annotationManager, Annotations, Math: CoreMath } = instance.Core; * // Each quad covers one line of text: x1/y1 bottom-left, x2/y2 bottom-right, x3/y3 top-right, x4/y4 top-left (PDF points, y grows downward) * const highlight = new Annotations.TextHighlightAnnotation({ PageNumber: 1 }); * highlight.setQuads([new CoreMath.Quad(72, 120, 300, 120, 300, 106, 72, 106)]); * highlight.StrokeColor = new Annotations.Color(255, 255, 0); // the highlight color * await annotationManager.addAnnotation(highlight); * ``` */ constructor(init?: AnnotationInit); /** The highlight color (/C) fills the quadrilaterals with multiply, so the text below stays clear. */ draw(ctx: CanvasRenderingContext2D, pageMatrix: Matrix): void; } /** CreateAnnot(kSquiggly); drawn by the main thread. */ declare class TextSquigglyAnnotation extends TextMarkupAnnotation { /** * Length of one full wave in page units, used when drawing every squiggly annotation in the viewer (not the appearance saved to the file); 10 by default. * Must be greater than 0; otherwise no wave is drawn. Redraw annotations (for example AnnotationManager.drawAnnotationsFromList) after changing it. */ static waveLength: number; /** * Wave amplitude in page units, used when drawing every squiggly annotation in the viewer (not the appearance saved to the file); 2 by default. * Must be 0 or greater; otherwise no wave is drawn. Redraw annotations (for example AnnotationManager.drawAnnotationsFromList) after changing it. */ static waveAmplitude: number; elementName: string; /** * Draws fixed-size waves along the bottom edge: TextSquigglyAnnotation.waveLength / waveAmplitude (page units, independent of line height), one cubic Bézier per half wave, clipped to the line; troughs touch the bottom edge. * Bézier control points are offset by 4/3 of the amplitude so the curve midpoint reaches the amplitude exactly. * Drawn in a "bottom edge frame": origin at the start of the bottom edge raised by one amplitude, x along the bottom edge, y toward the outside of the bottom edge, so lines in any direction (rotated pages, vertical writing) look the same. */ draw(ctx: CanvasRenderingContext2D, pageMatrix: Matrix): void; } /** CreateAnnot(kStrikeout); drawn by the main thread. */ declare class TextStrikeoutAnnotation extends TextMarkupAnnotation { elementName: string; /** Connects the midpoints of the left and right edges. */ draw(ctx: CanvasRenderingContext2D, pageMatrix: Matrix): void; } /** CreateAnnot(kUnderline); drawn by the main thread. */ declare class TextUnderlineAnnotation extends TextMarkupAnnotation { elementName: string; /** Draws a line along the bottom edge of the quadrilateral, 7% of the line height wide (at least 1 pt). */ draw(ctx: CanvasRenderingContext2D, pageMatrix: Matrix): void; } /** * Source of the default annotation subject (Subject), via setAnnotationSubjectHandler: * each annotation class asks the handler for the Subject with its type key when created (not a getter; changing the handler later does not affect existing annotations); * the default handler translates by the table below, and keys missing from it give "Unknown". A static entry point, one per runtime environment. */ type AnnotationSubjectHandler = (type: string) => string; /** Sets the resolver of annotation subjects (Core.Annotations.Utilities.setAnnotationSubjectHandler); only affects annotations created afterwards. */ declare function setAnnotationSubjectHandler(func: AnnotationSubjectHandler): void; /** Core.Annotations.Utilities: annotation subject handler and automatic font size. */ /** Arguments of calculateAutoFontSize: font size and the annotation's quadrilaterals (only y1 and y3 are used). */ interface FreeTextSubset { /** Base font size, such as 12 or '12pt'. */ FontSize: string | number; /** Quadrilaterals of the annotation; only y1 and y3 are used. */ Quads?: Array<{ /** Y of the first point of the quadrilateral. */ y1: number; /** Y of the third point of the quadrilateral. */ y3: number; }>; } /** * Automatic font size of free text: the smallest line height in the quadrilaterals (y1 - y3), rounded and multiplied by 0.75, is the upper limit; the smaller of the limit and the base size is returned with pt; * the base size is returned unchanged without quadrilaterals or when the smallest line height is 0. */ declare function calculateAutoFontSize(freeTextSubset: FreeTextSubset): string | number; /** Base class of button widgets; Check / Radio / Push extend it directly. */ declare class ButtonWidgetAnnotation extends WidgetAnnotation { elementName: string; /** Value when checked ('Yes' when a check box cannot read it; GetGroupMemberName for radios). */ exportValue: string; } /** CreateWidget(CheckBox); GetCheckBoxIsChecked / SetCheckBoxIsChecked / SetWidgetCheckStyle. */ declare class CheckButtonWidgetAnnotation extends ButtonWidgetAnnotation { elementName: string; } /** CreateWidget(ComboBox); GetWidgetItems / AddOptionItem / SetItemsSelectedIndex. */ declare class ChoiceWidgetAnnotation extends WidgetAnnotation { elementName: string; /** * Creates a combo box widget (sets the Combo flag). * @param field The field the widget belongs to. * @param init Initial property values. */ constructor(field?: Field | null, init?: AnnotationInit); } /** CreateWidget(TextField); GetTextFieldContent / SetTextFieldContent; GetMaxLength. */ declare class TextWidgetAnnotation extends WidgetAnnotation { elementName: string; /** Maximum length /MaxLen (0 = unlimited). Read from the file, read-only. */ maxLen: number; /** * Gets the maximum text length (/MaxLen). * @returns The maximum length; 0 means unlimited. */ getMaxLen(): number; /** Comb field: Comb flag set with MaxLen, one character per cell (cells = MaxLen). Comb without MaxLen is treated as an ordinary text field (PDF specification). */ isComb(): boolean; } declare class DatePickerWidgetAnnotation extends TextWidgetAnnotation { elementName: string; /** Date format (pdfDateFormat, same as dateFormat / getDateFormat). */ get pdfDateFormat(): string; set pdfDateFormat(format: string); /** * Gets the date format of the field. * @returns The date format. */ getDateFormat(): string; /** * Changes the date format (all widgets of the same field together): an existing value readable with the old format is rewritten in the new one; then committed, and written to the field's /AA on save. * Values that cannot be read are left unchanged. */ setDateFormat(format: string): Promise; /** The input box over the widget while filling (when open), otherwise null. */ getDatePicker(): HTMLElement | null; /** Redraws (after the format or value changes). */ refreshDatePicker(): void; } /** CreateWidget(ListBox); IsMultiSelectListBox / GetItemsSelectedValue. */ declare class ListWidgetAnnotation extends WidgetAnnotation { elementName: string; } /** CreateWidget(PushButton); GetButtonTitle / SetButtonAction. */ declare class PushButtonWidgetAnnotation extends ButtonWidgetAnnotation { elementName: string; /** * Creates a push button widget (sets the PushButton flag). * @param field The field the widget belongs to. * @param init Initial property values. */ constructor(field?: Field | null, init?: AnnotationInit); } /** CreateWidget(RadioButton); GetRadioButtonIsChecked / SetRadioButtonIsChecked / Get/SetGroupMemberName (export value). */ declare class RadioButtonWidgetAnnotation extends ButtonWidgetAnnotation { elementName: string; /** * Creates a radio button widget (sets the Radio flag). * @param field The field the widget belongs to. * @param init Initial property values. */ constructor(field?: Field | null, init?: AnnotationInit); } /** * Base class for selecting and dragging annotations (AnnotationEdit / Pan / Sticky / TextTool / GenericCreate all extend it). * Click selects (Shift adds / removes), dragging moves the selected annotations, dragging selection box handles resizes (lines, polylines, arcs and polygons drag their vertices; Shift snaps to 45°); * on release updateAnnotation is called once for each changed annotation. * Delete / Backspace deletes the selected annotations, Escape clears the selection. Dragging only changes main-thread objects and redraws the annotation layer, without sending commands. * Only annotations allowed by canModify are dragged or deleted. Outside form field creation mode, clicking a widget fills it (toggles check boxes / radios, opens an editor for text / choices) instead of selecting it. */ /** Minimum / maximum size while resizing: takes the annotation being resized and returns { width, height } (either may be omitted); null means no limit. */ type SizeGetter = (annotation: Annotation$1) => { [key: string]: number; } | null; declare class AnnotationSelectTool extends Tool { /** Sets the minimum size when resizing annotations (static, shared by all select / edit tools). */ static setMinimumAnnotationSizeWhenResizing(getter: SizeGetter | null): void; /** Sets the maximum size when resizing annotations. */ static setMaximumAnnotationSizeWhenResizing(getter: SizeGetter | null): void; private drag; private removeTouchGuard; private bindTouchGuard; private lastPointer; getMouseLocation(e: Pick): MouseLocation; /** Pressed on a link: its action runs if the pointer is still over it on release. */ private pressedLink; /** Pressed on an unselected annotation (without immediate action): selected on release. */ private pendingSelect; /** Immediate action (off by default): when on, pressing an unselected annotation selects it at once and it can be dragged directly; when off, click to select first, then press again to drag. */ private immediateAction; /** Selects an annotation as soon as it is pressed, so it can be dragged in the same gesture (text markup is still selected on release). */ enableImmediateActionOnAnnotationSelection(): void; /** Selects an annotation when the press is released (the default); the press does not drag it. */ disableImmediateActionOnAnnotationSelection(): void; /** Subclasses may clear reading state only after a pointer action has been admitted. */ protected beforeAnnotationInteraction(): void; mouseLeftDown(e: PointerEvent): void; mouseMove(e: PointerEvent): void; mouseLeftUp(e: PointerEvent): void; /** Commits after dragging: annotations moved to another page are moved there, the rest get updateAnnotation one by one. */ private commitDrag; /** Fires annotationDoubleClicked; free text enters inline editing. */ mouseDoubleClick(e: MouseEvent): void; keyDown(e: KeyboardEvent): void; switchIn(oldTool?: Tool): void; switchOut(newTool?: Tool): void; /** The press grabbed an annotation (move, resize, drag a handle); subsequent moves go to it. */ protected isSelecting(): boolean; /** With the link tool on, pressing a hand-drawn link selects, drags and resizes it (otherwise a click follows it). */ get selectsLinks(): boolean; private rubberBand; /** This press was taken over by the selection logic (creation tools then do not start drawing). */ private selectingPress; /** The leader handle of a selected measurement line under the pointer (checked before rectangle handles). */ private leaderHandleAt; /** The callout point handle of a selected free text with a callout under the pointer. */ private calloutHandleAt; /** The rotation handle of a selected annotation under the pointer. */ private rotationHandleAt; /** The vertex handle of a selected line / polyline / arc / polygon under the pointer. */ private vertexHandleAt; /** The selected group on this page (see groupOf); an empty array when none. */ private groupAt; /** The handle of the group's outer box under the pointer. */ private groupResizeHandleAt; /** * A press on a group's outer box: handles scale the group, inside the box (without add / remove modifiers) moves the group, regardless of what lies below; returns whether it took the press. * While a group exists, the members' own handles (vertices, leaders, rotation...) do not appear, so they are not searched. */ private pressGroup; /** The handle of a selected (resizable) annotation under the pointer. */ private handleAt; /** * Clamps the move displacement into the page (when Tool.ALLOW_ANNOTS_OUTSIDE_PAGE is off): dragged annotations stay in the page, * and do not move in a direction where they are wider (taller) than the page. */ private keepInPage; /** Selection box padding plus half a handle (page coordinates): the selection box and handles stay inside the page while dragging (the same as the safe distance of content editing boxes). */ private frameMargin; /** Clamps the pointer (page coordinates) into the page while dragging a handle; not clamped when the page cannot fit it. */ private keepPointInPage; /** * When the pointer reaches another page while dragging (switch on, all dragged annotations on the same page): moves them all to that page, keeping the grab point's position within the bounding box, and moves them into the page; * on release they land on the new page (AnnotationManager.moveAnnotationsToPage). Returns whether the page changed. */ private moveToOtherPage; private startDrag; } /** * ToolNames.EDIT (the default tool): select, drag and resize, then updateAnnotation in mouseLeftUp. * With no annotation selected, mouse / pen pressing on text drags a text selection; fingers keep scrolling and dragging existing selection handles; double-click on text selects a word. */ declare class AnnotationEditTool extends AnnotationSelectTool { private textSelection; private readonly selector; keyDown(e: KeyboardEvent): void; /** Lets the edit tool select text when pressing on text (also requires Tool.ENABLE_AUTO_SWITCH). */ enableTextSelection(): void; /** Stops the edit tool from selecting text. */ disableTextSelection(): void; /** Text can be selected only when both the instance switch and Tool.ENABLE_AUTO_SWITCH are on. */ isTextSelectionEnabled(): boolean; mouseLeftDown(e: PointerEvent): void; protected beforeAnnotationInteraction(): void; protected isSelecting(): boolean; mouseMove(e: PointerEvent): void; mouseLeftUp(e: PointerEvent): void; mouseDoubleClick(e: MouseEvent): void; } declare class AddImageContentTool extends Tool { cursor: string; /** The hover cursor is off while placing an image box. */ switchIn(oldTool?: Tool): void; switchOut(newTool?: Tool): void; mouseLeftUp(e: PointerEvent): void; } /** * Base class for shape creation: mouseLeftDown creates an annotation with the tool's default style (fires annotationCreated, not yet added to the document), * mouseMove changes the geometry from the start point and the pointer, mouseLeftUp calls addAnnotation (fires annotationAdded); annotations that are too small (accidental clicks) are dropped. * While drawing, the viewer draws the annotation on the annotation layer (this.annotation). Switching tools or pressing Escape discards an unfinished annotation. */ type AnnotationClass = new (init?: AnnotationInit) => Annotation$1; /** * Draw modes: press-and-drag (default), two clicks (the first press is the start, moving follows, the second press completes), * and mixed (lines only: holding longer than 400 ms before moving is press-and-drag, otherwise two clicks). */ declare const DrawModes: { /** Press and drag (the default). */ readonly HOLD_TO_DRAW: "holdToDraw"; /** First click starts, second click completes. */ readonly TWO_CLICKS: "twoClicks"; /** Lines only: holding longer than 400 ms before moving draws by dragging, otherwise by two clicks. */ readonly TWO_CLICKS_HOLD_TO_DRAW_HYBRID: "twoClicksHoldToDrawHybrid"; }; type DrawMode = typeof DrawModes[keyof typeof DrawModes]; declare class GenericAnnotationCreateTool extends AnnotationSelectTool { protected readonly annotationPrototype: AnnotationClass; /** The annotation being drawn, not yet added to the document. */ annotation: Annotation$1 | null; /** Page coordinates at press time. */ protected start: MouseLocation | null; /** Current draw mode; chosenDrawMode is the one set by setDrawMode (mixed mode switches between the two after the press). */ protected drawMode: DrawMode; private pressedAt; /** * Creates a tool that draws annotations of a given class (black stroke, no fill, width 1, opacity 1 by default). * @param docViewer The document viewer the tool works on. * @param annotationPrototype Class of the annotations to create; RectangleAnnotation by default. */ constructor(docViewer: DocumentViewer, annotationPrototype?: AnnotationClass, /** @internal */ initArgs?: AnnotationInit | undefined); cursor: string; switchOut(): void; mouseLeftDown(e: PointerEvent): void; mouseMove(e: PointerEvent): void; mouseLeftUp(e: PointerEvent): void; /** Double-clicking an existing annotation: same as the selection tool (fires annotationDoubleClicked; free text enters inline editing). */ mouseDoubleClick(e: MouseEvent): void; keyDown(e: KeyboardEvent): void; /** Adds the annotation being drawn to the document (dropped when too small). */ finish(): void; /** Creates the annotation: position, page, author, then the default style. */ protected createAnnotation(at: MouseLocation): Annotation$1; /** Changes the geometry from the start and current points; by default the rectangle spanned by the two points. */ protected update(annotation: Annotation$1, start: { x: number; y: number; }, p: { x: number; y: number; }): void; } /** * ToolNames.FREETEXT: drag out a text box (a click gives the default size); content defaults to "Insert text here", with red Helvetica 12pt text and no border. * After adding it goes straight into inline editing (enableAutoFocusOnCreate, on by default) and is deleted if nothing is typed. * While a text box is being edited, or an annotation is selected and empty space is pressed, the press only ends editing (the editor commits on blur) and deselects without creating (with enableCreationWhileSelecting it creates anyway); * pressing an existing annotation selects and drags it as usual (like the selection tool). */ /** Callback of setTextHandler (called with the tool as this; returns the initial text of a new text box). */ type FreeTextTextHandler = (this: FreeTextCreateTool) => string; declare class FreeTextCreateTool extends GenericAnnotationCreateTool { private static textHandler; /** * Sets the source of the initial text of new text boxes (static; date free text has its own source and is unaffected). * With inline typing (the default) the text box starts empty and the text comes from typing, so it is not used; it is used only on the create-then-edit path (subclasses other than add paragraph, or with inlineCreate off). */ static setTextHandler(handler: FreeTextTextHandler): void; /** Initial text of new text boxes when they are created and then edited. */ initialText: string; private autoFocus; /** * Creates the free text tool: red Helvetica 12pt left-aligned text, no border. * @param docViewer The document viewer the tool works on. */ constructor(docViewer: DocumentViewer); /** Content at creation (DateFreeText overrides it with a date). */ protected text(): string; protected createAnnotation(at: MouseLocation): Annotation$1; /** The editor of the text box currently open. */ isEditing(): boolean; /** Where the input box opens on release after this press; none when the press was used for something else (selecting an annotation, deselecting). */ private openAt; mouseLeftDown(e: PointerEvent): void; mouseLeftUp(e: PointerEvent): void; mouseMove(e: PointerEvent): void; /** The old create-then-edit approach (used by date free text and add paragraph): while editing or with a selection, this press only ends editing and deselects. */ private legacyMouseLeftDown; finish(): void; /** Opens the text editor right after a text box is created (the default). */ enableAutoFocusOnCreate(): void; /** Does not open the text editor after a text box is created. */ disableAutoFocusOnCreate(): void; /** * Whether the text editor opens right after a text box is created. * @returns True when auto focus is on. */ isAutoFocusingOnCreate(): boolean; /** Creates a text box even when the press only ends editing or deselects annotations. */ enableCreationWhileSelecting(): void; /** A press that ends editing or deselects annotations does not create a text box (the default). */ disableCreationWhileSelecting(): void; } /** * ToolNames.ADD_PARAGRAPH: drag out a paragraph box (a click gives the default size), create a text box there and start editing (entering content editing mode first when not in it), * then switch to the box selection tool. Without input the box is removed; with input, creating and typing are one entry in the content editing history. */ declare class AddParagraphTool extends FreeTextCreateTool { private pendingInput; private touchRelease; mouseLeftUp(e: PointerEvent): void; switchOut(): void; keyDown(e: KeyboardEvent): void; /** * Creates the add paragraph tool. * @param docViewer The document viewer the tool works on. */ constructor(docViewer: DocumentViewer); finish(): void; } declare class ContentEditTool extends AnnotationSelectTool { private boxDrag; /** Dragging to select text while editing. */ private selecting; private hitting; private marquee; /** PointerEvent.detail is zero in browsers; track desktop presses without changing touch taps. */ private desktopClick; private get content(); protected isSelecting(): boolean; mouseLeftDown(e: PointerEvent): void; mouseMove(e: PointerEvent): void; mouseLeftUp(e: PointerEvent): void; /** Sends dragged boxes to the Worker (SetFrame; a group is one request and one history entry); restores the original position on failure. */ private commitBox; mouseDoubleClick(e: MouseEvent): void; keyDown(e: KeyboardEvent): void; switchOut(): void; /** Handles of the selected box (not editing): drawn at the corners and edge midpoints of the outline's center line rectangle and grabbed where drawn. */ private boxHandleAt; /** Handles of the multiple-selection group box (union of the box containers). */ private groupHandleAt; private groupFrameOf; private frameHandleAt; /** * Scaling the group by its handle: the group box resizes with the drag, each box's container (the text rectangle plus 7px for text boxes, the rectangle for image boxes) * scales proportionally with the group while the text box extension stays the same; the result is clamped to the page (safe distance). During the drag only outlines move; on release commitBox sends one request to the Worker. */ private resizeGroup; } declare class FileAttachmentCreateTool extends Tool { /** Event names of the file attachment tool. */ static readonly Events: { /** 'fileRejected': the picked file is larger than ACCEPTED_FILE_SIZE. */ readonly FILE_REJECTED: "fileRejected"; /** 'annotationCreated': a file attachment annotation was created. */ readonly ANNOTATION_CREATED: "annotationCreated"; /** 'annotationAdded': a file attachment annotation was added to the document. */ readonly ANNOTATION_ADDED: "annotationAdded"; }; /** File types accepted by the file picker (its accept attribute); null accepts all files. */ ACCEPTED_FILE_TYPES: string | null; /** Maximum file size in bytes; larger files fire fileRejected. null means no limit. */ ACCEPTED_FILE_SIZE: number | null; defaults: Record; cursor: string; /** The hover cursor is off while placing an attachment. */ switchIn(oldTool?: Tool): void; switchOut(newTool?: Tool): void; mouseLeftDown(e: PointerEvent): void; } /** * Base class for creating form fields (CreateWidget); works with FormFieldCreationManager. Drag out the widget box (a click gives the default size); * field names are numbered automatically by type (TextField1, CheckBox1 ..., skipping ones already in the document); defaults are a black 1pt border and no background. */ declare class FormFieldCreateTool extends GenericAnnotationCreateTool { /** Nothing is created on a signature field that already has a digital signature (it cannot be selected either): pressing does nothing. */ mouseLeftDown(e: PointerEvent): void; /** * @param docViewer The owning DocumentViewer. * @param widgetClass Which widget to create. * @param namePrefix Prefix of automatic field names. * @param clickSize Size (pt) for a click without dragging out a box. */ /** * Creates a form field tool. * @param docViewer The document viewer the tool works on. * @param widgetClass Class of the widgets to create. * @param namePrefix Prefix of the generated field names. * @param clickSize Width and height in PDF points of fields added with a click; 150 x 22 by default. */ constructor(docViewer: DocumentViewer, widgetClass?: typeof WidgetAnnotation, /** @internal */ namePrefix?: string, /** @internal */ clickSize?: [number, number]); protected createAnnotation(at: MouseLocation): Annotation$1; /** The prefix plus the smallest number not yet used in the document. */ private nextName; } /** ToolNames.CHECK_BOX_FIELD; CreateWidget(CheckBox). */ declare class CheckBoxFormFieldCreateTool extends FormFieldCreateTool { /** * Creates the check box form field tool (fields are 18 x 18 pt when added with a click). * @param docViewer The document viewer the tool works on. */ constructor(docViewer: DocumentViewer); } /** ToolNames.COMBO_BOX_FIELD; CreateWidget(ComboBox). */ declare class ComboBoxFormFieldCreateTool extends FormFieldCreateTool { /** * Creates the combo box form field tool. * @param docViewer The document viewer the tool works on. */ constructor(docViewer: DocumentViewer); } /** ToolNames.DATE_PICKER_FORM_FIELD; CreateWidget(TextField) + SetTextFieldSpe; the format is written to the field's /AA on save (see DatePickerWidgetAnnotation). */ declare class DatePickerFormFieldCreateTool extends FormFieldCreateTool { private dateFormat; /** * Creates the date picker form field tool. * @param docViewer The document viewer the tool works on. */ constructor(docViewer: DocumentViewer); /** Format of date fields created afterwards. */ setDateFormat(format: string): void; protected createAnnotation(at: MouseLocation): Annotation$1; } /** ToolNames.LIST_BOX_FIELD; CreateWidget(ListBox). */ declare class ListBoxFormFieldCreateTool extends FormFieldCreateTool { /** * Creates the list box form field tool (fields are 150 x 60 pt when added with a click). * @param docViewer The document viewer the tool works on. */ constructor(docViewer: DocumentViewer); } /** * ToolNames.RADIO_FORM_FIELD; CreateWidget(RadioButton). Each new radio button starts as its own group (automatic field name); * its export value is numbered by the radio buttons in the document (Choice1, Choice2 ...) so buttons stay distinguishable after joining one group. */ declare class RadioButtonFormFieldCreateTool extends FormFieldCreateTool { /** * Creates the radio button form field tool (fields are 18 x 18 pt when added with a click). * @param docViewer The document viewer the tool works on. */ constructor(docViewer: DocumentViewer); protected createAnnotation(at: MouseLocation): Annotation$1; } /** ToolNames.SIG_FORM_FIELD; CreateWidget(SignatureFields). */ declare class SignatureFormFieldCreateTool extends FormFieldCreateTool { /** * Creates the signature form field tool (fields are 150 x 40 pt when added with a click; no border and no background). * @param docViewer The document viewer the tool works on. */ constructor(docViewer: DocumentViewer); } /** ToolNames.TEXT_FORM_FIELD; CreateWidget(TextField). */ declare class TextFormFieldCreateTool extends FormFieldCreateTool { /** * Creates the text form field tool. * @param docViewer The document viewer the tool works on. */ constructor(docViewer: DocumentViewer); } /** * ToolNames.POLYLINE: each click adds a vertex, the last segment follows the pointer, double-click or Enter completes, Escape abandons. * After disableCreationOverAnnotation, a first click on an existing annotation does not start drawing. After setSnapMode, points snap to the page's vector content. */ declare class PolylineCreateTool extends GenericAnnotationCreateTool { private creationOverAnnotation; /** * Creates the polyline tool (no line endings by default). * @param docViewer The document viewer the tool works on. * @param annotationPrototype Class of the annotations to create. */ constructor(docViewer: DocumentViewer, annotationPrototype?: AnnotationClass); /** The first click creates (two points: the fixed one and the one following the pointer); each later click fixes the following point and adds another. */ mouseLeftDown(e: PointerEvent): void; mouseMove(e: PointerEvent): void; mouseLeftUp(e: PointerEvent): void; mouseDoubleClick(e: MouseEvent): void; keyDown(e: KeyboardEvent): void; protected createAnnotation(at: MouseLocation): Annotation$1; /** Removes the "drawing" look before adding to the document (the dashed edge back to the first point becomes the polygon's own edge). */ finish(): void; /** A polygon closes when clicking back on the first vertex (within 8px on screen); polylines do not close. */ protected closes(path: Point[]): boolean; protected path(): Point[]; /** Snap mode (a SnapModes value or combination): once set, snaps to the page's vector content both before and while drawing (see tools/snapping.ts). */ getSnapMode(): number | undefined; /** * Sets which points of the page content the vertices snap to. * @param mode A snap mode, or several to combine. */ setSnapMode(mode: SnapModes | SnapModes[]): void; /** Lets a first click on an existing annotation start drawing. */ enableCreationOverAnnotation(): void; /** A first click on an existing annotation selects it instead of starting to draw (the default). */ disableCreationOverAnnotation(): void; } /** * ToolNames.ARC: the first click sets the start, and moving previews a semicircle with the start-to-pointer segment as diameter; the second click sets a point on the arc, after which the pointer is the end; the third click sets the end and completes it. * Stored as three points: start, a point on the arc, end (a three-point ink in the file; see reading and writing in annotation-manager). ArcMeasurementCreateTool extends it but draws by point-by-point clicks like a polyline. */ declare class ArcCreateTool extends PolylineCreateTool { /** 0 not started; 1 start set, the pointer sets the point on the arc; 2 point on the arc set, the pointer sets the end. */ private stage; private mid; /** * Creates the arc tool (at least 3 points). * @param docViewer The document viewer the tool works on. * @param annotationPrototype Class of the annotations to create. */ constructor(docViewer: DocumentViewer, annotationPrototype?: AnnotationClass); /** Draws with three clicks (see the file header); the arc measurement tool uses point-by-point clicks instead. */ protected get plain(): boolean; mouseLeftDown(e: PointerEvent): void; mouseMove(e: PointerEvent): void; mouseDoubleClick(e: MouseEvent): void; /** Pointer at p: in step one, a semicircle with start-to-p as diameter (the arc point at the middle of the arc); in step two, p is the end. */ private preview; protected createAnnotation(at: MouseLocation): Annotation$1; } /** ToolNames.LINE: press sets the start, drag to the end. Line endings default to None (defaults.StartLineStyle / EndLineStyle). */ declare class LineCreateTool extends GenericAnnotationCreateTool { /** Values of the draw mode. */ static readonly DrawModes: { /** Press and drag (the default). */ readonly HOLD_TO_DRAW: "holdToDraw"; /** First click starts, second click completes. */ readonly TWO_CLICKS: "twoClicks"; /** Lines only: holding longer than 400 ms before moving draws by dragging, otherwise by two clicks. */ readonly TWO_CLICKS_HOLD_TO_DRAW_HYBRID: "twoClicksHoldToDrawHybrid"; }; /** * Gets the draw mode. * @returns The draw mode. */ getDrawMode(): DrawMode; /** Press-and-drag, two clicks, or both mixed. */ setDrawMode(mode: DrawMode): void; /** * Creates the line tool (no line endings by default). * @param docViewer The document viewer the tool works on. */ constructor(docViewer: DocumentViewer); protected createAnnotation(at: MouseLocation): Annotation$1; protected update(annotation: Annotation$1, _start: unknown, p: { x: number; y: number; }): void; /** Snap mode (a SnapModes value or combination): once set, snaps to the page's vector content both before and while drawing (see tools/snapping.ts). */ getSnapMode(): number | undefined; /** * Sets which points of the page content the line snaps to. * @param mode A snap mode, or several to combine. */ setSnapMode(mode: SnapModes | SnapModes[]): void; } /** ToolNames.ARROW: a line with an open arrow at the end by default (SetLineType). */ declare class ArrowCreateTool extends LineCreateTool { /** * Creates the arrow tool (a line tool with an open arrow at the end). * @param docViewer The document viewer the tool works on. */ constructor(docViewer: DocumentViewer); } /** * ToolNames.CALLOUT: a text box with a callout (FreeText with Intent FreeTextCallout), created with three clicks: * first click the arrow tip, then the knee (moving draws only the leader), finally where the text box goes (moving drags the text box's dashed outline). * The segment from the knee to the text box is horizontal or vertical (the end is at the midpoint of one text box edge and the knee lies perpendicular to that edge): * the text box goes on the side of the knee where the third click deviates most, with its knee-facing edge at the click, centered on the knee. * After adding it is selected without opening the editor (double-click to edit); Esc abandons it. * enableAutoSizedTextBox / disableAutoSizedTextBox only store the switch (the text box size is changed by dragging handles). */ /** * Callback of setTextHandler (called with the tool as this; returns the initial text of a new callout text box). * The d.ts declares Promise but the value is taken synchronously at runtime; a non-string return value (such as a Promise) is treated as unset. */ type CalloutTextHandler = (this: CalloutCreateTool) => string | Promise; declare class CalloutCreateTool extends PolylineCreateTool { private static textHandler; /** Sets the source of the initial text of new callout text boxes (static); with text, inline editing starts right after creation. */ static setTextHandler(handler: CalloutTextHandler): void; /** Content at creation: empty by default (selected, no editor; double-click to edit); when set to non-empty, it is filled in and inline editing starts right away. */ initialText: string; /** * Creates the callout tool: red Helvetica 12pt text, black border and an open arrow at the start of the callout line. * @param docViewer The document viewer the tool works on. */ constructor(docViewer: DocumentViewer); /** Content at creation: from setTextHandler if set (a non-string return counts as unset), otherwise initialText. */ protected text(): string; /** The editor of the text box currently open. */ isEditing(): boolean; /** 0 not started; 1 arrow set, the pointer sets the knee; 2 knee set, the pointer sets the text box. */ private stage; private tip; private knee; /** Press: while editing, only ends editing; the first click sets the arrow (only deselects when something is selected, like FreeText), the second the knee, the third places the text box. */ mouseLeftDown(e: PointerEvent): void; mouseMove(e: PointerEvent): void; mouseLeftUp(e: PointerEvent): void; mouseDoubleClick(e: MouseEvent): void; private tooClose; /** * Text box position in step three: on the side of the knee where the pointer deviates most, with its knee-facing edge at the pointer (at least MIN_GAP from the knee), centered on the knee. * The chosen side must keep the arrow and the knee on the same side of the text box: otherwise try the other side on the same axis, * then the side of the pointer on the perpendicular axis. */ private box; /** Pointer at p: in step one, only the line from the arrow to the pointer; in step two (knee set), the text box's dashed outline follows the pointer. */ private preview; finish(): void; /** Turns on auto-sized text boxes for new callouts (only the setting is stored). */ enableAutoSizedTextBox(): void; /** Turns off auto-sized text boxes for new callouts (only the setting is stored). */ disableAutoSizedTextBox(): void; protected createAnnotation(at: MouseLocation): Annotation$1; } /** ToolNames.RECTANGLE: drag out a rectangle; after setSnapMode both corners snap to the page's vector content. */ declare class RectangleCreateTool extends GenericAnnotationCreateTool { /** * Creates the rectangle tool. * @param docViewer The document viewer the tool works on. * @param annotationPrototype Class of the annotations to create. */ constructor(docViewer: DocumentViewer, annotationPrototype?: AnnotationClass); /** Snap mode (a SnapModes value or combination): once set, snaps to the page's vector content both before and while drawing (see tools/snapping.ts). */ getSnapMode(): number | undefined; /** * Sets which points of the page content the corners snap to. * @param mode A snap mode, or several to combine. */ setSnapMode(mode: SnapModes | SnapModes[]): void; } /** * ToolNames.CROP: drag out a crop box (kept in the tool for display, not added to the document); applyCrop crops by the distances between the box and the page edges (Document.cropPages). * Crop scope: SINGLE_PAGE the page of the box (default), ALL_PAGES all pages, MULTI_PAGE the pages given by setPagesToCrop. Dragging again replaces the box. * Note: the crop box cannot be dragged to adjust it (drag a new one instead). */ type CropMode = 'SINGLE_PAGE' | 'ALL_PAGES' | 'MULTI_PAGE'; declare class CropCreateTool extends RectangleCreateTool { /** Values of the crop mode. */ static readonly CropModes: { /** Crop the page the crop box is on. */ readonly SINGLE_PAGE: "SINGLE_PAGE"; /** Crop all pages. */ readonly ALL_PAGES: "ALL_PAGES"; /** Crop the pages set with setPagesToCrop. */ readonly MULTI_PAGE: "MULTI_PAGE"; }; private cropping; private mode; private pagesToCrop; /** * Creates the page crop tool. * @param docViewer The document viewer the tool works on. */ constructor(docViewer: DocumentViewer); mouseLeftDown(e: PointerEvent): void; /** The box stays in the tool and is not added to the document; boxes that are too small count as accidental clicks. */ finish(): void; /** Crops pages by the distances between the crop box and the page edges, then clears the box. Which pages are cropped depends on the crop mode. Does nothing without a crop box. */ applyCrop(): Promise; /** * Whether a crop box has been drawn and not yet applied or cleared. * @returns True while cropping. */ getIsCropping(): boolean; /** * Gets the crop mode. * @returns The mode; 'SINGLE_PAGE' by default. */ getCropMode(): CropMode; /** * Sets the crop mode. Throws for unknown modes. * @param mode 'SINGLE_PAGE', 'ALL_PAGES' or 'MULTI_PAGE'. */ setCropMode(mode: CropMode): void; /** * Gets the pages cropped in 'MULTI_PAGE' mode. * @returns A copy of the page numbers (1-based). */ getPagesToCrop(): number[]; /** * Sets the pages cropped in 'MULTI_PAGE' mode (the box's page when empty). * @param pages Page numbers (1-based). */ setPagesToCrop(pages: number[]): void; /** Applies the same crop box to these pages (switches to MULTI_PAGE and records the pages). */ multiSelectAnnotations(pageNumbers: number[]): void; /** Removes the crop box. */ reset(): void; } /** ToolNames.DATE_FREETEXT: free text whose content is today's date, formatted YYYY-MM-DD by default (YYYY MM DD HH mm ss supported). */ declare class DateFreeTextCreateTool extends FreeTextCreateTool { private dateFormat; /** * Creates the date free text tool. * @param docViewer The document viewer the tool works on. */ constructor(docViewer: DocumentViewer); protected text(): string; /** * Gets the date format of new date text annotations. * @returns The date format. */ getDateFormat(): string; /** * Sets the date format of new date text annotations. * @param format The date format. */ setDateFormat(format: string): void; } /** ToolNames.ELLIPSE: drag out the bounding rectangle, or two clicks (setDrawMode). */ declare class EllipseCreateTool extends GenericAnnotationCreateTool { /** Values of the draw mode. */ static readonly DrawModes: { /** Press and drag (the default). */ readonly HOLD_TO_DRAW: "holdToDraw"; /** First click starts, second click completes. */ readonly TWO_CLICKS: "twoClicks"; /** Lines only: holding longer than 400 ms before moving draws by dragging, otherwise by two clicks. */ readonly TWO_CLICKS_HOLD_TO_DRAW_HYBRID: "twoClicksHoldToDrawHybrid"; }; /** * Creates the ellipse tool. * @param docViewer The document viewer the tool works on. */ constructor(docViewer: DocumentViewer); /** * Gets the draw mode. * @returns The draw mode. */ getDrawMode(): DrawMode; /** Press-and-drag or two clicks. */ setDrawMode(mode: DrawMode): void; } /** * ToolNames.ERASER: drags a gray eraser trail (20 pt wide by default): * - Ink: on release, paths within half the trail width are erased; touched points are removed and segments crossing the trail are cut, so paths split into pieces; empty ones are deleted and the rest committed once each * - Other annotations: deleted whole as soon as the trail touches them during the drag; lines / polylines / polygons by their segments, others by the four rectangle edges, and points inside filled ones count too (the hit width is 1/3 of the trail width) * erasingAnnotation ({ annotation, skipAnnotation }) fires the first time each annotation is touched; calling skipAnnotation() keeps it. * Form widgets, links, invisible annotations and ones that cannot be modified (canModify) are not erased. * Everything erased in one stroke (press to release) is one undo step: on press the history manager merges subsequent changes into one batch, released after the ink is cut on release. * Erase target (setEraseTarget): 'all' as above; 'ink' erases only ink. Ink erase mode (setEraseMode): 'partial' cuts along the trail; 'whole' deletes the whole ink when touched. */ /** * What the eraser removes: `'all'` erases every annotation the stroke touches; `'ink'` erases only freehand (ink) annotations. * ComPDFKit extension. */ type EraseTarget = 'all' | 'ink'; /** * How the eraser treats ink: `'partial'` removes only the points the stroke touches (splitting the path); `'whole'` deletes each touched ink annotation entirely. * ComPDFKit extension. */ type EraseMode = 'whole' | 'partial'; declare class EraserTool extends GenericAnnotationCreateTool { /** Event names of the eraser tool. */ static readonly Events: { /** 'erasingAnnotation': the eraser touched an annotation for the first time; receives the annotation and a skipAnnotation function that keeps it. */ readonly ERASING_ANNOTATION: "erasingAnnotation"; }; /** Already asked in this stroke (erasingAnnotation fired): ink is cut on release; skipped ones are not erased. */ private touched; private skipped; /** Whether this stroke has the history manager merging (paired with releaseBatch). */ private holding; private target; private mode; /** * Creates the annotation eraser tool (a gray trail 20 pt wide). * @param docViewer The document viewer the tool works on. */ constructor(docViewer: DocumentViewer); /** * Gets which annotations the eraser removes. * ComPDFKit extension. * @returns `'all'` (default) or `'ink'`. */ getEraseTarget(): EraseTarget; /** * Sets which annotations the eraser removes. Other values are ignored. * ComPDFKit extension. * @param target `'all'` erases every annotation the stroke touches; `'ink'` erases only ink annotations. */ setEraseTarget(target: EraseTarget): void; /** * Gets how the eraser treats ink annotations. * ComPDFKit extension. * @returns `'partial'` (default) or `'whole'`. */ getEraseMode(): EraseMode; /** * Sets how the eraser treats ink annotations. Other values are ignored. * ComPDFKit extension. * @param mode `'partial'` removes only the touched points; `'whole'` deletes each touched ink annotation entirely. */ setEraseMode(mode: EraseMode): void; mouseLeftDown(e: PointerEvent): void; mouseMove(e: PointerEvent): void; /** Annotations touched by this segment of the trail: ink is recorded (cut on release), others are deleted whole. */ private eraseAlong; /** Erasable on this page: not widgets or links, visible, modifiable. */ private erasable; mouseLeftUp(e: PointerEvent): void; mouseRightDown(): void; /** The hover cursor is off while erasing. */ switchIn(oldTool?: Tool): void; switchOut(): void; /** Erases ink along the trail, then removes the trail. */ complete(): void; private release; protected createAnnotation(at: MouseLocation): Annotation$1; } /** * ToolNames.FREEHAND: press starts a stroke, move adds points, release ends the stroke. A new stroke on blank space of the same page within createDelay (1000 ms by default) * joins the same annotation (multi-stroke writing) and addAnnotation runs when it expires; with createDelay 0 each stroke is added immediately. * Anything else within the delay (pressing an annotation or outside pages, switching tools, Escape) adds the strokes drawn so far right away, without selecting them. * With setSimplifyPen on, each finished stylus stroke has its path simplified (tolerance 0.75; mouse and finger strokes are not simplified). */ declare class FreeHandCreateTool extends GenericAnnotationCreateTool { private createDelay; private simplifyPen; /** The stroke being drawn (path index in the annotation); -1 between strokes. */ private stroke; private timer; /** * Creates the freehand (ink) tool. * @param docViewer The document viewer the tool works on. */ constructor(docViewer: DocumentViewer); mouseLeftDown(e: PointerEvent): void; mouseMove(e: PointerEvent): void; mouseLeftUp(e: PointerEvent): void; mouseDoubleClick(e: MouseEvent): void; finish(): void; /** Switching away keeps the strokes drawn so far. */ switchOut(): void; /** * Escape while waiting for the next stroke adds the strokes drawn so far right away, without selecting them; other keys work as in the base tool. * @param e The keyboard event. */ keyDown(e: KeyboardEvent): void; /** Ended by another action before the delay expires: adds the strokes drawn so far without selecting them. */ private finishEarly; protected createAnnotation(at: MouseLocation): Annotation$1; /** * Gets how long a finished stroke waits for further strokes before the annotation is added. * @returns The delay in milliseconds; 1000 by default. */ getCreateDelay(): number; /** * Sets how long a finished stroke waits for further strokes on the same page to join the same annotation; 0 adds each stroke immediately. * @param ms The delay in milliseconds. */ setCreateDelay(ms: number): void; /** * Whether strokes drawn with a pen are simplified. * @returns True when pen strokes are simplified. */ getSimplifyPen(): boolean; /** * Sets whether strokes drawn with a pen (not mouse or touch) are simplified when finished. * @param simplify Whether to simplify pen strokes. */ setSimplifyPen(simplify: boolean): void; } /** * ToolNames.FREEHAND_HIGHLIGHT: thick, translucent ink (Opacity 0.5 and width 20 by default) with intent InkHighlight, multiplied with the page. * When a stroke is finished and all points are within autoSmoothingRange (30 by default) above or below the first point, it is straightened into a horizontal line (average y); * otherwise, when all are within that range left or right, into a vertical line (average x). */ declare class FreeHandHighlightCreateTool extends FreeHandCreateTool { private autoSmoothingRange; /** * Creates the freehand highlighter tool (20 pt wide, opacity 0.5). * @param docViewer The document viewer the tool works on. */ constructor(docViewer: DocumentViewer); protected createAnnotation(at: MouseLocation): Annotation$1; /** * Gets the range within which a finished stroke is straightened into a horizontal line. * @returns The range in PDF points; 30 by default. */ getAutoSmoothingRange(): number; /** * Sets the range within which a finished stroke is straightened: when all points are within this distance above or below the first point, the stroke becomes a horizontal line. * @param range The range in PDF points. */ setAutoSmoothingRange(range: number): void; } /** ToolNames.POLYGON: like the polyline, and clicking back on the first vertex (within 8px on screen) also closes and completes it. */ declare class PolygonCreateTool extends PolylineCreateTool { /** * Creates the polygon tool (at least 3 vertices). * @param docViewer The document viewer the tool works on. */ constructor(docViewer: DocumentViewer); } /** * ToolNames.POLYGON_CLOUD: polygon + cloudy border (SetBorderEffect). */ declare class PolygonCloudCreateTool extends PolygonCreateTool { protected createAnnotation(at: MouseLocation): Annotation$1; } /** * ToolNames.SNIPPING: drag out a snip box (kept in the tool for display); applySnipping renders that area at the current zoom, including annotations: * CLIPBOARD (default) writes to the clipboard, DOWNLOAD downloads a PNG (file name from setFilenameHandler, snip by default), * CROP_AND_REMOVE crops this page to the box and deletes other pages. Afterwards snippingApplied fires (page number and distances from the box to the page edges). * The snip box is not an annotation: when drawing finishes the tool fires annotationAdded, and when the box is removed it fires snippingCancelled. * Since the box stays in the tool and is not added to the document, the tool fires these two itself (the UI layer opens / closes the snipping overlay from them): * annotationAdded (argument: the snip box) fires when drawing finishes and the box is large enough; snippingCancelled fires when the box is cleared without being applied (redraw, Esc, tool switch, reset); applying does not fire it. * A finished box acts like a selected rectangle: drag the 8 handles to resize, drag inside to move (staying in the page), press outside to clear and redraw; each adjustment fires snippingChanged on release (argument: the snip box), * so the UI can reposition its overlay. The viewer draws the box like a selected annotation (selectedDraft, 1px border and 7px handles; the border is the snip area itself, without padding). */ type SnippingMode = 'CLIPBOARD' | 'DOWNLOAD' | 'CROP_AND_REMOVE'; declare class SnippingCreateTool extends RectangleCreateTool { /** Values of the snipping mode. */ static readonly SnippingModes: { /** Copy the snipped area to the clipboard as PNG. */ readonly CLIPBOARD: "CLIPBOARD"; /** Download the snipped area as a PNG file. */ readonly DOWNLOAD: "DOWNLOAD"; /** Crop the page to the snip box and remove all other pages. */ readonly CROP_AND_REMOVE: "CROP_AND_REMOVE"; }; /** Event names of the snipping tool. */ static readonly Events: { /** 'snippingApplied': the snip was applied; receives the page number and the distances from the box to the page edges. */ readonly SNIPPING_APPLIED: "snippingApplied"; /** 'snippingCancelled': the snip box was cleared without being applied. */ readonly SNIPPING_CANCELLED: "snippingCancelled"; /** 'snippingChanged': the snip box was moved or resized; receives the box. */ readonly SNIPPING_CHANGED: "snippingChanged"; }; private snipping; private mode; /** Dragging a handle (handle) or moving the whole box (handle null): the pointer and box at press time. */ private adjust; /** File name for download (without .png). */ static setFilenameHandler(handler: () => Promise): void; /** * Creates the snipping tool. * @param docViewer The document viewer the tool works on. */ constructor(docViewer: DocumentViewer); /** The finished box (for the viewer's selection box); null when there is no box or it is still being drawn. */ get selectedDraft(): Annotation$1 | null; /** Whether a page coordinate is on a box handle (handle) or inside the box (handle null); null outside. Grab areas are the same as handles of selected annotations. */ private hitAt; mouseLeftDown(e: PointerEvent): void; mouseMove(e: PointerEvent): void; mouseLeftUp(e: PointerEvent): void; finish(): void; /** Applies the snip box by the snipping mode: copies the rendered area to the clipboard, downloads it as PNG, or crops the page to the box and removes the other pages. Then fires snippingApplied. Does nothing without a snip box. */ applySnipping(): Promise; /** * Whether a snip box has been drawn and not yet applied or cleared. * @returns True while snipping. */ getIsSnipping(): boolean; /** * Gets the snipping mode. * @returns The mode; 'CLIPBOARD' by default. */ getSnippingMode(): SnippingMode; /** * Sets the snipping mode. * @param mode 'CLIPBOARD', 'DOWNLOAD' or 'CROP_AND_REMOVE'. */ setSnippingMode(mode: SnippingMode): void; /** Clears the snip box (fires snippingCancelled when one was drawn). */ reset(): void; } /** ToolNames.MARQUEE: drag out a box to zoom so the box fills the viewport, centered. Only changes the viewport; no commands. */ /** Zoom function for a click: current zoom → new zoom. */ type ZoomHandler = (currentZoomLevel: number) => number; declare class MarqueeZoomTool extends Tool { private static minZoom; private static maxZoom; /** Maximum zoom of marquee zoom (static; UI.setMaxZoomLevel calls it). */ static setMaxZoomLevel(zoomLevel: number): void; /** Minimum zoom of marquee zoom (static; UI.setMinZoomLevel calls it). */ static setMinZoomLevel(zoomLevel: number): void; private static zoomHandler; /** Sets the zoom for a click without dragging: takes the current zoom and returns the zoom after the click (kept between the minimum and maximum); none by default, so a click does nothing. */ static setZoomHandler(func: ZoomHandler | null): void; private start; private box; cursor: string; /** The hover cursor is off during marquee zoom. */ switchIn(oldTool?: Tool): void; mouseLeftDown(e: PointerEvent): void; mouseMove(e: PointerEvent): void; mouseLeftUp(e: PointerEvent): void; switchOut(newTool?: Tool): void; private clear; /** Coordinates relative to the viewer element (DisplayMode window coordinates). */ private windowPoint; } declare class ArcMeasurementCreateTool extends ArcCreateTool { /** Measurement info for measurement annotations created afterwards (with no scale nothing is drawn and createAnnotationWithNoScale fires). */ Measure: MeasureData; /** * Creates the arc measurement tool. * @param docViewer The document viewer the tool works on. */ constructor(docViewer: DocumentViewer); /** Clicks point by point (the arc tool itself draws nothing); the third point completes it. */ mouseLeftDown(e: PointerEvent): void; /** * Gets the result text options of new arc measurements. * @returns A copy of the display options. */ getDefaultMeasurementDisplayOptions(): MeasurementDisplayOptions; /** Changes only the given keys (inapplicable ones are ignored); measurement annotations created afterwards carry them. */ setDefaultMeasurementDisplayOptions(options: MeasurementDisplayOptions): void; protected createAnnotation(at: MouseLocation): Annotation$1; } /** ToolNames.PERIMETER_MEASUREMENT: draws a polyline point by point to measure total length (RulerType.kPerimeter). */ declare class PerimeterMeasurementCreateTool extends PolylineCreateTool { /** Measurement info for measurement annotations created afterwards (with no scale nothing is drawn and createAnnotationWithNoScale fires). */ Measure: MeasureData; /** * Creates the perimeter measurement tool. * @param docViewer The document viewer the tool works on. * @param annotationPrototype Class of the annotations to create. */ constructor(docViewer: DocumentViewer, annotationPrototype?: AnnotationClass); mouseLeftDown(e: PointerEvent): void; protected createAnnotation(at: MouseLocation): Annotation$1; } declare class AreaMeasurementCreateTool extends PerimeterMeasurementCreateTool { Measure: MeasureData; /** * Creates the polygon area measurement tool (at least 3 vertices). * @param docViewer The document viewer the tool works on. */ constructor(docViewer: DocumentViewer); /** * Gets the caption options of new area measurements. * @returns A copy of the caption options. */ getDefaultMeasurementCaptionOptions(): MeasurementCaptionOptions; /** * Changes the caption options of new area measurements (merged into the current options). * @param options The options to change. */ setDefaultMeasurementCaptionOptions(options: MeasurementCaptionOptionsInput): void; /** * Gets the result text options of new area measurements. * @returns A copy of the display options. */ getDefaultMeasurementDisplayOptions(): MeasurementDisplayOptions; /** Changes only the given keys (inapplicable ones are ignored); measurement annotations created afterwards carry them. */ setDefaultMeasurementDisplayOptions(options: MeasurementDisplayOptions): void; protected createAnnotation(at: MouseLocation): Annotation$1; } /** * ToolNames.DISTANCE_MEASUREMENT: draws a line to measure distance (RulerType.kDistance), with open arrows at both ends by default. * Scale and precision come from Measure (set by MeasurementManager); the engine recomputes the result and generates an appearance with the result text. * New lines carry the leader lines from setLeaderLineDefaultOptions (setLeadLength and so on). The imperial tick switches are deprecated: they set the precision to 1/8 / 0.1. */ interface LeaderLineOptions { leaderLineLength: number; leaderLineOffset: number; leaderLineExtension: number; } declare class DistanceMeasurementCreateTool extends LineCreateTool { /** Measurement info for measurement annotations created afterwards (with no scale nothing is drawn and createAnnotationWithNoScale fires). */ Measure: MeasureData; protected imperialMarks: boolean; /** * Creates the distance measurement tool (open arrows at both ends). * @param docViewer The document viewer the tool works on. */ constructor(docViewer: DocumentViewer); mouseLeftDown(e: PointerEvent): void; protected createAnnotation(at: MouseLocation): Annotation$1; /** Deprecated (inches and feet-inches can use fractional precisions such as 1/8 directly): sets the precision to 1/8. */ enableImperialMarks(): void; /** Deprecated: sets the precision to 0.1. */ disableImperialMarks(): void; /** * Gets the leader line options of new distance measurements. * @returns A copy of the options. */ getLeaderLineDefaultOptions(): LeaderLineOptions; /** * Changes the leader line options of new distance measurements. * @param options The options to change. */ setLeaderLineDefaultOptions(options: Partial): void; } /** * ToolNames.CALIBRATION_MEASUREMENT: measures a segment of known length to derive the scale. It draws a measurement line without arrows (default scale 1 in = 1 in, not a measurement item) * and selects it when done; the caller computes the scale from its length (Measure.value) and the real length, then calls MeasurementManager.createAndApplyScale. */ declare class CalibrationMeasurementTool extends DistanceMeasurementCreateTool { Measure: MeasureData; /** * Creates the scale calibration tool. * @param docViewer The document viewer the tool works on. */ constructor(docViewer: DocumentViewer); finish(): void; } /** ToolNames.RECTANGULAR_AREA_MEASUREMENT: drag out a rectangle (a four-vertex polygon) to measure area, or two clicks (setDrawMode). */ declare class RectangularAreaMeasurementCreateTool extends AreaMeasurementCreateTool { /** Values of the draw mode. */ static readonly DrawModes: { /** Press and drag (the default). */ readonly HOLD_TO_DRAW: "holdToDraw"; /** First click starts, second click completes. */ readonly TWO_CLICKS: "twoClicks"; /** Lines only: holding longer than 400 ms before moving draws by dragging, otherwise by two clicks. */ readonly TWO_CLICKS_HOLD_TO_DRAW_HYBRID: "twoClicksHoldToDrawHybrid"; }; /** Dragging a rectangle: press creates, move changes the four vertices, release completes (no point-by-point clicks); in two-click mode the second press completes. */ mouseLeftDown(e: PointerEvent): void; mouseMove(e: PointerEvent): void; mouseLeftUp(e: PointerEvent): void; mouseDoubleClick(): void; protected createAnnotation(at: MouseLocation): Annotation$1; /** * Gets the draw mode. * @returns The draw mode. */ getDrawMode(): DrawMode; /** Press-and-drag or two clicks. */ setDrawMode(mode: DrawMode): void; } /** ToolNames.CLOUDY_RECTANGULAR_AREA_MEASUREMENT: rectangular area with a cloudy border. */ declare class CloudyRectangularAreaMeasurementCreateTool extends RectangularAreaMeasurementCreateTool { protected createAnnotation(at: MouseLocation): Annotation$1; } /** * ToolNames.STICKY: immediate placement by default. Draft mode keeps the real note on * the tool for the existing page renderer/editor; only nonempty completion writes it. */ declare class StickyCreateTool extends AnnotationSelectTool { private creationOverAnnotation; /** The actual uncommitted note, also consumed by DocumentViewer's draft renderer. */ annotation: StickyAnnotation | null; private draftDocument; private readonly abortDraft; private readonly onDraftPermissionChanged; /** * Creates the sticky note tool (yellow Comment icon by default). * @param docViewer The document viewer the tool works on. */ constructor(docViewer: DocumentViewer); cursor: string; mouseLeftDown(): void; mouseMove(): void; mouseLeftUp(e: PointerEvent): void; /** Add the same note exactly once; blank/cancelled/stale drafts never enter AM or history. */ commitDraft(): Promise; /** End ownership synchronously, before any write/events can reenter the editor. */ cancelDraft(): void; switchOut(next?: Tool): void; keyDown(e: KeyboardEvent): void; /** Lets a click on an existing annotation create a note. */ enableCreationOverAnnotation(): void; /** A click on an existing annotation does not create a note (the default). */ disableCreationOverAnnotation(): void; /** Turns on view state saving for new notes (only the setting is stored). */ enableViewStateSaving(): void; /** Turns off view state saving for new notes (only the setting is stored). */ disableViewStateSaving(): void; } /** ToolNames.COUNT_MEASUREMENT: a click places a count marker (a note with the Check icon, RulerType.kCount, getCountResult). */ declare class CountMeasurementCreateTool extends StickyCreateTool { /** Measurement info for measurement annotations created afterwards (with no scale nothing is drawn and createAnnotationWithNoScale fires). */ Measure: MeasureData; /** * Creates the count measurement tool (Check icon by default). * @param docViewer The document viewer the tool works on. */ constructor(docViewer: DocumentViewer); } /** * ToolNames.CURVE_MEASUREMENT: curve measurement: click the start, move (a straight line at first), click the end to create it; * it is then selected, and dragging the two middle control points bends the line into a cubic Bézier; the length is written to the result text by scale. Press-and-drag also works (same drawing choices as line measurement). * Nothing is drawn without a scale (createAnnotationWithNoScale fires). */ declare class CurveMeasurementCreateTool extends GenericAnnotationCreateTool { /** Values of the draw mode. */ static readonly DrawModes: { /** Press and drag (the default). */ readonly HOLD_TO_DRAW: "holdToDraw"; /** First click starts, second click completes. */ readonly TWO_CLICKS: "twoClicks"; /** Lines only: holding longer than 400 ms before moving draws by dragging, otherwise by two clicks. */ readonly TWO_CLICKS_HOLD_TO_DRAW_HYBRID: "twoClicksHoldToDrawHybrid"; }; /** Measurement info for measurement annotations created afterwards (with no scale nothing is drawn and createAnnotationWithNoScale fires). */ Measure: MeasureData; /** * Creates the curve measurement tool (two clicks or press and drag). * @param docViewer The document viewer the tool works on. */ constructor(docViewer: DocumentViewer); /** * Gets the draw mode. * @returns The draw mode. */ getDrawMode(): DrawMode; /** * Sets the draw mode. * @param mode The draw mode. */ setDrawMode(mode: DrawMode): void; mouseLeftDown(e: PointerEvent): void; protected createAnnotation(at: MouseLocation): Annotation$1; protected update(annotation: Annotation$1, start: { x: number; y: number; }, p: { x: number; y: number; }): void; } declare class EllipseMeasurementCreateTool extends EllipseCreateTool { /** Measurement info for measurement annotations created afterwards (with no scale nothing is drawn and createAnnotationWithNoScale fires). */ Measure: MeasureData; mouseLeftDown(e: PointerEvent): void; /** The result follows while dragging. */ mouseMove(e: PointerEvent): void; /** * Gets the caption options of new ellipse measurements. * @returns A copy of the caption options. */ getDefaultMeasurementCaptionOptions(): MeasurementCaptionOptions; /** * Changes the caption options of new ellipse measurements (merged into the current options). * @param options The options to change. */ setDefaultMeasurementCaptionOptions(options: MeasurementCaptionOptionsInput): void; /** * Gets the result text options of new ellipse measurements. * @returns A copy of the display options. */ getDefaultMeasurementDisplayOptions(): MeasurementDisplayOptions; /** Changes only the given keys (inapplicable ones are ignored); measurement annotations created afterwards carry them. */ setDefaultMeasurementDisplayOptions(options: MeasurementDisplayOptions): void; protected createAnnotation(at: MouseLocation): Annotation$1; } declare class PanTool extends AnnotationSelectTool { private pan; /** Pressed pointers (client coordinates). */ private readonly pointers; private gesture; /** Hand cursor for panning (CSS grab / grabbing). */ cursor: string; switchOut(): void; mouseLeftDown(e: PointerEvent): void; mouseMove(e: PointerEvent): void; mouseLeftUp(e: PointerEvent): void; /** * Whether the view is being panned (by mouse drag or a touch pan). * @returns True while panning. */ isPanning(): boolean; /** * Whether a two-finger pinch is in progress. * @returns True while pinching. */ isPinching(): boolean; private startGesture; private moveGesture; } /** * ToolNames.RUBBER_STAMP: setRubberStamp picks a stamp to place once, useStamp keeps placing that one; the preview follows the pointer * (the preview of a standard stamp is its real appearance at natural size, rendered by the Worker on a blank document) and a click places it (addStamp). * - Standard stamps: getDefaultStamps / get/setStandardStamps (image URLs are accepted too and become image stamps) / getStandardStampAnnotations * - Custom stamps: get/setCustomStamps addCustomStamp deleteCustomStamps; createCustomStampAnnotation draws an image stamp on a canvas with drawCustomStamp * (without a canvas it falls back to the engine's text stamp, whose background is only white / red / green / blue); the subtitle fills in the date by moment format and $currentUser becomes the current user * - Document stamps: setDocumentStamps turns pages of another PDF into stamps (note: rendered as images, not vector appearances) * - setStampScaleFactor scales on placement; setCustomDrawFunction draws on the stamp image before placement (the stamp becomes an image stamp); getPreview draws a preview image */ /** Custom stamp (CustomStampData). */ interface CustomStamp { id?: string; title: string; subtitle?: string; color?: Color | string; textColor?: Color | string; font?: string; bold?: boolean; italic?: boolean; underline?: boolean; strikeout?: boolean; category?: string; } /** Source and options of document stamps: pages default to all pages, cropVisibleContent defaults to true (crops the surrounding blank space). */ interface DocumentStampSource { source: DocumentSource; title?: string; filename?: string; extension?: string; pages?: number[]; cropVisibleContent?: boolean; } interface DocumentStampOptions { pages?: number[]; cropVisibleContent?: boolean; } interface DocumentStampsResult { registeredCount: number; failures: Array<{ title: string; reason: Error; }>; pageSuccesses: Array<{ title: string; pageNumber: number; }>; pageFailures: Array<{ title: string; pageNumber: number; reason: Error; }>; } declare class RubberStampCreateTool extends AnnotationSelectTool { /** Event names of the rubber stamp tool. */ static readonly Events: { /** 'annotationAdded': a stamp was placed. */ readonly ANNOTATION_ADDED: "annotationAdded"; /** 'stampsUpdated': the standard, custom or document stamps changed. */ readonly STAMPS_UPDATED: "stampsUpdated"; /** 'customStampsDeleted': custom stamps were deleted; receives the deleted stamps. */ readonly CUSTOM_STAMPS_DELETED: "customStampsDeleted"; }; /** Default background colors of custom stamps. */ static readonly FILL_COLORS: string[]; /** Default text colors of custom stamps. */ static readonly TEXT_COLORS: string[]; /** Date format choices for custom stamp subtitles. */ static readonly TIMESTAMP_CHOICHES: { /** Choice id. */ id: string; /** Date format of the subtitle ('other' for a custom format). */ value: string; }[]; /** Preview following the pointer (not added to the document). */ annotation: Annotation$1 | null; /** Placement position (set by mouseLeftUp; can also be set before calling addStamp). */ location: { /** Page number (1-based). */ pageNumber: number; /** X of the stamp center in PDF points. */ x: number; /** Y of the stamp center in PDF points. */ y: number; } | null; private stamp; /** Set by useStamp: keep placing the same one after placement. */ private repeat; private standardStamps; private customStamps; private scaleFactor; private customDraw; private preview; private previewLoading; private templates; private registration; cursor: string; switchOut(newTool?: Tool): void; /** Built-in standard stamp names. */ getDefaultStamps(): string[]; /** * Gets the standard stamp names offered by the tool. * @returns A copy of the stamp names. */ getStandardStamps(): string[]; /** Standard stamp names, or image URLs (http(s) / data:, made into image stamps); unknown names are removed. */ setStandardStamps(stamps: string[]): void; /** One StampAnnotation (not placed) per standard stamp: Icon is the stamp name for standard stamps; image URLs become image stamps; document stamps follow. */ getStandardStampAnnotations(): Promise; /** A click then places this stamp (once). */ setRubberStamp(annotation: Annotation$1, text?: string): Promise; /** Keeps placing this stamp (Icon is a standard stamp name, or give a StampAnnotation) until another is chosen. */ useStamp(stamp: { /** Standard stamp name. */ Icon?: string; /** Fill color; black by default. */ FillColor?: Color; /** Width in PDF points; 0 (natural size) by default. */ Width?: number; /** Height in PDF points; 0 (natural size) by default. */ Height?: number; /** Opacity from 0 to 1; 1 by default. */ Opacity?: number; } | StampAnnotation): void; /** No stamp chosen (the current one is not a StampAnnotation). */ isEmptyStamp(): boolean; /** Width and height are multiplied by this on placement (1 by default; must be positive). */ setStampScaleFactor(factor: number): void; /** Draws on the stamp image before placement (callback(ctx, annotation?)); the placed stamp becomes an image stamp. */ setCustomDrawFunction(callback: (ctx: CanvasRenderingContext2D, annotation?: Annotation$1) => void): void; /** The preview follows the pointer: standard stamps draw their real appearance at natural size; when the appearance is not fetched yet, fetch it and draw when it arrives. */ /** * With a stamp pending, a press places the stamp: pressing another annotation neither selects nor drags it; without a pending stamp, pressing an existing annotation selects and drags it as usual. */ mouseLeftDown(e: PointerEvent): void; mouseMove(e: PointerEvent): void; mouseLeftUp(e: PointerEvent): void; /** Places the current stamp at location (centered on it; multiplied by setStampScaleFactor; drawn with setCustomDrawFunction first if set). */ addStamp(): Promise; /** Draws the stamp's current appearance into a canvas, then lets the setCustomDrawFunction function draw; the result becomes the image. */ private applyCustomDraw; /** Draws a preview image (dataURL): the stamp is fitted proportionally into canvasWidth × canvasHeight (getPreview). */ getPreview(annotation: Annotation$1, parameters: { /** Width of the preview image in pixels. */ canvasWidth: number; /** Height of the preview image in pixels. */ canvasHeight: number; /** Replaces the text of a text stamp before drawing. */ text?: string; /** 'rtl' aligns the stamp to the right of the image; left by default. */ direction?: 'ltr' | 'rtl'; }): Promise; /** Shows the preview at the last pointer position (showPreview; our preview is drawn on the annotation layer). */ showPreview(): Promise; /** Removes the preview that follows the pointer. */ hidePreview(): void; private movePreview; /** Preview of standard stamps and text stamps (dynamic stamps) at the current zoom level; fetched when missing (drawn on the next move after it arrives); the old preview of the same stamp stands in until the new one arrives. */ private currentPreview; /** * Gets the custom stamps. * @returns A copy of the custom stamp list. */ getCustomStamps(): CustomStamp[]; /** Fills in id and category for each (default 'Custom Stamp'). */ setCustomStamps(stamps: CustomStamp[]): void; /** * Adds a custom stamp (filling in defaults for missing fields) and fires stampsUpdated. * @param stamp The custom stamp. */ addCustomStamp(stamp: CustomStamp): void; /** Deletes by object reference (pass the objects from getCustomStamps); missing ones log a warning. */ deleteCustomStamps(stamps: CustomStamp[]): void; /** * Creates a stamp annotation for each custom stamp. * @returns The stamp annotations, not added to the document. */ getCustomStampAnnotations(): Promise; /** Custom stamp → image stamp (drawn by drawCustomStamp; width and height are half the canvas, in pt); falls back to the engine text stamp without a canvas. */ createCustomStampAnnotation(stamp: CustomStamp): Promise; /** * Draws a custom stamp on canvas: a rounded background box, the title (smaller font when it does not fit), and the subtitle below when present (a date in moment format, * with $currentUser replaced by the current user). Returns the stamp width (half the canvas pixels). */ drawCustomStamp(options: CustomStamp & { /** Canvas to draw on; a new canvas when omitted. */ canvas?: HTMLCanvasElement; /** Minimum stamp width (half the canvas pixels); 300 by default. */ width?: number; /** Stamp height (half the canvas pixels); 100 by default. */ height?: number; /** Element whose width limits the title width; 520 pixels when omitted. */ canvasParent?: HTMLElement; }): number; /** Subtitle: $currentUser becomes the current user (display name), then the date is filled in by moment format. */ private subtitleText; /** * Registers pages of another PDF as stamps (calling again replaces the previous registration). Note: each page is rendered as an image (at DOCUMENT_STAMP_SCALE), * not a vector appearance; with cropVisibleContent the surrounding blank space (white or transparent) is cropped. */ setDocumentStamps(sources: DocumentStampSource[], options?: DocumentStampOptions): Promise; /** Removes all document stamps and fires stampsUpdated. */ clearDocumentStamps(): void; /** Input of the last setDocumentStamps (a copy). */ getDocumentStampRegistration(): { /** The registered stamp sources. */ sources: DocumentStampSource[]; /** The registration options. */ options?: DocumentStampOptions; }; /** label is "title page". */ hasDocumentStampLabel(label: string): boolean; private documentStampAnnotations; } /** * ToolNames.SIGNATURE: hand-drawn signatures (FreeHandAnnotation) or image signatures (StampAnnotation). * - Signature pad: setSignatureCanvas binds a to write on with the pointer; strokes are recorded in canvas pixels in an ink annotation * (drawn on the canvas at 3× the line width); clearSignatureCanvas clears it, resizeCanvas resets the pixel size to the canvas display size and scales the strokes along. * - Size on the page: hand-drawn signatures scale so that "the canvas height is 30 pt" (canvas height 144 without a pad); image signatures are at most 30 pt tall and never enlarged; * then multiplied by setSignatureScaleFactor. setDefaultSignatureOptions (deprecated) gives the maximum side length. * - The preview follows the pointer (showPreview / hidePreview); a click places a copy with Subject Signature. * Without a signature set, a click only records the position and fires locationSelected; after the UI gets a signature it calls addSignature. * - Signature fields: when an empty signature field is clicked, DocumentViewer hands the position here (firing locationSelected [position, field]) and the signature then goes to that field: * annotation mode (default) places a signature annotation scaled into the field and associates it; appearance mode draws the signature as the field appearance (SigningModes). * - Saved signatures (saveSignatures ...) live only in memory; exportSignatures exports strokes (or XFDF) and image dataURLs, importSignatures reads them back. * Note: signatures are not turned by page rotation. XFDF coordinates are flipped by the height of the page the signature annotation is on (792 without a document). */ /** How to sign a signature field: annotation mode places a signature annotation and associates it; appearance mode draws it as the field appearance. */ declare enum SigningModes { ANNOTATION = "annotation", APPEARANCE = "appearance" } /** Signatures accepted by setSignature / importSignatures: ink or image annotations, strokes (canvas pixels), image dataURLs, ink XFDF. */ type SignatureSource = Annotation$1 | Array> | string | null; /** Callback of setTextHandler (SignatureCreateTool.TextHandler). */ type SignatureTextHandler = (this: SignatureCreateTool) => string; declare class SignatureCreateTool extends Tool { /** Signing modes of signature fields (same as the SigningModes enum). */ static readonly SigningModes: typeof SigningModes; /** Event names of the signature tool. */ static readonly Events: { /** 'locationSelected': a position or an empty signature field was clicked without a signature to place; receives the position and the field (or null). */ readonly LOCATION_SELECTED: "locationSelected"; /** 'signatureReady': a signature annotation was created for placing; receives the annotation and its position. */ readonly SIGNATURE_READY: "signatureReady"; /** 'annotationAdded': a signature annotation was added to the document. */ readonly ANNOTATION_ADDED: "annotationAdded"; /** 'signatureDeleted': a saved signature was deleted; receives the signature and its index. */ readonly SIGNATURE_DELETED: "signatureDeleted"; /** 'signatureSaved': signatures were saved; receives the saved signatures. */ readonly SIGNATURE_SAVED: "signatureSaved"; /** 'fileRejected': setSignature rejected a file larger than ACCEPTED_FILE_SIZE; receives the reason, the limit and the file size. */ readonly FILE_REJECTED: "fileRejected"; }; private static signHereHandler; /** * Sets the source of the "Sign here" text (static; handler is called with the tool as this and returns the label text on signature fields). * When unset, DocumentViewer draws the default "SIGN HERE" label. */ static setTextHandler(textHandler: SignatureTextHandler): void; /** setSignature rejects a file whose given size exceeds this (bytes) and fire fileRejected; null means no limit. */ ACCEPTED_FILE_SIZE: number | null; defaults: Record; /** Where the next signature goes (recorded when clicking a signature field or the page); cleared after addSignature uses it. */ location: MouseLocation | null; /** The field, when location comes from a signature field. */ private locationWidget; private signingMode; /** Preview following the pointer (not added to the document). */ annotation: Annotation$1 | null; private signature; private pad; private saved; private scale; private maxSize; /** Whether the preview follows the pointer and a click places the signature. */ private previewing; cursor: string; switchOut(newTool?: Tool): void; /** Sets the full signature: an ink annotation (strokes, color and width copied), an image annotation or dataURL (image signature), or a stroke array; null clears it. */ setSignature(signature: SignatureSource, fileSize?: number): Promise; /** * Gets the full signature set with setSignature or drawn on the signature pad. * @returns The signature annotation, or null when none. */ getFullSignatureAnnotation(): Annotation$1 | null; /** * Whether there is no usable signature: no signature, an ink signature without strokes, or an image signature without image, text or icon. * @returns True when the signature is empty. */ isEmptySignature(): Promise; /** Binds the signature pad: press and move on the canvas to write a stroke, release to end it; strokes are added to the current full signature (a new ink when there is none or it is an image). */ setSignatureCanvas(canvas: HTMLCanvasElement): void; /** Clears the pad and the corresponding signature. */ clearSignatureCanvas(): void; /** Call after the pad's display size changes: the pixel size becomes the display size, and existing strokes are scaled proportionally and redrawn. */ resizeCanvas(): Promise; /** Preview image of the signature (dataURL): hand-drawn signatures are drawn at the pad's height and the signature's width; image signatures are the image itself. */ getPreview(annotation: Annotation$1): Promise; /** * Sets the factor by which signatures are scaled when placed on the page. Values that are not positive are ignored with a warning. * @param scale The scale factor; 1 by default. */ setSignatureScaleFactor(scale: number): void; /** @deprecated Use setSignatureScaleFactor. Maximum side length (pt) of signatures placed on the page. */ setDefaultSignatureOptions(options: { /** Maximum side length of placed signatures in PDF points. */ maximumDimensionSize?: number; }): void; /** Previews the signature as the pointer moves; a click places it. */ showPreview(): Promise; /** Stops the preview following the pointer and removes it; clicks then only record the position. */ hidePreview(): void; /** * Gets how signature fields are signed. * @returns The signing mode; ANNOTATION by default. */ getSigningMode(): SigningModes; /** * Sets how signature fields are signed. Throws for unknown modes. * @param mode The signing mode. */ setSigningMode(mode: SigningModes): void; /** * Whether a position (or signature field) for the next signature has been recorded. * @returns True when a location is recorded. */ hasLocation(): boolean; /** Clears the recorded position and signature field. */ clearLocation(): void; /** Places the full signature: on the recorded signature field if any, at the recorded position if any, otherwise in the middle of the current page. */ addSignature(): Promise; /** * Adds signatures to the saved signatures (kept in memory only) and fires signatureSaved. * @param signatures A signature annotation or an array of them. */ saveSignatures(signatures: Annotation$1 | Annotation$1[]): void; /** * Gets the saved signatures. * @returns A copy of the saved signature list. */ getSavedSignatures(): Annotation$1[]; /** * Deletes a saved signature and fires signatureDeleted. * @param index Zero-based index in the saved signatures. */ deleteSavedSignature(index: number): void; /** Deletes all saved signatures, firing signatureDeleted for each. */ deleteAllSavedSignatures(): void; /** Exports saved signatures: strokes for hand-drawn ones (ink XFDF when pathsOnly is false), dataURLs for images. */ exportSignatures(pathsOnly?: boolean): Promise>; /** Reads back the result of exportSignatures (one item or an array; each strokes, an image dataURL or ink XFDF) into the saved signatures. */ importSignatures(data: string | Array>>): Promise; mouseMove(e: PointerEvent): void; /** Places the previewed signature at the click; without one, records the position and fires locationSelected (the UI gets a signature, then calls addSignature). */ mouseLeftUp(e: PointerEvent): void; /** Any source → a new signature annotation (the input is not changed). */ private toSignature; private inkSignature; private imageSignature; private applyDefaults; private bindCanvas; /** Redraws the pad: clears it and draws the current signature's strokes at 3× the line width. */ private drawCanvas; /** Pixel height of the signature pad (144 without a pad): hand-drawn signatures scale so that it maps to 30 pt. */ private canvasHeight; private createCanvas; /** * Signs a signature field: the signature is turned by the field's own rotation (/MK /R), not by page or view rotation, since field content is already oriented by /MK /R; * scaled proportionally to fit in the field, aligned to the start edge in the field's orientation and centered across (0° left, 90° bottom, 180° right, 270° top). * Annotation mode adds the signature annotation and associates it; appearance mode draws it as the field appearance. * emit true is the signature tool's own flow (fires events); false is signWidgetWith (no events, replaces the associated signature). */ private fitIntoWidget; private place; /** Copy of the signature: centered at at, at its size on the page, moved into the page. */ private copyAt; /** * The page is shown turned by q × 90° (page /Rotate plus view rotation): the signature is turned back q × 90° counterclockwise within the page so it is upright on screen. * Ink rotates its strokes around the bounding box center; images rotate pixels, swap width and height, and add 90q to Rotation; then it is moved into the page. */ private turnUpright; /** Turns the signature q × 90° counterclockwise within the page (ink rotates strokes; images rotate pixels, swap width and height, add 90q to Rotation), then moves it into the page. */ private turn; /** Size on the page: ink maps the pad height to 30 pt; images are at most 30 pt tall and never enlarged; scaled down to the maximum side length when larger; then multiplied by the scale factor. */ private placedSize; private exportOne; private importAll; /** Height of page pageNumber: XFDF coordinates are PDF coordinates (bottom-left origin) and are flipped by it; page 1 when that page does not exist, 792 without a document. */ private xfdfPageHeight; /** Hand-drawn signature → XFDF with a single ink element on the signature annotation's own page (the annotation is exported as usual; signatures from the pad are on page 1). */ private inkToXfdf; /** Ink XFDF → hand-drawn signature (strokes, color and width of the first ink element). */ private inkFromXfdf; private clearPreview; } /** * ToolNames.STAMP: after a click, pick an image (file picker) and place it as an image stamp at the click, scaled to fit 200 pt square by its aspect ratio and centered on the click. * pickImage can be overridden (for example to take the image from the clipboard or your own dialog); it returns a dataURL, null means cancelled. */ declare class StampCreateTool extends AnnotationSelectTool { /** Event names of the image stamp tool. */ static readonly Events: { /** 'annotationAdded': an image stamp was added to the document. */ readonly ANNOTATION_ADDED: "annotationAdded"; /** 'annotationCreated': an image stamp was created. */ readonly ANNOTATION_CREATED: "annotationCreated"; /** 'fileRejected': an image file was rejected (type, size or decoding). */ readonly FILE_REJECTED: "fileRejected"; }; /** Image types accepted by createAnnotationFromFile (comma separated: mime, image/*, .extension), also the file picker's accept; all images (image/*) by default. */ ACCEPTED_IMAGE_TYPES: string; /** Maximum file size (bytes) accepted by createAnnotationFromFile; larger files fire fileRejected; null, 0 or less means no limit. */ ACCEPTED_FILE_SIZE: number | null; cursor: string; /** Preview following the pointer (not added to the document): only after armImage. */ annotation: Annotation$1 | null; /** Image stamp chosen by the UI, waiting for a click to place it. */ private armed; switchOut(newTool?: Tool): void; private disarm; private movePreview; /** With an image pending, a press places the stamp and pressing another annotation does not select it; without one, pressing an existing annotation selects and drags it as usual, and only empty space places an image. */ mouseLeftDown(e: PointerEvent): void; mouseMove(e: PointerEvent): void; mouseLeftUp(e: PointerEvent): void; /** * Makes an image file into an image stamp, scaled to fit 200 pt square, centered on pageCoordinates on that page, and adds it to the document (used for pasting clipboard images). * Fires fileRejected and returns null when the type is not in ACCEPTED_IMAGE_TYPES, the size exceeds ACCEPTED_FILE_SIZE, or decoding fails. */ createAnnotationFromFile(file: File, pageCoordinates: { /** Page number (1-based). */ pageNumber: number; /** X of the stamp center in PDF points. */ x: number; /** Y of the stamp center in PDF points. */ y: number; }): Promise; private place; } /** * Text selection, shared by the text select tool, text markup tools and the edit tool. Starts when pressed on text (tolerance = selection sensitivity in screen pixels); * during the drag only TextManager.hitTest / setSelection are called (synchronous, no requests on the hot path); when the text of the page under the pointer is not cached it is loaded first, keeping the previous frame's selection meanwhile. * If the page text was not loaded at press time, selection starts from the press position once it loads, provided the pointer is still down. */ declare class TextSelector { private readonly tool; private anchor; /** While dragging a handle, the offset between the press position and the point the handle indicates (page coordinates), kept during the drag. */ private grip; /** Press position while waiting for page text to load after pressing. */ private waiting; constructor(tool: Tool); private get viewer(); private get text(); /** Selection sensitivity (screen pixels) converted to a tolerance in page coordinates. */ tolerance(): number; /** Currently dragging a text selection. */ isSelecting(): boolean; /** * Press: on text, selection starts (returns 'started'); when the page text is not loaded, it is loaded (returns 'loading'; once loaded and still pressed, selection starts here, * and onStart notifies the caller); off text returns 'none'. */ start(loc: MouseLocation, onStart?: (at: TextPosition) => void): 'started' | 'loading' | 'none'; /** * A press on a handle at either end of the selection starts dragging it: the other end is the fixed anchor and this end follows the pointer. * The handle is below the bottom of the line, so at press time there is a distance between the pointer and the point the handle indicates (mid line); it is kept during the drag so the pointer does not jump to the next line at once. Returns whether a handle was pressed. */ startHandle(loc: MouseLocation): boolean; /** Drag: the focus is the nearest character on the page under the pointer; when that page's text is not cached it is loaded and nothing changes this frame. */ extend(at: MouseLocation): void; /** Release: ends the drag; clears the selection when nothing was selected (just a click). Returns whether text is selected. */ end(): boolean; /** Hover: prefetches the text of the page under the pointer if not cached, so a press can hit right away. */ hover(loc: MouseLocation): void; /** Selects the word at a point (double click); returns false when not on text. */ selectWord(loc: MouseLocation): boolean; private begin; } /** Base class for text hit testing; selection state lives in TextManager, the tool holds none and only selects text through TextSelector. */ declare class TextTool extends AnnotationSelectTool { /** The cursor of text tools is text. */ cursor: string; private textSelection; protected readonly selector: TextSelector; keyDown(e: KeyboardEvent): void; /** Allows selecting text with this tool (the default). */ enableTextSelection(): void; /** Disallows selecting text with this tool. */ disableTextSelection(): void; /** * Whether text can be selected with this tool. * @returns True when text selection is allowed. */ isTextSelectionEnabled(): boolean; } /** * ToolNames.TEXT_SELECT: drag on text to select it (during the drag only TextManager.hitTest / setSelection, synchronously), double-click selects a word, * Ctrl / Cmd + C copies the selected text, Escape clears the selection. Fingers hit text handles, annotations and control handles first; mouse / pen off text behaves like the selection tool. */ declare class TextSelectTool extends TextTool { mouseLeftDown(e: PointerEvent): void; protected isSelecting(): boolean; mouseMove(e: PointerEvent): void; mouseLeftUp(e: PointerEvent): void; mouseDoubleClick(e: MouseEvent): void; keyDown(e: KeyboardEvent): void; } /** * ToolNames.MARK_INSERT_TEXT: places a caret at the clicked text (CreateAnnot(kCaret)); it cannot be dragged or resized. */ declare class MarkInsertTextCreateTool extends TextSelectTool { /** * Creates the insert-text mark tool. * @param args The document viewer the tool works on. */ constructor(...args: ConstructorParameters); mouseLeftDown(): void; mouseMove(e: PointerEvent): void; /** On text the caret goes before or after the character (by the left / right half it falls on), with its bottom on the bottom of the line and sized 0.6 of the line height; off text it goes at the click. */ mouseLeftUp(e: PointerEvent): void; } /** * Base class for creating text markup: drag on text to select it; the quadrilaterals of the selected lines → TextMarkupAnnotation.Quads (during the drag only synchronous hit tests, see TextSelector); * a selection across pages creates one annotation per page. When there is no text under the press (such as scans), it falls back to one quadrilateral from the dragged rectangle. * The flow is the same as shapes: press creates (annotationCreated), drag changes the quadrilaterals, release calls addAnnotation (annotationAdded); annotations that are too small are dropped. * When the static switch AUTO_SET_TEXT is on (off by default) the selected text is written to the content (Contents), * and no longer overwritten once the user changes the content. */ declare class TextAnnotationCreateTool extends TextTool { protected readonly annotationPrototype: AnnotationClass; /** When on, annotations created from a text selection write the selected text to their content (off by default; one switch shared by subclasses). */ static AUTO_SET_TEXT: boolean; /** Automatically written content text: updated with the selection only while the content is still that text (left alone once the user changes it). */ private readonly autoText; /** The annotation being drawn, not yet added to the document. */ annotation: Annotation$1 | null; private start; /** text: by selection; rect: by the dragged rectangle; pending: waiting for page text to load. */ private mode; /** The text markup under this press (selected on release if there was no drag). */ private pressedMarkup; /** * Creates a tool that creates text markup annotations over selected text (red by default). * @param docViewer The document viewer the tool works on. * @param annotationPrototype Class of the annotations to create; TextHighlightAnnotation by default. */ constructor(docViewer: DocumentViewer, annotationPrototype?: AnnotationClass); switchOut(): void; mouseLeftDown(e: PointerEvent): void; mouseMove(e: PointerEvent): void; mouseLeftUp(e: PointerEvent): void; /** Quadrilaterals of the selected lines on the draft's page. */ private shapeFromSelection; /** Adds by selection: one annotation per page of the selection (the draft is the one on the starting page), then clears the selection. */ private finishSelection; /** Writes the selected text to the content when AUTO_SET_TEXT is on (see the file header). */ private setText; /** After adding by selection (the replace text tool adds the caret here). */ protected added(_annotations: Annotation$1[]): void; mouseDoubleClick(): void; keyDown(e: KeyboardEvent): void; /** Selection (rectangle) → annotation geometry; a nearly horizontal drag (across one line of text) takes the height of one line, centered on the drag line. */ protected shape(annotation: Annotation$1, r: Rect): void; /** Adds to the document and returns it; drops it and returns null when too small (under 2 pt). */ protected finish(): Annotation$1 | null; } /** ToolNames.STRIKEOUT */ declare class TextStrikeoutCreateTool extends TextAnnotationCreateTool { /** * Creates the text strikeout tool. * @param docViewer The document viewer the tool works on. */ constructor(docViewer: DocumentViewer); } /** ToolNames.MARK_REPLACE_TEXT: strikeout + a caret at the end; the caret is the group's primary annotation. */ declare class MarkReplaceTextCreateTool extends TextStrikeoutCreateTool { /** * Creates the replace-text mark tool. * @param docViewer The document viewer the tool works on. */ constructor(docViewer: DocumentViewer); protected finish(): Annotation$1 | null; /** After the strikeout is added, adds a caret at the end (on the last page) and puts the strikeout under it. */ protected added(annotations: Annotation$1[]): void; } /** ToolNames.REDACTION: dragging on text selects text to redact (one quadrilateral per selected line); dragging off text draws a rectangle. Red border and black fill by default. Apply with AnnotationManager.applyRedactions. */ declare class RedactionCreateTool extends TextAnnotationCreateTool { /** Redacts by the dragged rectangle (no text selection); the cursor is a crosshair (as when not over text). */ cursor: string; private autoSizedText; /** * Creates the redaction tool: red outline, black fill, red 18pt overlay text. * @param docViewer The document viewer the tool works on. */ constructor(docViewer: DocumentViewer); protected shape(annotation: Annotation$1, r: Rect): void; /** Note: automatic font size of the overlay text (OverlayText) only stores the switch. */ enableAutoSizedText(): void; /** Turns off automatic font size of the overlay text (only the setting is stored). */ disableAutoSizedText(): void; } /** * ToolNames.REDACTION_ERASURE: erasure redaction ("whiteout"). The dragged area is a redaction annotation marked Erasure; * applying it erases text and graphics in the area and shows the page background (no fill), so before applying it shows a white fill without overlay text. */ declare class ErasureRedactionCreateTool extends RedactionCreateTool { /** * Creates the redaction erasure tool (white fill, no overlay text). * @param docViewer The document viewer the tool works on. */ constructor(docViewer: DocumentViewer); } /** ToolNames.HIGHLIGHT: yellow by default. */ declare class TextHighlightCreateTool extends TextAnnotationCreateTool { /** * Creates the text highlight tool (yellow by default). * @param docViewer The document viewer the tool works on. */ constructor(docViewer: DocumentViewer); } /** ToolNames.SQUIGGLY */ declare class TextSquigglyCreateTool extends TextAnnotationCreateTool { /** * Creates the text squiggly underline tool. * @param docViewer The document viewer the tool works on. */ constructor(docViewer: DocumentViewer); } /** ToolNames.UNDERLINE */ declare class TextUnderlineCreateTool extends TextAnnotationCreateTool { /** * Creates the text underline tool. * @param docViewer The document viewer the tool works on. */ constructor(docViewer: DocumentViewer); } /** A few small top-level Core functions and enums. */ /** Font styles (names used by rich text and content editing). */ declare const FontStyles: { /** Bold. */ readonly BOLD: "BOLD"; /** Italic. */ readonly ITALIC: "ITALIC"; /** Underline. */ readonly UNDERLINE: "UNDERLINE"; }; /** Whether the canvas supports this blend mode (globalCompositeOperation, such as 'multiply'). */ declare function isBlendModeSupported(mode: string): boolean; /** Color processing after rendering (constants only; our rendering does not apply them). */ declare const ColorPostProcessMode: { /** No post-processing. */ readonly NONE: 0; /** Inverts colors. */ readonly INVERT: 1; /** Maps colors to a gradient. */ readonly GRADIENT_MAP: 2; /** Night mode colors. */ readonly NIGHT_MODE: 3; }; /** Switch for scripts in documents (on by default). Note: scripts are never executed; only the switch is stored. */ declare function enableEmbeddedJavaScript(): void; /** Turns off the switch for scripts in documents. Scripts are never executed; only the switch is stored. */ declare function disableEmbeddedJavaScript(): void; /** * Returns the switch for scripts in documents. * @returns true unless disableEmbeddedJavaScript was called (on by default). */ declare function isEmbeddedJavaScriptEnabled(): boolean; /** The AnnotationManager methods needed for strict font matching. */ interface FontMatchingTarget { getAnnotationsList: () => Array<{ elementName: string; }>; trigger: (name: string, args: unknown[]) => void; drawAnnotationsFromList: (list: never[]) => unknown; } /** * Strict annotation font matching (off by default): used to choose fonts for full PDFs and the free text rich text editor. * When an AnnotationManager is passed, turning it on fires annotationChanged (modify) once for all annotations, and turning it off redraws free text. * Note: our free text editing does not choose fonts by it; only the switch is stored. */ declare function enableStrictAnnotationFontMatching(manager?: FontMatchingTarget): void; /** * Turns off strict annotation font matching. When it was on and an AnnotationManager is passed, its free text annotations are redrawn. * @param manager Optional annotation manager to redraw. */ declare function disableStrictAnnotationFontMatching(manager?: FontMatchingTarget): void; /** * Returns whether strict annotation font matching is on. * @returns true after enableStrictAnnotationFontMatching; false by default. */ declare function getIsStrictAnnotationFontMatchingEnabled(): boolean; declare class Matrix2D { m_a: number; m_b: number; m_c: number; m_d: number; m_h: number; m_v: number; constructor(a?: number, b?: number, c?: number, d?: number, h?: number, v?: number); /** Rotates by radians around the origin (counterclockwise is positive). */ static rotation(radians: number): Matrix2D; initCoordinates(a: number, b: number, c: number, d: number, h: number, v: number): void; set(a: number, b: number, c: number, d: number, h: number, v: number): void; /** Inverse matrix; all zeros when not invertible. */ inverse(): Matrix2D; /** Transforms this point (in place, and returns it). */ mult

(point: P): P; /** this = apply m first, then this (in place, and returns this). */ concat(m: Matrix2D): this; equals(m: Matrix2D): boolean; } /** Page box: origin at 0 when width / height are given; otherwise x1 y1 x2 y2. */ interface PageBox { width?: number; height?: number; x1?: number; y1?: number; x2?: number; y2?: number; } /** * Core.getPageMatrix: zoom is the zoom, rotation is PageRotation (0–3, multiples of 90° clockwise), page the page box, * offset the offset on the canvas; with useMultiplier (true by default) zoom and offset are also multiplied by canvasMultiplier (or the given multiplier). */ declare function getPageMatrix(zoom: number, rotation: number, page: PageBox, offset?: { /** Horizontal offset. */ x: number; /** Vertical offset. */ y: number; }, useMultiplier?: boolean, multiplier?: number): Matrix2D; /** * Checks whether a link uses an allowed scheme (http, https, ftp, mailto or tel). A `www.` prefix counts as https. * @param uri The link to check. * @returns true when the link can be parsed and its scheme is allowed. */ declare function isValidURI(uri: string): boolean; /** With newWindow, opens in a new window (cutting opener); otherwise navigates the current page. */ declare function openURI(uri: string, newWindow?: boolean): void; declare namespace Core { export { AnnotationHistoryManager, AnnotationManager, AppearanceManager, Bookmark, CanvasManager, CenterAlignmentTypes, ColorPostProcessMode, ComPDFKitError, ContentEditHistoryManager, ContentEditManager, DisplayMode, DisplayModeManager, DisplayModes, DistributeAlignmentTypes, Document, DocumentViewer, EMPTY_XFDF, EditBoxManager, EventHandler, FitMode, FontStyles, FormFieldCreationManager, MeasurementManager, PageHistoryManager, PageInfo$1 as PageInfo, PageRotation, SaveOptions, Scale, Search, SearchMode, StandardAlignmentTypes, TextDirection, TextManager, areObjectURLBlobsEnabled, createDocument, disableEmbeddedJavaScript, disableLogs, disableObjectURLBlobs, disableStrictAnnotationFontMatching, enableEmbeddedJavaScript, enableStrictAnnotationFontMatching, getAllowedFileExtensions, getAppearanceManager, getBuild, getCanvasManager, getCanvasMultiplier, getHashParameter, getIsStrictAnnotationFontMatchingEnabled, getPageMatrix, getVersion, getWebFontNameList, getWorkerPath$1 as getWorkerPath, isBlendModeSupported, isEmbeddedJavaScriptEnabled, isValidURI, openURI, preloadPDFWorker, resetWorker, setAllowedFileExtensions, setCachingLevel, setCanvasMultiplier, setCustomFontURL, setPreRenderLevel, setProgressiveTime, setWorkerPath$1 as setWorkerPath, unsetCanvasMultiplier }; export type { AnnotationCreation, AnnotationManagerEvents, AnnotationPermissionTarget, AnnotationWriteOptions, AutoSelectOnCreatePolicy, BackgroundOptions, Base64Source, BlendMode, ColorSeparation, DigitalSignatureTextAppearance, DocumentEvents, DocumentPermissions, DocumentSource, DocumentWatermarkOptions, DownloadProgress, ErrorCode, ExternalSignOptions, ExternalSignSession, ExternalSignValue, ExtractPagesOptions, FileAttachment, GetFileDataOptions, HeaderFooterOptions, HeaderFooterPosition, Layer, LoadCanvasOptions, LoadDocumentOptions, Metadata, OptimizeDefaults, OptimizeOptions, OverprintPreviewMode, PageChanges, PageList, PageText, ResolvedSource, SearchResult, SearchStream, SemanticDiffOptions, SignOptions, SignResult, StandardType, TextExtractorProcessingFlags, TextHit, TextPosition, TextSelection, VerificationCertificate, VerificationOptions, VerificationResult, ViewerEvents, WatermarkOptions }; export namespace Actions { export { Dispatcher, GoTo, GoToR, Hide, JavaScript, Named, ResetForm, SubmitForm, URI }; } export namespace Annotations { export { Annotation$1 as Annotation, ArcAnnotation, Border, BoxControlHandle, BoxSelectionModel, ButtonWidgetAnnotation, CalloutControlHandle, CalloutSelectionModel, CanvasHelper, CaretAnnotation, CheckButtonWidgetAnnotation, ChoiceWidgetAnnotation, Color, ControlHandle, DatePickerWidgetAnnotation, EllipseAnnotation, FileAttachmentAnnotation, FileAttachmentSelectionModel, FileAttachmentUtils, Font, FreeHandAnnotation, FreeTextAnnotation, FreeTextSelectionModel, HTMLAnnotation, IPathAnnotation, LineAnnotation, LineControlHandle, LineEndType, LineLeaderControlHandle, LineSelectionModel, Link, ListWidgetAnnotation, MarkupAnnotation, PathControlHandle, PathSelectionModel, Point, PolygonAnnotation, PolygonControlHandle, PolygonSelectionModel, PolylineAnnotation, PushButtonWidgetAnnotation, Quad, RadioButtonWidgetAnnotation, Rect, RectangleAnnotation, RedactionAnnotation, RedactionSelectionModel, RotationControlHandle, RotationUtils, SelectionAlgorithm, SelectionModel, SignatureWidgetAnnotation, SoundAnnotation, SoundSelectionModel, StampAnnotation, StickyAnnotation, StickySelectionModel, TextControlHandle, TextHighlightAnnotation, TextMarkupAnnotation, TextSelectionModel, TextSquigglyAnnotation, TextStrikeoutAnnotation, TextUnderlineAnnotation, TextWidgetAnnotation, WidgetAnnotation, WidgetFlags, restoreDeserialize, restoreDraw, restoreSerialize, setCustomControlHandleDrawHandler, setCustomDeserializeHandler, setCustomDrawHandler, setCustomSerializeHandler }; export type { TextStampColor, TextStampShape }; export namespace Forms { export { Field, FieldManager }; } export namespace Utilities { export { calculateAutoFontSize, setAnnotationSubjectHandler }; export type { AnnotationSubjectHandler, FreeTextSubset }; } } export namespace ContentEdit { export { ContentBox, ContentBoxEditor, ContentBoxEditor as ContentEditSession, ContentImageBox, ContentImageBoxEditor, Events, Types, addNewParagraph, alignContents, getContent, getContentEditingFonts, getDocumentContent, getResourcePath, getWorkerPath, loadTextAttributes, preloadWorker, searchAndReplaceText, setContent, setContentCharacterSpacing, setContentFont, setContentFontSize, setContentLineSpacing, setContentParagraphSpacing, setResourcePath, setTextAttributes, setTextColor, setTextOpacity, setWorkerPath, toTextAttributes, toggleBoldContents, toggleItalicContents, toggleStrikeContents, toggleUnderlineContents, updateDocumentContent }; export type { AddNewParagraphOptions, ContentTarget, ContentTextPosition, ContentTextRange, ContentTextSelectionGeometry, FontStyle, SearchAndReplaceOptions, SpanObject, TextAttributes, TextDetails }; } export namespace Math { export { Matrix, Point, Quad, Rect, TransformationBuilder }; } export namespace Tools { export { AddImageContentTool, AddParagraphTool, AnnotationEditTool, AnnotationSelectTool, ArcCreateTool, ArcMeasurementCreateTool, AreaMeasurementCreateTool, ArrowCreateTool, CalibrationMeasurementTool, CalloutCreateTool, CheckBoxFormFieldCreateTool, CloudyRectangularAreaMeasurementCreateTool, ComboBoxFormFieldCreateTool, ContentEditTool, CountMeasurementCreateTool, CropCreateTool, CurveMeasurementCreateTool, DateFreeTextCreateTool, DatePickerFormFieldCreateTool, DistanceMeasurementCreateTool, EllipseCreateTool, EllipseMeasurementCreateTool, EraserTool, ErasureRedactionCreateTool, FileAttachmentCreateTool, FormFieldCreateTool, FreeHandCreateTool, FreeHandHighlightCreateTool, FreeTextCreateTool, GenericAnnotationCreateTool, LineCreateTool, ListBoxFormFieldCreateTool, MarkInsertTextCreateTool, MarkReplaceTextCreateTool, MarqueeZoomTool, PanTool, PerimeterMeasurementCreateTool, PolygonCloudCreateTool, PolygonCreateTool, PolylineCreateTool, RadioButtonFormFieldCreateTool, RectangleCreateTool, RectangularAreaMeasurementCreateTool, RedactionCreateTool, RubberStampCreateTool, SignatureCreateTool, SignatureFormFieldCreateTool, SnapModes, SnippingCreateTool, StampCreateTool, StickyCreateTool, TextAnnotationCreateTool, TextFormFieldCreateTool, TextHighlightCreateTool, TextSelectTool, TextSquigglyCreateTool, TextStrikeoutCreateTool, TextTool, TextUnderlineCreateTool, Tool, ToolNames }; export type { EraseMode, EraseTarget }; } } /** The i18next instance of this viewer (common members; cast to i18next's `i18n` type for the full API). */ interface I18n { readonly language: string readonly languages: readonly string[] t(key: string | string[], options?: Record): string exists(key: string, options?: Record): boolean changeLanguage(language?: string): Promise<(key: string | string[], options?: Record) => string> addResourceBundle(language: string, namespace: string, resources: Record, deep?: boolean, overwrite?: boolean): this getResourceBundle(language: string, namespace: string): Record | undefined on(event: string, callback: (...args: any[]) => void): void off(event: string, callback?: (...args: any[]) => void): void } // Generated by scripts/build-types.mjs. Do not edit. /** * The UI namespace, available as `instance.UI`: loads documents and controls the viewer's interface (elements, panels, headers, tools, popups, notes, search, printing and more). * Members are grouped by topic; component classes for building custom headers are in {@link UI.Components}. */ declare namespace UI { /** * Turns on editable sticky note hover for one viewer (off by default). * @param enabled `true` to turn it on. * @param key The viewer key, `1` by default. * @group View */ export function setStickyNoteHoverEnabled(enabled: boolean, key?: number | undefined): void /** * Sets the ICC output profile used for color separation. When color separation is on, pages are redrawn with the new profile right away. * @param profile A File, Blob, ArrayBuffer, typed array or URL; `null` restores the default CoatedFOGRA39 profile. * @returns A Promise that resolves once the profile is applied. * @group View */ export function setColorSeparationProfile(profile: ColorSeparationProfile): Promise /** * Injects CSS text into the viewer. Calls accumulate. The styles go into this instance's root node (not the host page's `document.head`) * and are removed when the instance is destroyed. * @param cssText The CSS text. * @example * ```js * instance.UI.setCustomStyle('.cpdf-header { background: #222; }'); * ``` * @group View */ export function setCustomStyle(cssText: string): void /** * Turns on view-only mode, closing every editing entry point (the View toolbar group is shown first). Whitelisted elements keep working. * @group View-only mode */ export function enableViewOnlyMode(): void /** * Turns off view-only mode; the toolbar group is not changed. * @group View-only mode */ export function disableViewOnlyMode(): void /** * Adds elements to the whitelist (visible and usable in view-only mode) and removes them from the blacklist. Accepts a string or an array of strings. * Duplicate elements are not added twice. * @param dataElements A dataElement or an array of them. * @group View-only mode */ export function addToViewOnlyWhitelist(dataElements: string | string[]): void /** * Removes elements from the whitelist and adds them to the blacklist: in view-only mode they are hidden / disabled even if they are in the built-in whitelist (per-type lists). * Duplicate elements are not added twice. * @param dataElements A dataElement or an array of them. * @group View-only mode */ export function removeFromViewOnlyWhitelist(dataElements: string | string[]): void /** * Gets the custom dataElement whitelist of view-only mode. * @returns A copy of the whitelist. * @group View-only mode */ export function getViewOnlyWhitelist(): string[] /** * Replaces the dataElement whitelist (the blacklist is unchanged). Only arrays are accepted. * @param dataElements The new whitelist. * @group View-only mode */ export function updateViewOnlyWhitelist(dataElements: string[]): void /** * Replaces the list of shortcuts that still respond in view-only mode. Accepts values of `UI.Shortcuts`; other values throw a TypeError. * Takes effect immediately. The list is stored per instance. * @param shortcuts Shortcut names from `UI.Shortcuts`. * @group View-only mode */ export function updateViewOnlyShortcuts(shortcuts: string[]): void /** * Gets the shortcuts that still respond in view-only mode. * @returns A copy of the list. * @group View-only mode */ export function getViewOnlyShortcuts(): string[] /** * Sets the UI theme. The value is case-insensitive; only `'light'` and `'dark'` are accepted. The theme is not persisted. * Non-string values are ignored with a warning. * @param theme `'light'` or `'dark'`. * @example * ```js * instance.UI.setTheme('dark'); * ``` * @group Theme and language */ export function setTheme(theme: string): void /** * Switches the language of this instance and persists it (the language is remembered). * Calls in the same tick are debounced to the last one, and all returned Promises resolve together when the switch completes. The debounce state is kept per instance. * @param language The language code, such as `'en'` or `'zh-CN'`. * @returns A Promise that resolves once the language is switched. * @example * ```js * await instance.UI.setLanguage('ja'); * ``` * @group Theme and language */ export function setLanguage(language: string): Promise /** * Gets the current language. * @returns The language code. * @example * ```js * const language = instance.UI.getCurrentLanguage(); // for example 'en' * ``` * @group Theme and language */ export function getCurrentLanguage(): string /** * Gets the available language codes: the codes in the settings dialog language list (the 6 built-in languages plus those added by addLanguage), * together with the languages whose resources were injected by setTranslations. * @returns The language codes. * @example * ```js * const codes = instance.UI.getAvailableLanguages(); // ['en', 'zh-CN', ...] * ``` * @group Theme and language */ export function getAvailableLanguages(): string[] /** * Adds or overrides translations of a language without a language pack file. The object is deep-merged into the existing translations, * so only the keys to change are needed. Keys missing in a language fall back to English. * @param language The language code. * @param translationObject The translations, keyed like the language pack. * @example * ```js * // Rename the "Save" action in English * instance.UI.setTranslations('en', { common: { actions: { save: 'Save changes' } } }); * ``` * @group Theme and language */ export function setTranslations(language: string, translationObject: Record): void /** * Adds a language to the language dropdown (an item with the same code is replaced). When the language is selected, its pack * `locales/translation-{code}.json` is loaded from the WebViewer path unless its translations were given with `setTranslations`. * @param language `{ code, name }`. * @example * ```js * instance.UI.addLanguage({ code: 'de', name: 'Deutsch' }); * instance.UI.setTranslations('de', { common: { actions: { save: 'Speichern', cancel: 'Abbrechen' } } }); * await instance.UI.setLanguage('de'); * ``` * @group Theme and language */ export function addLanguage(language: LanguageItem): void /** * Removes a language from the language dropdown. Accepts `{ code }` or a code string. * @param language The language code, or `{ code }`. * @param language.code The language code, such as `'zh-CN'`. * @example * ```js * instance.UI.removeLanguage('th'); * ``` * @group Theme and language */ export function removeLanguage(language: string | { code: string }): void /** * Replaces the whole language dropdown. * @param languages The languages as `[{ code, name }]`. * @example * ```js * instance.UI.setLanguages([ * { code: 'en', name: 'English' }, * { code: 'fr', name: 'Français' }, * ]); * ``` * @group Theme and language */ export function setLanguages(languages: LanguageItem[]): void /** * Gets the translation of a key in the current language (this instance's i18next `t`); returns the key when there is no translation. * An optional second argument (i18next options such as interpolation) is passed to `t` as is. Keys are this package's language pack keys. * @param key The language key, or several keys to try in order. * @param options i18next options. * @returns The translated text. * @example * ```js * const label = instance.UI.getLocalizedText('common.actions.save'); // 'Save' in English * ``` * @group Theme and language */ export function getLocalizedText(key: string | string[], options?: Record): string /** * This instance's i18next instance; available once the instance is created (may be undefined in unit test fixtures). * @group Theme and language */ export const i18n: I18n /** * Switches the tool of the active viewer. When the tool belongs to a toolbar group, that group is activated first. * @param toolName The tool name. * @param options Tool options. * @param options.continueAdding Keeps the signature field tool active after a field is created, instead of returning to the selection tool. Applies until the tool changes. * @example * ```js * instance.UI.setToolMode('AnnotationCreateRectangle'); * ``` * @group Tools */ export function setToolMode(toolName: string, options?: { continueAdding?: boolean }): void /** * Gets the current tool of the active viewer. * @returns The tool object. * @example * ```js * const tool = instance.UI.getToolMode(); * if (tool.name === instance.Core.Tools.ToolNames.RECTANGLE) { * console.log('The rectangle tool is active'); * } * ``` * @group Tools */ export function getToolMode(): CoreTool /** * Switches the toolbar group (the 2.x `toolMenu-*` prefix is accepted too). * @param groupDataElement The dataElement of the toolbar group, such as a value of `UI.ToolbarGroup`. * @example * ```js * instance.UI.setToolbarGroup(instance.UI.ToolbarGroup.ANNOTATE); * ``` * @group Tools */ export function setToolbarGroup(groupDataElement: string, _pickTool?: boolean): void /** * Gets the dataElement of the active ribbon item. * @returns The dataElement. * @group Tools */ export function getActiveRibbonItem(): string /** * Activates a ribbon item. Behaves like `setToolbarGroup`: switching groups also cancels the current tool, ends content or page editing, * closes style panels and swaps the header when needed. The argument must be a string. * @param ribbonItem The dataElement of the ribbon item. * @example * ```js * instance.UI.setActiveRibbonItem(instance.UI.ToolbarGroup.FORMS); * console.log(instance.UI.getActiveRibbonItem()); // 'toolbarGroup-Forms' * ``` * @group Tools */ export function setActiveRibbonItem(ribbonItem: string): void /** * Activates a GroupedItems (only writes activeGroupedItems; the toolbar group is not switched). * @param groupedItems The dataElement of the GroupedItems. * @group Tools */ export function setActiveGroupedItems(groupedItems: string): void /** * Registers a tool with the viewer. The tool can then be activated with `setToolMode(toolName)` and placed in a header * with `new UI.Components.ToolButton({ dataElement, toolName })`; tool buttons without their own icon or title use `buttonImage` and `tooltip`. * The last two arguments (mapping custom annotation classes to the tool) are not supported and are ignored with a warning. * @param tool `{ toolName, toolObject, buttonImage, buttonName, tooltip, ... }`. * @example * ```js * const { Tools, documentViewer } = instance.Core; * instance.UI.registerTool({ * toolName: 'MyRectangleTool', * toolObject: new Tools.RectangleCreateTool(documentViewer), * buttonImage: 'RectangleTool', // a built-in icon name * tooltip: 'My rectangle', * }); * instance.UI.setToolMode('MyRectangleTool'); * ``` * @group Tools */ export function registerTool(tool: ToolRegistration, annotationConstructor?: unknown, customAnnotationCheckFunc?: unknown): void /** * Unregisters a tool. * @param toolName The tool name. * @example * ```js * instance.UI.unregisterTool('MyRectangleTool'); * ``` * @group Tools */ export function unregisterTool(toolName: string): void /** * Updates a tool button's buttonName / tooltip / buttonGroup / buttonImage. * @param toolName The tool name. * @param properties The properties to change. * @group Tools */ export function updateTool(toolName: string, properties?: { /** dataElement of the tool's button; disabling the tool disables this element. */ buttonName?: string /** Title (or translation key) used by tool buttons of this tool that have no title of their own. */ tooltip?: string /** Tool group of the button. Stored only; currently has no effect. */ buttonGroup?: string /** Icon used by tool buttons of this tool that have no icon of their own. */ buttonImage?: string }): void /** * Disables tools; without arguments, all annotation creation tools. When the current tool is disabled, the selection tool is activated. A single string is accepted too. * @param toolNames A tool name or an array of them. * @example * ```js * const { ToolNames } = instance.Core.Tools; * instance.UI.disableTools([ToolNames.FREEHAND, ToolNames.ERASER]); * ``` * @group Tools */ export function disableTools(toolNames?: string | string[]): void /** * Enables tools; without arguments, all annotation creation tools. * @param toolNames A tool name or an array of them. * @example * ```js * instance.UI.enableTools([instance.Core.Tools.ToolNames.FREEHAND]); * ``` * @group Tools */ export function enableTools(toolNames?: string | string[]): void /** * Disables one tool; same as `disableTools([toolName])`. The name is required (omitting it does not mean all tools). * @param toolName The tool name. * @group Tools */ export function disableTool(toolName: string): void /** * Enables one tool; same as `enableTools([toolName])`. * @param toolName The tool name. * @group Tools */ export function enableTool(toolName: string): void /** * Tells whether a tool is disabled. Tools without a button return false. * @param toolName The tool name. * @returns `true` when the tool is disabled. * @example * ```js * const disabled = instance.UI.isToolDisabled(instance.Core.Tools.ToolNames.RECTANGLE); * ``` * @group Tools */ export function isToolDisabled(toolName: string): boolean /** * Sets the author shown in the settings dialog. This is separate from the current user set by `setCurrentUser`. * @param author The author name. * @group Tools */ export function setAuthor(author: string): void /** * Changing the style of a selected annotation is synced back to the tool that creates it (flows/annotations setAnnotationsStyles). * @group Annotation styles */ export function enableAnnotationToolStyleSyncing(): void /** * Turns off syncing annotation styles back to tools (off by default). * @group Annotation styles */ export function disableAnnotationToolStyleSyncing(): void /** * Turns on syncing style changes made in the annotation style popup back to the tool defaults (on by default). * This UI has no such popup, so the switch has no reader for now: the state is valid but the UI does not read it. * The style panel's syncing uses enable / disableAnnotationToolStyleSyncing (which also write this switch, so the two never disagree). * @group Annotation styles */ export function enableToolDefaultStyleUpdateFromAnnotationPopup(): void /** * Turns off the switch set by `enableToolDefaultStyleUpdateFromAnnotationPopup`. * @group Annotation styles */ export function disableToolDefaultStyleUpdateFromAnnotationPopup(): void /** * Sets the preset colors of the text / stroke / fill sections of the style panel. * - An array: global, used by all tools; each item is #rrggbb or 'transparency'. If any item is invalid, warns and changes nothing. * - `{ toolNames, colors }`: only for these tools (and the annotations they create); warns when toolNames or colors is missing. * Writes `viewer.customElementOverrides.colorPalette` (read by the style panel; 'transparency' draws no swatch, the fill section always has a no-color swatch) and the three color sets (`setColors`, text / stroke / fill, transparency removed from fill). * Tool names are matched exactly; in the object form `colors` must be an array of valid colors; arguments that are neither an array nor an object are ignored with a warning. * @param palette An array of colors, or `{ toolNames, colors }`. * @example * ```js * instance.UI.setColorPalette(['#E44234', '#FF8D00', '#1460F3', 'transparency']); * ``` * @group Annotation styles */ export function setColorPalette(palette: string[] | PaletteOption): void /** * Sets which palette's color the tool button icon uses ('text' | 'border' | 'fill'). * Writes viewer.colorMap[toolName].iconColor ('TextColor' / 'StrokeColor' / 'FillColor'). If the tool does not have that color, warns with the available palettes and changes nothing. * colorMap is keyed by tool name. Unregistered tools warn. * The default UI does not color tool buttons, so only the state is stored, for `Components.ToolButton` showColor; the current UI does not draw it. * @param toolName The tool name. * @param colorPalette `'text'`, `'border'` or `'fill'`. * @group Annotation styles */ export function setIconColor(toolName: string, colorPalette: 'text' | 'border' | 'fill'): void /** * Sets which palette tab the style panel opens by default. * Writes viewer.colorMap[toolName].currentStyleTab; rules and warnings are the same as setIconColor. * The style panel has no color tabs (text / stroke / fill colors are shown together), so only the state is stored (`getCurrentStyleTab`); the UI does not read it. * @param toolName The tool name. * @param colorPalette `'text'`, `'border'` or `'fill'`. * @group Annotation styles */ export function setActivePalette(toolName: string, colorPalette: 'text' | 'border' | 'fill'): void /** * Registers a custom fill style. Options: key / appliesTo / title / svg / clipToShape / clipToShapeFn / drawHandler. * Invalid options are ignored with a console warning (no throw). Registering the same key again replaces it. title / svg are reserved for a style panel fill dropdown, which this UI does not have. * @param options The fill style options. * @group Annotation styles */ export function registerCustomFillStyle(options: CustomFillStyleOptions): void /** * Unregisters a custom fill style. Annotations still using it fall back to the default solid fill and are redrawn. * @param key The key the style was registered with. * @group Annotation styles */ export function unregisterCustomFillStyle(key: string): void /** * Adds a panel. `render` is a built-in panel name (string) or a function that returns an HTMLElement or a string; * the function is called once, when the panel is first shown. Open the panel with `openElements([dataElement])`. * @param panel `{ dataElement, location, render }`. * @example * ```js * instance.UI.addPanel({ * dataElement: 'infoPanel', * location: 'right', * render: () => { * const div = document.createElement('div'); * div.textContent = 'Custom panel content'; * return div; * }, * }); * instance.UI.openElements(['infoPanel']); * ``` * @group Panels */ export function addPanel(panel: PanelData): void /** * Replaces all panels. Accepts Panel objects from getPanels() or plain objects. * @param panelList The panels. * @example * ```js * // Remove the link properties panel * instance.UI.setPanels(instance.UI.getPanels().filter(panel => panel.dataElement !== instance.UI.Panels.LINK)); * ``` * @group Panels */ export function setPanels(panelList: Array): void /** * Gets the panels as Panel objects. Changes made through them (`setLocation`, `delete`, ...) apply to the viewer right away. * @returns The panels. * @example * ```js * const names = instance.UI.getPanels().map(panel => panel.dataElement); * ``` * @group Panels */ export function getPanels(): Panel[] /** * Sets the active tab of a tab panel. * @param options `{ tabPanel, tabName }`. * @param options.tabPanel The dataElement of the tab panel. * @param options.tabName The dataElement of the panel to show. * @example * ```js * instance.UI.setActiveTabInPanel({ tabPanel: instance.UI.Panels.TABS, tabName: instance.UI.Panels.OUTLINE }); * ``` * @group Panels */ export function setActiveTabInPanel(options: { tabPanel: string tabName: string }): void /** * Sets the active tab of the left panel; same as `setActiveTabInPanel({ tabPanel: 'tabPanel', tabName })` (replaces the 2.x setActiveElementTab). * @param dataElement The dataElement of the tab. * @example * ```js * instance.UI.setActiveLeftPanel(instance.UI.Panels.OUTLINE); * instance.UI.openElements([instance.UI.Panels.TABS]); * ``` * @group Panels */ export function setActiveLeftPanel(dataElement: string): void /** * Adds a custom tab to the left panel (legacy API). * Converted to addPanel on the left (tab.title → title, tab.img → icon, plus the panel's dataElement / render), with a warning that it is a legacy API. * @param options `{ tab, panel }`. * @param options.tab The tab. * @param options.tab.dataElement The tab's dataElement. * @param options.tab.title The tab's tooltip text. * @param options.tab.img The tab's icon. * @param options.panel The panel. * @param options.panel.dataElement The panel's dataElement. * @param options.panel.render A built-in panel name, or a function returning the panel's element. * @group Panels */ export function setCustomPanel(options: { tab: { dataElement: string title?: string img?: string } panel: { dataElement: string render: FunctionRef } }): void /** * Opens or closes the left panel (`UI.Panels.TABS`); replaces the 2.x toggleSidebar. Opening it closes other panels on the same side. * The value is not type-checked; it is tested for truthiness. * @param value `true` to open. * @example * ```js * instance.UI.setSideWindowVisibility(true); * ``` * @group Panels */ export function setSideWindowVisibility(value: boolean): void /** * Sets the width of a panel and triggers `UI.Events.PANEL_RESIZED`; the document area adjusts to the new width. * The width is clamped to [264, window width] with a warning. The 2.x name `leftPanel` is accepted for the left panel. * Panels are 260 pixels wide by default and have no resize handle. * @param dataElement The dataElement of the panel. * @param width The width in pixels. * @example * ```js * instance.UI.setPanelWidth(instance.UI.Panels.TABS, 320); * ``` * @group Panels */ export function setPanelWidth(dataElement: string, width: number): void /** * Replaces the modular UI (components, headers, panels, flyouts and popups) with imported data. * Everything is validated first (unknown types, missing item references, header placement, panel location / render); any invalid item * rejects the Promise and leaves the UI unchanged. Functions in the data are names looked up in `functionMap`. Items marked `disabled` are disabled * as with `disableElements`. `UI.Events.MODULAR_UI_IMPORTED` is triggered when done. * @param data The data, as returned by `exportModularComponents`. * @param functionMap Functions referenced by name in the data. * @returns A Promise that resolves once the data is applied. * @example * ```js * const response = await fetch('/config/modular-ui.json'); * await instance.UI.importModularComponents(await response.json(), { * saveToServer: () => console.log('save'), // referenced as "onClick": "saveToServer" in the JSON * }); * ``` * @group Modular UI */ export function importModularComponents(data: ModularComponentsData, functionMap?: { [x: string]: (...args: any[]) => unknown; }): Promise /** * Exports the modular UI data of this viewer. The result is JSON-serializable and can be passed to `importModularComponents` as is. * Functions are written as their names in the function map given to `importModularComponents` (functions not in it are left out with a warning); * disabled items get `disabled: true`; the viewer's built-in flyouts are skipped. * @returns The modular UI data. * @example * ```js * const json = JSON.stringify(instance.UI.exportModularComponents(), null, 2); * ``` * @group Modular UI */ export function exportModularComponents(): { /** Components (buttons, groups, dividers and so on) keyed by dataElement. */ modularComponents: Record> /** Headers keyed by dataElement. */ modularHeaders: Record> /** Panels keyed by dataElement. */ panels: Record> /** Flyouts keyed by dataElement. */ flyouts: Record> /** Items of each popup, keyed by popup dataElement. */ popups: Record } /** * Adds headers (a single header or an array) together with the items they contain. A header with the same dataElement is replaced. * @param headerList A header or an array of headers. * @example * ```js * const { ModularHeader, CustomButton } = instance.UI.Components; * instance.UI.addModularHeaders([ * new ModularHeader({ * dataElement: 'myLeftHeader', * placement: 'left', * items: [new CustomButton({ dataElement: 'helloButton', label: 'Hi', onClick: () => alert('Hello') })], * }), * ]); * ``` * @group Modular UI */ export function addModularHeaders(headerList: object | object[]): void /** * Replaces all headers with the given ones; headers not in the list are removed. Items registered before are kept and can still be referenced. * @param headerList A header or an array of headers. * @example * ```js * // Keep only the default top header * instance.UI.setModularHeaders([instance.UI.getModularHeader('default-top-header')]); * ``` * @group Modular UI */ export function setModularHeaders(headerList: object | object[]): void /** * Gets a header as a `UI.Components.ModularHeader` object whose items are component objects. Warns and returns null when it does not exist. * The default UI has the headers `'default-top-header'` and `'tools-header'`. * @param dataElement The dataElement of the header. * @returns The header, or `null`. * @example * ```js * const header = instance.UI.getModularHeader('default-top-header'); * header.setJustifyContent('space-between'); * console.log(header.getItems().map(item => item.dataElement)); * ``` * @group Modular UI */ export function getModularHeader(dataElement: string): null | UI.Components.ModularHeader /** * Gets all headers of this viewer, default headers included, as `UI.Components.ModularHeader` objects. * @returns The headers. * @example * ```js * const names = instance.UI.getModularHeaderList().map(header => header.dataElement); * ``` * @group Modular UI */ export function getModularHeaderList(): UI.Components.ModularHeader[] /** * Gets a GroupedItems instance (children as component instances). Warns and returns null when it does not exist or has another type. * @param dataElement The dataElement of the GroupedItems. * @returns The GroupedItems, or `null`. * @example * ```js * // The tools shown under the Annotate ribbon * const annotateTools = instance.UI.getGroupedItems('annotateGroupedItems'); * annotateTools.setItems(annotateTools.items.filter(item => item.dataElement !== 'eraserToolButton')); * ``` * @group Modular UI */ export function getGroupedItems(dataElement: string): null | UI.Components.GroupedItems /** * Gets a RibbonGroup instance. Warns and returns null when it does not exist or has another type. * @param dataElement The dataElement of the RibbonGroup. * @returns The RibbonGroup, or `null`. * @group Modular UI */ export function getRibbonGroup(dataElement: string): null | UI.Components.RibbonGroup /** * Sets the gap of GroupedItems. Must be a non-negative number (pixels); otherwise ignored with a warning. * @param gap The gap in pixels. * @param selectors `{ groupedItemsDataElement }` to change only one GroupedItems. * @example * ```js * instance.UI.setGroupedItemsGap(12, { groupedItemsDataElement: 'annotateGroupedItems' }); * ``` * @group Modular UI */ export function setGroupedItemsGap(gap: number, selectors?: GroupedItemsSelectors): void /** * Sets the flex-grow of GroupedItems. Must be a non-negative number; otherwise ignored with a warning. * @param grow The flex-grow value. * @param selectors `{ groupedItemsDataElement }` to change only one GroupedItems. * @group Modular UI */ export function setGroupedItemsGrow(grow: number, selectors?: GroupedItemsSelectors): void /** * Sets the justify-content of GroupedItems. Values from UI.JustifyContent; others are ignored with a warning. * @param justifyContent The alignment. * @param selectors `{ groupedItemsDataElement }` to change only one GroupedItems. * @group Modular UI */ export function setGroupedItemsJustifyContent(justifyContent: string, selectors?: GroupedItemsSelectors): void /** * Adds, finds and positions flyouts (the drop-down menus of modular headers). * @group Modular UI */ export const Flyouts: FlyoutsAPI /** * The items of the popup shown when an annotation is selected. Custom items use the types `'actionButton'`, `'statefulButton'`, `'toggleElementButton'`, `'toolButton'` or `'divider'`. * @example * ```js * instance.UI.annotationPopup.add([ * { * type: 'actionButton', * dataElement: 'logAnnotationButton', * label: 'Log', * onClick: () => console.log(instance.Core.annotationManager.getSelectedAnnotations()), * }, * ]); * ``` * @group Popups and menus */ export const annotationPopup: PopupAPI /** * The items of the popup shown when text is selected. * @example * ```js * instance.UI.textPopup.add({ * type: 'actionButton', * dataElement: 'searchSelectionButton', * label: 'Search', * onClick: () => { * const text = instance.Core.documentViewer.getSelectedText(); * instance.UI.searchTextFull(text); * }, * }, 'copyTextButton'); * ``` * @group Popups and menus */ export const textPopup: PopupAPI /** * The items of the right-click (or long press) menu over the document. It has no items by default, so it only appears once items are added. * @example * ```js * // The right-click menu only appears once it has items * instance.UI.contextMenuPopup.update([ * { type: 'actionButton', dataElement: 'ctxPrintButton', label: 'Print', onClick: () => instance.UI.print() }, * { type: 'actionButton', dataElement: 'ctxDownloadButton', label: 'Download', onClick: () => instance.UI.downloadPdf() }, * ]); * ``` * @group Popups and menus */ export const contextMenuPopup: PopupAPI /** * The items of the popup shown while editing text or images; copy, properties and delete by default. * @example * ```js * // Remove the delete button * const items = instance.UI.contentEditPopup.getItems().filter(item => item.dataElement !== 'contentEditDeleteButton'); * instance.UI.contentEditPopup.update(items); * ``` * @group Popups and menus */ export const contentEditPopup: PopupAPI /** * UI.snippingToolPopup (the 2.x `cropPagePopup`): items of the popup beside the snipping box; download / exit by default. * @group Popups and menus */ export const snippingToolPopup: PopupAPI /** * Edits the items of the main menu (the settings menu opened from the top header). * @group Popups and menus */ export const settingsMenuOverlay: MenuOverlayAPI /** * Adds a custom modal. A modal with the same `dataElement` replaces the existing one. * The modal stays hidden until it is opened with `openElements([dataElement])`; clicking the backdrop or pressing Escape closes it * unless `disableBackdropClick` / `disableEscapeKeyDown` is set. * `header`, `body` and `footer` each take `{ title, className, style, innerHTML, children }`, where `children` are * `{ title, button, className, style, onClick }`; alternatively `render` returns an element or a string shown as the content. * @param options The modal options; `dataElement` is required. * @example * ```js * instance.UI.addCustomModal({ * dataElement: 'aboutModal', * header: { title: 'About' }, * body: { innerHTML: '

Contract review workspace

' }, * footer: { * children: [ * { title: 'Close', button: true, onClick: () => instance.UI.closeElements(['aboutModal']) }, * ], * }, * }); * instance.UI.openElements(['aboutModal']); * ``` * @group Dialogs */ export function addCustomModal(options: CustomModalOptions): void /** * Replaces the content of the centered loading row. * `element` accepts an HTML string or an HTMLElement; `styles` is a style object applied to it. Pass `null` to restore the default. * @param options The custom loading content, or `null`. * @example * ```js * instance.UI.setCustomLoading({ element: '
', styles: { color: '#1460f3' } }); * ``` * @group Dialogs */ export function setCustomLoading(options: CustomLoadingOptions | null): void /** * Opens the error dialog with the given message. * The text is shown as is (the internal `{x} failed` suffix is only used for internal download / print failures). The loading overlay is closed first. * The signature and password dialogs are not closed: they hold pending Promises that their own flows settle. * @param message The message to show. * @group Dialogs */ export function displayErrorMessage(message: string): void /** * Opens the warning dialog. * A string is treated as `{ message }`. An object replaces the previous options as a whole: * `title` / `message` / `confirmBtnText` (translated when the language pack has the key, otherwise shown as is), `onConfirm` / `onCancel` (may return a Promise or a value; the dialog closes once it resolves). * The arguments are type-checked. The dialog has Cancel and OK buttons, X acts as Cancel, clicking the backdrop or pressing Esc does not close it. * If a callback throws, the dialog still closes and the error is logged with console.error. * @param options The message text, or the dialog options. * @example * ```js * instance.UI.showWarningMessage({ * title: 'Delete page', * message: 'This cannot be undone.', * onConfirm: () => deletePage(), * }); * ``` * @group Dialogs */ export function showWarningMessage(options: string | WarningMessageOptions): void /** * Finds the next match (call again to find the following one). * @param searchValue The text to search. * @param options Search options, or a string such as `'CaseSensitive,WholeWord'`. * @example * ```js * instance.UI.searchText('total', 'CaseSensitive,WholeWord'); * // Call again to go to the next match * instance.UI.searchText('total', 'CaseSensitive,WholeWord'); * ``` * @group Search */ export function searchText(searchValue: string, options?: string | SearchOptions): void /** * Searches the whole document and highlights all results. Resolves when the search finishes (or is cleared). * By default (isUserTriggered) the search panel opens and the search term is written into its input. Options: caseSensitive / wholeWord / wildcard / regex. * @param searchValue The text to search. * @param options Search options. * @param isUserTriggered Whether to open the search panel and fill its input; `true` by default. * @param config Extra settings. * @param config.shouldDispatchUIActions When false, the search runs without changing the UI: the search panel and its input are left as they are. * @returns A Promise that resolves when the search finishes. * @example * ```js * await instance.UI.searchTextFull('invoice', { caseSensitive: true }); * ``` * @group Search */ export function searchTextFull(searchValue: string, options?: SearchOptions, isUserTriggered?: boolean, config?: { shouldDispatchUIActions?: boolean }): Promise /** * The same query consumed by the search panel; changing it alone does not start or cancel a search. * @group Search */ export function getSearchQuery(): string /** * Set the search panel query without opening the panel or executing a query. * @example * ```js * instance.UI.setSearchQuery('contract'); * ``` * @group Search */ export function setSearchQuery(query: string): void /** * Adds a listener called after a search completes with `(searchValue, options, results)`. The same function is added only once. * @param listener The listener. * @example * ```js * instance.UI.addSearchListener((searchValue, options, results) => { * console.log(`${results.length} result(s) for "${searchValue}"`); * }); * ``` * @group Search */ export function addSearchListener(listener: (searchValue: string, options: Record, results: unknown[]) => void): void /** * Removes a listener added by `addSearchListener`. * @param listener The listener. * @example * ```js * const onSearch = (searchValue, options, results) => console.log(results.length); * instance.UI.addSearchListener(onSearch); * // later * instance.UI.removeSearchListener(onSearch); * ``` * @group Search */ export function removeSearchListener(listener: (searchValue: string, options: Record, results: unknown[]) => void): void /** * Replaces the search started from the UI's search input with a custom function (per instance). Pass null to restore the default. * @param fn The search function, or `null`. * @example * ```js * instance.UI.overrideSearchExecution((searchValue, options) => { * // Always search whole words * instance.UI.searchTextFull(searchValue, { ...options, wholeWord: true }, false); * }); * ``` * @group Search */ export function overrideSearchExecution(fn: ((searchValue: string, options: Record) => void) | null): void /** * Replaces the displayed search results with external ones (the existing results are cleared, then these are highlighted together). * @param results The search results. * @group Search */ export function setSearchResults(results: SearchResult[]): void /** * Sets the active search result (only changes its color; does not navigate). Without a result, picks the result at `index` from the existing ones. * @param result The search result. * @param index The index of an existing result. * @group Search */ export function setActiveResult(result?: SearchResult, index?: number): void /** * Clears the search results when the search panel closes (the default). * @group Search */ export function enableClearSearchOnPanelClose(): void /** * Keeps the search results when the search panel closes (leaving the search tab still clears them). * @group Search */ export function disableClearSearchOnPanelClose(): void /** * Prints the current document (the permission password dialog opens first when printing is not allowed). Pages are rendered behind a spinner overlay and handed to the browser print dialog. * @example * ```js * printLink.addEventListener('click', () => instance.UI.print()); * ``` * @group Print */ export function print(): void /** * Prints without the overlay. Resolves once handed to the browser print dialog; rejects when there is no document or rendering fails, and resolves without printing when the user cancels the permission password dialog. * Annotations flagged as "no print" are printed too (the engine has no print mode). * @param options Print options. * @returns A Promise that resolves once the pages are handed to the browser. * @example * ```js * await instance.UI.printInBackground({ * pagesToPrint: [1, 2, 3], * includeAnnotations: true, * onProgress: (pageNumber) => console.log(`Rendered page ${pageNumber}`), * }); * ``` * @group Print */ export function printInBackground(options?: PrintInBackgroundOptions): Promise /** * Stops the print in progress (rendering stops at the current page). Does nothing when nothing is printing. * @example * ```js * instance.UI.cancelPrint(); * ``` * @group Print */ export function cancelPrint(): void /** * Sets the bitmap scale used for printing (devicePixelRatio by default). * @param quality A positive number. * @example * ```js * instance.UI.setPrintQuality(2); // render pages at twice the CSS pixel size * ``` * @group Print */ export function setPrintQuality(quality: number): void /** * Sets the default print options, merged with the existing ones. includeComments / includeAnnotations / maintainPageOrientation are booleans; margins is a string such as "0.5in" or "0.5in 0.4in 0.3in 0.2in". * There is no print settings dialog: includeAnnotations decides whether print() and the print button include annotations, margins sets the page margins; includeComments / maintainPageOrientation have no effect and warn when true. * @param options The default print options. * @example * ```js * instance.UI.setDefaultPrintOptions({ includeAnnotations: false, margins: '0.5in' }); * ``` * @group Print */ export function setDefaultPrintOptions(options: PrintDefaults): void /** * Sets the date format of the printed notes page. The value is stored only; there is no printed notes page. * @param format The date format. * @group Print */ export function setPrintedNoteDateFormat(format: string): void /** * Sets the darkening factor for grayscale printing. The value is stored only; it has no effect without a grayscale print option. * @param factor The darkness factor. * @group Print */ export function setGrayscaleDarknessFactor(factor: number): void /** * Uses embedded printing (the flattened PDF is handed to the browser's PDF viewer to print). When pagesToPrint is given, pages are still rendered one by one. * @param use `true` by default. * @group Print */ export function useEmbeddedPrint(use?: boolean | undefined): void /** * Tells whether embedded printing is on and supported by the current browser (not on Android). * @returns `true` when embedded printing will be used. * @group Print */ export function willUseEmbeddedPrinting(): boolean /** * Settings of the notes (comments) panel. * @group Notes */ export namespace NotesPanel { /** Turns on collapsing of long note text. The setting is stored, but the notes list does not collapse text yet. */ export function enableTextCollapse(): void /** Turns off collapsing of long note text. The setting is stored, but the notes list does not collapse text yet. */ export function disableTextCollapse(): void /** Turns on collapsing of replies. The setting is stored, but replies are always shown when their note is selected. */ export function enableReplyCollapse(): void /** Turns off collapsing of replies. The setting is stored, but replies are always shown when their note is selected. */ export function disableReplyCollapse(): void /** Shows replies only for the selected note (the default). */ export function disableAutoExpandCommentThread(): void /** * Shows the replies of every note without selecting it. * @example * ```js * instance.UI.NotesPanel.enableAutoExpandCommentThread(); * ``` */ export function enableAutoExpandCommentThread(): void /** * Custom panel header: render(notes) returns an HTMLElement placed before the title bar; with overwriteDefaultHeader it replaces the title bar. * notes are the (filtered) annotations in the list. Pass null to cancel. * @example * ```js * instance.UI.NotesPanel.setCustomHeader({ * overwriteDefaultHeader: false, * render: (notes) => { * const div = document.createElement('div'); * div.textContent = `${notes.length} comment(s)`; * return div; * }, * }); * ``` */ export function setCustomHeader(options: CustomHeaderOptions | null): void /** * Sets what the notes panel shows when it lists no annotations: `render` when given; otherwise `message` (or `readOnlyMessage` for read-only documents) * and `icon` (inline SVG markup, not drawn with `hideIcon`). Pass null to restore the default. * @example * ```js * instance.UI.NotesPanel.setCustomEmptyPanel({ message: 'No comments yet', hideIcon: true }); * ``` */ export function setCustomEmptyPanel(options: CustomEmptyPanelOptions | null): void /** Turns on previews of reply attachments. The setting is stored, but replies have no attachments yet. */ export function enableAttachmentPreview(): void /** Turns off previews of reply attachments. The setting is stored, but replies have no attachments yet. */ export function disableAttachmentPreview(): void /** Turns off selecting several notes at once. The setting is stored, but the notes list selects one note at a time. */ export function disableMultiSelect(): void /** Turns on selecting several notes at once. The setting is stored, but the notes list selects one note at a time. */ export function enableMultiSelect(): void /** * Sets the function that uploads reply attachments. The function is stored, but replies have no attachments yet. * @param handler Receives the file and resolves to its URL; `null` removes it. */ export function setAttachmentHandler(handler: ((...args: any[]) => unknown) | null): void /** * Options of the status dropdown (standard names from StatusList; unknown names are ignored with a warning, duplicates are removed). * In this UI the review status menu only lists the selected ones among Accepted / Rejected / Cancelled / Completed / None; the mark checkbox is disabled unless Marked and Unmarked are selected; * an empty array disables the status button. Pass Object.values(StatusList) to restore all. * @example * ```js * const { StatusList } = instance.UI.NotesPanel; * instance.UI.NotesPanel.setStatusList([StatusList.ACCEPTED, StatusList.REJECTED, StatusList.NONE]); * ``` */ export function setStatusList(statuses: string[]): void /** The status names. */ export const StatusList: { /** The note was accepted. */ readonly ACCEPTED: 'Accepted' /** The note was rejected. */ readonly REJECTED: 'Rejected' /** The note was cancelled. */ readonly CANCELLED: 'Cancelled' /** The note was completed. */ readonly COMPLETED: 'Completed' /** No review status. */ readonly NONE: 'None' /** The note is marked (the check box of a note). */ readonly MARKED: 'Marked' /** The note is not marked. */ readonly UNMARKED: 'Unmarked' } /** Turns on the measurement annotation filter of the notes panel. The setting is stored, but the notes panel has no such filter yet. */ export function enableMeasurementAnnotationFilter(): void /** Turns off the measurement annotation filter of the notes panel. The setting is stored, but the notes panel has no such filter yet. */ export function disableMeasurementAnnotationFilter(): void } /** * Opens the notes tab, selects the annotation and starts editing it (the list scrolls to the item and focuses its reply box; sticky notes are edited in the on-page note editor). * Uses the same flow as the annotation popup's Reply. Warns when the annotation is not found. * @param annotationId The annotation id. * @example * ```js * const [annotation] = instance.Core.annotationManager.getAnnotationsList(); * instance.UI.focusNote(annotation.Id); * ``` * @group Notes */ export function focusNote(annotationId: string): void /** * Shows only the annotations for which `filter` returns true in the notes list. Pass null to cancel. * @param filter The filter function, or `null`. * @example * ```js * // Show only the current user's annotations * const user = instance.Core.annotationManager.getCurrentUser(); * instance.UI.setCustomNoteFilter(annotation => annotation.Author === user); * ``` * @group Notes */ export function setCustomNoteFilter(filter: ((annotation: Core.Annotations.Annotation) => boolean) | null): void /** * Sets the date format of the notes list, using dayjs format tokens (`'DD/MM/YYYY HH:mm:ss'` by default). * @param format The date format. * @example * ```js * instance.UI.setNoteDateFormat('YYYY-MM-DD HH:mm'); * ``` * @group Notes */ export function setNoteDateFormat(format: string): void /** * Annotations for which the callback returns true cannot be replied to (no reply box in the list, and replying is refused). Pass null to cancel. * @param isReplyDisabled The predicate, or `null`. * @example * ```js * instance.UI.disableReplyForAnnotations(annotation => annotation.Author === 'System'); * ``` * @group Notes */ export function disableReplyForAnnotations(isReplyDisabled: ((annotation: Core.Annotations.Annotation) => boolean) | null): void /** * Registers and activates a sort strategy (a strategy with the same name replaces a built-in one). Requires `name` and `getSortedNotes`; otherwise ignored with a warning. * When the strategy is not the default `position`, the notes list is sorted by it, with separators decided by shouldRenderSeparator / getSeparatorContent. * @param strategy `{ name, getSortedNotes, shouldRenderSeparator?, getSeparatorContent? }`. * @example * ```js * // Sort notes by their text length, longest first * instance.UI.addSortStrategy({ * name: 'length', * getSortedNotes: notes => notes.sort((a, b) => b.getContents().length - a.getContents().length), * }); * ``` * @group Notes */ export function addSortStrategy(strategy: SortStrategy): void /** * Selects a sort strategy by name (a built-in name from NotesPanelSortStrategy, or one registered by addSortStrategy). Throws an Error for an empty name. * @param sortStrategy The strategy name. * @example * ```js * instance.UI.setNotesPanelSortStrategy(instance.UI.NotesPanelSortStrategy.CREATED_DATE); * ``` * @group Notes */ export function setNotesPanelSortStrategy(sortStrategy: string): void /** * Same as `addSortStrategy`. * @param newStrategy The strategy. * @group Notes */ export function setNotesPanelSort(newStrategy: SortStrategy): void /** * The on-page sticky note editor only opens when `filter` returns true for the selected annotation (only sticky notes have it for now). Pass null to cancel (always opens by default). * @param filter The filter, or `null`. * @group Notes */ export function setInlineCommentFilter(filter: ((annotation: unknown) => boolean) | null): void /** * Calls `fn(wrapperElement, { annotation, isSelected }, createElement)` after each notes list item renders. Pass null to cancel. * @param fn The transform function, or `null`. * @group Notes */ export function dangerouslySetNoteTransformFunction(fn: ((...args: any[]) => unknown) | null): void /** * Calls `fn(annotation)` when a notes list item is clicked and its annotation is not selected yet. Pass null to cancel. * The function is only called when the annotation is not already selected. * @param fn The selection function, or `null`. * @group Notes */ export function setCustomNoteSelectionFunction(fn: ((...args: any[]) => unknown) | null): void /** * Sets the overlay shown when hovering an annotation: `handler(annotation)` returns a DOM element (null / false / undefined draw nothing; there is no default overlay). Pass null to cancel. * @param handler The handler, or `null`. * @group Notes */ export function setAnnotationContentOverlayHandler(handler: ((...args: any[]) => unknown) | null): void /** * Turns autosave on. * @group Notes */ export function enableAutosave(): void /** * Turns autosave off. * @group Notes */ export function disableAutosave(): void /** * Sets how long after the last edit autosave runs (1000 ms by default). Values that are not non-negative numbers are ignored with a warning. * @param ms The delay in milliseconds. * @group Notes */ export function setAutosaveInterval(ms?: number): void /** * Pressing Enter alone submits in the reply box (Shift+Enter adds a new line). * @group Notes */ export function enableNoteSubmissionWithEnter(): void /** * Turns off submitting with Enter. * @group Notes */ export function disableNoteSubmissionWithEnter(): void /** * Appends an item to the date / time dropdown of the custom stamp dialog (dayjs tokens; date and time are joined by a space, time first when timeFirst). * Ignored with console.error when it is not an object or has neither key. * @param dateTimeFormat `{ date?, time?, timeFirst? }`. * @param dateTimeFormat.date Date format, such as `'YYYY-MM-DD'`. * @param dateTimeFormat.time Time format, such as `'HH:mm'`. * @param dateTimeFormat.timeFirst When true, the time is shown before the date. * @example * ```js * instance.UI.addDateTimeFormat({ date: 'YYYY-MM-DD', time: 'HH:mm' }); * ``` * @group Notes */ export function addDateTimeFormat(dateTimeFormat: { date?: string time?: string timeFirst?: boolean }): void /** * Sets the IANA time zone (such as "Europe/London") used for notes list dates. Invalid names are ignored with a warning. * @param timezone The time zone name. * @example * ```js * instance.UI.setTimezone('America/New_York'); * ``` * @group Notes */ export function setTimezone(timezone: string): void /** * Sets the read state of an annotation (all are read by default). Unread items show a blue frame and dot in the notes list and become read when clicked. * @param options `{ isRead, annotationId }`. * @param options.isRead `false` marks the annotation unread. * @param options.annotationId The id of the annotation. * @example * ```js * const { annotationManager } = instance.Core; * annotationManager.addEventListener('annotationChanged', (annotations, action, { imported }) => { * if (action === 'add' && imported) * annotations.forEach(annotation => instance.UI.setAnnotationReadState({ isRead: false, annotationId: annotation.Id })); * }); * ``` * @group Notes */ export function setAnnotationReadState(__0: { isRead: boolean annotationId: string }): void /** * Gets the read state of an annotation. Throws an Error when the annotation is not found. * Returns true for read annotations. * @param annotationId The annotation id. * @returns `true` when read. * @example * ```js * const [annotation] = instance.Core.annotationManager.getSelectedAnnotations(); * const isRead = instance.UI.getAnnotationReadState(annotation.Id); * ``` * @group Notes */ export function getAnnotationReadState(annotationId: string): boolean | undefined /** * Re-reads the outline of the active viewer and shows it in the outline panel. A read failure is only logged; the Promise does not reject. * @returns A Promise that resolves when the outline is reloaded. * @group Outline and bookmarks */ export function reloadOutline(): Promise /** * Sets a handler that decides how to jump when an outline item is clicked: `handler(outline, defaultJump)`. * `outline` is a Core.Bookmark; `defaultJump()` performs the default jump (aligns the target with the top of the viewport, and with its left edge when the page is wider than the viewport). Pass null to restore the default. * On phones the left panel still collapses after the jump; errors thrown by the handler are only logged. * @param handler The jump handler, or `null`. * @group Outline and bookmarks */ export function setCustomOutlineJumpHandler(handler: OutlineJumpHandler | null): void /** * UI.OutlinesPanel: outline panel settings. setDefaultOptions({ autoExpandOutlines }) sets whether a newly opened document's outline is fully expanded (collapsed by default). * @group Outline and bookmarks */ export const OutlinesPanel: OutlinesPanelAPI /** * Exports the user bookmarks. * @param documentViewerKey The viewer key; the active viewer by default. * @returns An object mapping 0-based page indexes to bookmark texts. * @group Outline and bookmarks */ export function exportBookmarks(documentViewerKey?: number): Record /** * Replaces all user bookmarks with the given ones (existing bookmarks not in the object are removed). * @param bookmarks An object mapping 0-based page indexes to bookmark texts. * @param documentViewerKey The viewer key; the active viewer by default. * @group Outline and bookmarks */ export function importBookmarks(bookmarks: Record, documentViewerKey?: number): void /** * Shows a bookmark icon at the top right of each page (click to add or remove the page's bookmark). Off by default. * @group Outline and bookmarks */ export function enableBookmarkIconShortcutVisibility(): void /** * Hides the bookmark icon shown by `enableBookmarkIconShortcutVisibility`. * @group Outline and bookmarks */ export function disableBookmarkIconShortcutVisibility(): void /** * UI.ThumbnailsPanel (6 members). * @group Thumbnails and pages */ export namespace ThumbnailsPanel { /** UI.ThumbnailsPanel.enableMultiSelect(): enters multi-select mode. */ export function enableMultiSelect(): void /** UI.ThumbnailsPanel.disableMultiSelect(): leaves multi-select mode. */ export function disableMultiSelect(): void /** * Adds pages to the thumbnail selection and triggers `UI.Events.SELECTED_THUMBNAIL_CHANGED`. Requires the `ThumbnailMultiselect` feature (on by default). * Non-arrays, the feature being off, already selected pages and out-of-range pages are ignored with a warning; duplicates count once. * The default thumbnails panel does not draw this selection. * @example * ```js * instance.UI.addEventListener(instance.UI.Events.SELECTED_THUMBNAIL_CHANGED, (pageIndexes) => { * console.log('selected page indexes:', pageIndexes); * }); * instance.UI.ThumbnailsPanel.selectPages([1, 3]); * ``` */ export function selectPages(pageNumbers: number[]): void /** * Removes pages (1-based page numbers) from the thumbnail selection; pages not selected are ignored. * @example * ```js * instance.UI.ThumbnailsPanel.unselectPages([3]); * ``` */ export function unselectPages(pageNumbersToDeselect: number[]): void /** * Gets the selected thumbnail pages as 1-based page numbers. * @example * ```js * const pages = instance.UI.ThumbnailsPanel.getSelectedPageNumbers(); // for example [1, 3] * ``` */ export function getSelectedPageNumbers(): number[] /** Same as `UI.setThumbnailSelectionMode`. */ export function setThumbnailSelectionMode(thumbnailSelectionMode: ThumbnailSelectionMode): void } /** * Sets the thumbnail selection mode (UI.setThumbnailSelectionMode and UI.ThumbnailsPanel.setThumbnailSelectionMode share this implementation): * 'checkbox' (default, select by clicking the checkbox) | 'thumbnail' (select by clicking the whole thumbnail). Other values are ignored with console.error. Stored only: the default thumbnails have no multi-select UI. * @param thumbnailSelectionMode `'checkbox'` or `'thumbnail'`. * @group Thumbnails and pages */ export function setThumbnailSelectionMode(thumbnailSelectionMode: ThumbnailSelectionMode): void /** * UI.pageManipulationOverlay: items of the thumbnail page operation menu. By default three preset groups (move / rotate / page operations) and two dividers; * custom groups are `{ type: 'customPageOperation', header, dataElement, operations: [{ title, img, onClick(selectedPageNumbers), dataElement }] }`. * Only the items are stored; there is no thumbnail page operation menu to sync (`pageManipulationFlyout`), and `getItems` reads the same item list. * @group Thumbnails and pages */ export const pageManipulationOverlay: PageManipulationOverlayAPI /** * UI.multiPageManipulationControls: items of the batch bar shown when several thumbnails are selected; by default three preset groups (rotate / move / more) and two dividers. Items are stored only. * @group Thumbnails and pages */ export const multiPageManipulationControls: ItemListAPI /** * UI.thumbnailControlMenu: items of the "more" menu shown when hovering a thumbnail; `thumbRotateClockwise` and `thumbDelete` by default. * Items are `{ title, img, onClick(selectedPageNumbers), dataElement }`. Items are stored only. * @group Thumbnails and pages */ export const thumbnailControlMenu: ItemListAPI /** * Sets custom page labels (the page number text under thumbnails). * Labels must be unique (throws otherwise). When the count equals the page count, custom labels are turned on; otherwise they are stored but not used. They reset to 1..N when the document or pages change. * Page labels stored in the PDF are not read. * @param pageLabels One label per page. * @param documentViewerKey The viewer key; the active viewer by default. * @group Thumbnails and pages */ export function setPageLabels(pageLabels: string[], documentViewerKey?: number): void /** * Extracts pages (with their annotations) as a PDF File. Rejects when a page number is out of range or there is no document. * @param pageNumbersToExtract The 1-based page numbers. * @returns A Promise that resolves with the PDF File. * @group Thumbnails and pages */ export function extractPagesWithAnnotations(pageNumbersToExtract: number[]): Promise /** * Deleting pages in the page editor no longer asks for confirmation. * @group Thumbnails and pages */ export function disablePageDeletionConfirmationModal(): void /** * Deleting pages in the page editor asks for confirmation (the default). * @group Thumbnails and pages */ export function enablePageDeletionConfirmationModal(): void /** * Applying a crop no longer asks for confirmation. Stored only: there is no document crop dialog. * @group Thumbnails and pages */ export function disableApplyCropWarningModal(): void /** * Applying a crop asks for confirmation. Stored only. * @group Thumbnails and pages */ export function enableApplyCropWarningModal(): void /** * "Crop and delete" snipping no longer asks for confirmation. Stored only: the snipping tool only downloads and has no such confirmation. * @group Thumbnails and pages */ export function disableApplySnippingWarningModal(): void /** * "Crop and delete" snipping asks for confirmation. Stored only. * @group Thumbnails and pages */ export function enableApplySnippingWarningModal(): void /** * Adds a preset to the crop dialog (in inches). Invalid presets are ignored with console.error. Stored only: there is no document crop dialog. * @param presetName The preset name. * @param newPreset `{ yOffset, height, xOffset, width }`. * @group Thumbnails and pages */ export function setPresetCropDimensions(presetName: string, newPreset: PresetCropDimension): void /** * Adds a blank page size preset to the insert page dialog (in inches). Invalid presets are ignored with console.error. * The size dropdown of the page editor's insert / merge page dialog lists them after A3 / A4 / A5. * @param presetName The preset name. * @param newPreset `{ height, width }`. * @group Thumbnails and pages */ export function setPresetNewPageDimensions(presetName: string, newPreset: PresetNewPageDimension): void /** * Sets the options of the replacement page dialog's file dropdown: `{ id, filename, onSelect() => Document }`. * Ignored with a warning when an item is not an object or has none of id / filename / onSelect. Stored only: the page editor's Replace opens the system file picker and has no such dialog. * @param list The file options. * @group Thumbnails and pages */ export function setPageReplacementModalFileList(list: PageReplacementFile[]): void /** * Enters the page editor. Resolves once the working copy is created; does nothing when already in it. * Rejects when there is no document, the page assembly permission is missing (the permission password dialog was cancelled) or the copy fails (the previous toolbar group is restored). * @returns A Promise that resolves once the page editor is ready. * @example * ```js * await instance.UI.enterPageEditorMode(); * console.log(instance.UI.isInPageEditorMode()); // true * ``` * @group Page editor */ export function enterPageEditorMode(): Promise /** * Leaves the page editor and discards the working copy; the main document is unchanged and the View group is shown. Does nothing outside the page editor. * @returns A Promise that resolves once the page editor is closed. * @example * ```js * await instance.UI.exitPageEditorMode(); * ``` * @group Page editor */ export function exitPageEditorMode(): Promise /** * Tells whether the page editor is open. * @returns `true` while the page editor is open. * @group Page editor */ export function isInPageEditorMode(): boolean /** * Reloads the active viewer with the working copy (does not download). Does nothing outside the page editor. * @returns A Promise that resolves once the document is reloaded. * @example * ```js * // Apply the page changes, then download the result * await instance.UI.savePageEditor(); * await instance.UI.downloadPdf(); * ``` * @group Page editor */ export function savePageEditor(): Promise /** * Shows the Save button of the page editor header. * @group Page editor */ export function enablePageEditorSave(): void /** * Hides the Save button of the page editor header. * @group Page editor */ export function disablePageEditorSave(): void /** * Shows the Save As button of the page editor header. * @group Page editor */ export function enablePageEditorSaveAs(): void /** * Hides the Save As button of the page editor header. * @example * ```js * instance.UI.disablePageEditorSaveAs(); * ``` * @group Page editor */ export function disablePageEditorSaveAs(): void /** * Sets a handler that replaces the default redaction applying after Save is clicked in the redaction confirmation: `handler(annotationsToRedact, originalApplyRedactions)` * (`originalApplyRedactions()` performs the default applying and returns a Promise). Cleanup waits for the Promise returned by the handler. Pass null to restore the default. * @param handler The handler, or `null`. * @example * ```js * instance.UI.setCustomApplyRedactionsHandler(async (annotationsToRedact, originalApplyRedactions) => { * if (window.confirm(`Apply ${annotationsToRedact.length} redaction(s)?`)) * await originalApplyRedactions(); * }); * ``` * @group Redaction */ export function setCustomApplyRedactionsHandler(handler: CustomApplyRedactionsHandler | null): void /** * Adds a redaction search pattern. * @param pattern `{ label, icon?, type, regex }`. * @group Redaction */ export function addRedactionSearchPattern(pattern: RedactionSearchPattern): void /** * Replaces the regular expression of a redaction search pattern. * @param type The pattern type. * @param regex The new regular expression. * @group Redaction */ export function replaceRedactionSearchPattern(type: string, regex: RegExp): void /** * Removes a redaction search pattern. * @param type The pattern type. * @group Redaction */ export function removeRedactionSearchPattern(type: string): void /** * Sets the units offered by the two unit dropdowns of the measurement settings dialog. A missing list keeps its current value; unknown units are ignored with a warning. * Known units: `'in'`, `'mm'`, `'cm'`, `'pt'`, `'ft'`, `'ft-in'`, `'m'`, `'yd'`, `'km'`, `'mi'`. A selected unit that is not in the new list is still shown. * @param units `{ from, to }` lists of unit names. * @param units.from Units offered for the page distance, such as `'in'` or `'mm'`. * @param units.to Units offered for the real-world distance. * @example * ```js * instance.UI.setMeasurementUnits({ from: ['mm', 'cm', 'in'], to: ['m', 'km'] }); * ``` * @group Measurement */ export function setMeasurementUnits(__0?: { from?: string[] to?: string[] }): void /** * Sets custom rows for the measurement overlay. * @param info An array of `{ title, label, validate, value, onChange }`. * @group Measurement */ export function setCustomMeasurementOverlayInfo(info: unknown[]): void /** * Gets the scale presets of a measurement system as `[displayName, Scale]` pairs. Defaults: metric 1:10 to 1:1000, imperial 1/16" to 1". * @param system `'metric'` or `'imperial'`. * @returns The presets. * @group Measurement */ export function getMeasurementScalePreset(system: MeasurementSystem): Array<[string, Scale]> /** * Adds a scale preset. * @param options `{ measurementSystem, displayName, presetScale, index }`. * @param options.measurementSystem `'metric'` or `'imperial'`. * @param options.displayName The text shown in the preset list. * @param options.presetScale The scale of the preset. * @param options.index Position in the list; appended when omitted. * @group Measurement */ export function addMeasurementScalePreset(__0: { measurementSystem: MeasurementSystem displayName: string presetScale: Scale index?: number }): void /** * Removes a scale preset. * @param system `'metric'` or `'imperial'`. * @param index The index of the preset. * @group Measurement */ export function removeMeasurementScalePreset(system: MeasurementSystem, index: number): void /** * Turns on multiple scales mode. The setting is stored, but the default UI does not use it yet. * @group Measurement */ export function enableMultipleScalesMode(): void /** * Turns off multiple scales mode. The setting is stored, but the default UI does not use it yet. * @group Measurement */ export function disableMultipleScalesMode(): void /** * Tells whether multiple scales mode is on. * @returns `true` after `enableMultipleScalesMode`. * @group Measurement */ export function isMultipleScalesModeEnabled(): boolean /** * Sets the position of the scale overlay. * @param position `'top-left'`, `'top-right'`, `'bottom-left'` or `'bottom-right'`. * @group Measurement */ export function setScaleOverlayPosition(position: ScaleOverlayPosition): void /** * The font lists of the viewer: the font dropdowns, the fonts of the signature dialog's type tab and the font sizes of the content editing panel. * @group Fonts */ export const Fonts: FontsAPI /** * Sets the directory of UI font files (a trailing slash is added). Stored per instance; the UI still finds fonts through webFontURL / customFontURL, so only the value is kept. * @param path The font directory. * @group Fonts */ export function setFontPath(path: string): void /** * Gets the path set by `setFontPath`. * @returns The font path, or `null` when never set. * @group Fonts */ export function getFontPath(): string | null /** * Gets the custom stamps (PNG data URLs, newest first). * @returns A copy of the list. * @example * ```js * const stamps = instance.UI.getCustomStamps(); * ``` * @group Stamps */ export function getCustomStamps(): string[] /** * Adds custom stamps to the front of the custom stamp list; the list is remembered by the browser. * @param images A PNG data URL or an array of them. * @example * ```js * const canvas = document.createElement('canvas'); * canvas.width = 200; * canvas.height = 60; * const context = canvas.getContext('2d'); * context.fillStyle = '#d32f2f'; * context.font = 'bold 36px sans-serif'; * context.fillText('PAID', 50, 45); * instance.UI.addCustomStamps(canvas.toDataURL('image/png')); * ``` * @group Stamps */ export function addCustomStamps(images: string | string[]): void /** * Replaces all custom stamps. * @param images PNG data URLs. * @example * ```js * instance.UI.setCustomStamps([]); // remove all custom stamps * ``` * @group Stamps */ export function setCustomStamps(images: string[]): void /** * Sets the tabs of the stamp panel (`type: 'tab'` for the built-in STANDARD / DYNAMIC / CUSTOM, `type: 'custom'` for an import tab). * @param tabs The tabs. * @group Stamps */ export function setStampPanelTabs(tabs: StampPanelTab[]): void /** * Sets the image stamps shown on the import tab. * @param images Image data URLs. * @group Stamps */ export function setImportStamps(images: string[]): void /** * Sets how many signature templates can be saved; without an argument, back to the default 5. Anything but a non-negative integer is ignored with a warning. * @param maxSignaturesCount The maximum count. * @example * ```js * instance.UI.setMaxSignaturesCount(3); * ``` * @group Signatures */ export function setMaxSignaturesCount(maxSignaturesCount?: number): void /** * Sets the fonts for typed signatures. Accepts an array, a single string, or a callback that receives the current fonts and returns new ones. * @param fonts The fonts, or a callback. * @example * ```js * instance.UI.setSignatureFonts(['Arial', 'Courier New']); * // or keep the current fonts and add one * instance.UI.setSignatureFonts(fonts => [...fonts, 'Georgia']); * ``` * @group Signatures */ export function setSignatureFonts(fonts: string | string[] | ((currentFonts: string[]) => string[])): void /** * Sets the color swatches of the signature dialog (used when a tab has no override of its own). 1 to 3 colors; otherwise ignored with a warning. * Any CSS color syntax is accepted (#RGB, rgb(), hsl(); the defaults are rgb()). * @param colors The colors. * @example * ```js * instance.UI.setSignatureModalColors(['#000000', '#1a237e', '#b71c1c']); * ``` * @group Signatures */ export function setSignatureModalColors(colors: string[]): void /** * Sets which signing tabs the signature dialog shows and their order (keyboard / trackpad / image by default). * @param tabs The tabs. * @example * ```js * instance.UI.setSignatureDialogTabs(['trackpad', 'image']); * ``` * @group Signatures */ export function setSignatureDialogTabs(tabs: SignatureDialogTab[]): void /** * Changes the signature dialog per tab (keyboard / trackpad): * swatches, the custom color switch, fonts (keyboard only), the line width switch and default line width (trackpad only). With replace false only the given items change; with true the whole tab is replaced (missing items go back to defaults). * Swatches accept `{ type: 'color', value }` and strings; fonts accept strings and `{ fontFamily, label, fontWeight }`. * @param type `'keyboard'` or `'trackpad'`. * @param properties The properties to set. * @param replace Whether to replace the whole tab; `false` by default. * @example * ```js * instance.UI.setSignatureDialogProperties('trackpad', { * colors: ['#000000', '#0d47a1'], * enableLineWidth: true, * lineWidth: 3, * }); * ``` * @group Signatures */ export function setSignatureDialogProperties(type: 'keyboard' | 'trackpad', properties: SignatureDialogPropertiesArg, replace?: boolean | undefined): void /** * Settings of digital signature verification. `addTrustedCertificates` adds certificates (PEM or DER; Files and bytes are read now, URLs are downloaded at every verification) * to the trust list of the active viewer, which is used on every verification; an open document is verified again right away. * @group Signatures */ export const VerificationOptions: VerificationOptionsAPI /** * Sets which saved signatures are shown in the signature dialog; changing the function takes effect immediately. * Signatures not yet restored as annotations from storage (right after opening, before the signature tool loads them) cannot be passed to the callback and are always shown. * @param filterFunction `(annotation, index) => boolean`. * @group Signatures */ export function setDisplayedSignaturesFilter(filterFunction: (annotation: unknown, index: number) => boolean): void /** * Shows a disclaimer at the bottom of the dialog's create page; the text is the language key message.signatureDisclaimer (changeable through UI.setTranslations). * @group Signatures */ export function enableSignatureDisclaimer(): void /** * Hides the signature disclaimer. * @group Signatures */ export function disableSignatureDisclaimer(): void /** * Sets the scale used when drawing typed signatures as images (1 by default); larger is sharper but uses more memory. * Must be a positive number; otherwise ignored with a warning (0 or negative values would draw an empty image). * @param multiplier The scale. * @group Signatures */ export function setTextSignatureQuality(multiplier: number): void /** * Gets the scale set by `setTextSignatureQuality`. * @returns The scale. * @group Signatures */ export function getTextSignatureQuality(): number /** * Signs a signature field. * With a signature (ink or image stamp), it is signed directly at the field's size and rotation (core SignatureWidgetAnnotation#sign, no placement flow); * without one, it acts as if the user clicked the field: pick a saved signature or start creating one. Throws an Error for read-only fields; does nothing for fields already signed. * With a signature given, the signature tool's signatureReady event is not triggered (the core's sign does not trigger it). * @param signatureWidget The signature widget annotation. * @param signature The signature annotation to apply. * @returns A Promise that resolves once signed. * @group Signatures */ export function signSignatureWidget(signatureWidget: unknown, signature?: unknown): Promise /** * Reads and drives the form fill navigator (stepping through the fields to fill), per document viewer. * @group Forms */ export namespace FormFill { /** * Returns the navigator settings. * @param key The document viewer key; defaults to the active viewer. * @returns The current settings. */ export function getSettings(key?: number): { /** Which fields the form fill navigator steps through; false turns consecutive filling off. */ readonly type: FormFillConsecutive /** Only required fields are visited and counted. */ readonly skipNonRequired: boolean /** Whether fields to fill are outlined and filling a field moves to the next one after 500 ms; true by default. */ readonly enabled: boolean /** Order of the fields: 'CREATE' keeps the document order, 'DISTANCE' (default) sorts by page, then from top to bottom. */ readonly order: 'CREATE' | 'DISTANCE' /** Also visits fields marked as not shown on screen (NoView); false by default. */ readonly includeNoView: boolean /** The current field follows the field that has focus (or the check box or radio button last changed) instead of the field reached with Previous / Next; false by default. */ readonly preferFocused: boolean /** Forces fill mode on (true) or off (false) in the forms toolbar group; null (default) follows the form design mode. */ readonly fillMode: boolean | null } /** * Changes some navigator settings; settings not in `patch` keep their values. * @param patch The settings to change. * @param key The document viewer key; defaults to the active viewer. */ export function setSettings(patch: { /** Which fields the form fill navigator steps through; false turns consecutive filling off. */ type?: FormFillConsecutive /** Only required fields are visited and counted. */ skipNonRequired?: boolean /** Whether fields to fill are outlined and filling a field moves to the next one after 500 ms; true by default. */ enabled?: boolean /** Order of the fields: 'CREATE' keeps the document order, 'DISTANCE' (default) sorts by page, then from top to bottom. */ order?: 'CREATE' | 'DISTANCE' /** Also visits fields marked as not shown on screen (NoView); false by default. */ includeNoView?: boolean /** The current field follows the field that has focus (or the check box or radio button last changed) instead of the field reached with Previous / Next; false by default. */ preferFocused?: boolean /** Forces fill mode on (true) or off (false) in the forms toolbar group; null (default) follows the form design mode. */ fillMode?: boolean | null }, key?: number): void /** * Returns the fields the navigator steps through, in navigation order, filtered by the current settings. * @param key The document viewer key; defaults to the active viewer. * @returns The field widgets; empty when navigation has no field type selected. */ export function getFields(key?: number): WidgetLike[] /** * Returns the field recorded as current by the navigator, whether or not it is still in the field list. * @param key The document viewer key; defaults to the active viewer. * @returns The field widget, or `null`. */ export function getCurrentCandidate(key?: number): unknown /** * Records a field as current without jumping to it, and cancels a pending move to the next field. * @param widget A field widget of this viewer, or `null` to clear. * @param key The document viewer key; defaults to the active viewer. */ export function setCurrentCandidate(widget: unknown | null, key?: number): void /** * Returns the current field if it is in the field list. With `preferFocused` set, the focused field comes first. * @param key The document viewer key; defaults to the active viewer. * @param candidates The field list to check against; defaults to `getFields()`. * @returns The field widget, or `null`. */ export function getCurrent(key?: number, candidates?: readonly unknown[]): unknown /** * Returns the field after or before the current one, wrapping around the list. * @param delta `1` for the next field, `-1` for the previous one. * @param key The document viewer key; defaults to the active viewer. * @returns The field widget, or `null` when there is no current field. */ export function getAdjacent(delta: 1 | -1, key?: number): unknown } /** * Collapses or expands the form fill navigator. * @param collapsed `true` to collapse. * @group Forms */ export function setFormFillNavigatorCollapsed(collapsed: boolean): void /** * Moves the form fill navigator. Partial updates are allowed (only left or top). Coordinates are relative to the instance root element * and are clamped to the instance area (negatives become 0; while shown, it cannot pass the right / bottom edges of the App root, as when dragging). Throws a TypeError for non-objects. * @param position `{ left, top }` in CSS pixels. * @group Forms */ export function setFormFillNavigatorPosition(position: { /** Distance from the left edge of the viewer, in px; 30 by default. */ left?: number /** Distance from the top edge of the viewer, in px; 100 by default. */ top?: number }): void /** * Enables formFieldIndicatorContainer so field indicator labels are visible (only for fields that have the indicator turned on). * @group Forms */ export function showFormFieldIndicators(): void /** * Disables formFieldIndicatorContainer; no field indicator labels are drawn. * @group Forms */ export function hideFormFieldIndicators(): void /** * Loads a file into the "old" or "new" pane of the compare page (`flag` is `'old'` or `'new'`). * Switches to the compare group first when needed. Does nothing without a file or with any other flag. A failed load does not reject * (the pane quietly resets, as with drag and drop; an invalid license is reported through LOAD_ERROR). * @param file The document source or a loaded Document. * @param filename The file name to show. * @param password The document password. * @param flag `'old'` or `'new'`. * @returns A Promise that resolves when loading finishes. * @group Compare */ export function loadCompareDocument(file: DocumentSource | Document, filename: string | undefined, password: string | undefined, flag: 'old' | 'new' | undefined): Promise /** * Enters side-by-side mode (left key 1, right key 2). Resolves once the right pane is ready and triggers UI.Events.MULTI_VIEWER_READY. * From the compare / page editor / color separation / content editing groups, returns to the View group first. Does nothing when already in it. * Rejects when the UI is not mounted (the second pane's DOM never appears) or the instance is destroyed. * @returns A Promise that resolves once the right pane is ready. * @example * ```js * await instance.UI.enterMultiViewerMode(); * await Promise.all([ * instance.UI.loadDocument('/files/contract-v1.pdf', {}, 1), * instance.UI.loadDocument('/files/contract-v2.pdf', {}, 2), * ]); * instance.UI.enableMultiViewerSync(1); * ``` * @group Compare */ export function enterMultiViewerMode(): Promise /** * Leaves side-by-side mode: stops sync and comparison, makes key 1 active again and unmounts the right pane. Does nothing when not in it. * @returns A Promise that resolves once the mode is left. * @example * ```js * await instance.UI.exitMultiViewerMode(); * ``` * @group Compare */ export function exitMultiViewerMode(): Promise /** * Compares the text of the two panes page by page and highlights the differences on both sides. Requires enterMultiViewerMode first; otherwise logs an error and returns. * If the two documents are not both loaded yet, waits until they are. * @returns A Promise that resolves once the comparison is shown. * @example * ```js * await instance.UI.enterMultiViewerMode(); * await instance.UI.loadDocument('/files/contract-v1.pdf', {}, 1); * await instance.UI.loadDocument('/files/contract-v2.pdf', {}, 2); * await instance.UI.startTextComparison(); * ``` * @group Compare */ export function startTextComparison(): Promise /** * Ends the comparison and removes the difference annotations on both sides. * @returns A Promise that resolves once the comparison is stopped. * @example * ```js * await instance.UI.stopTextComparison(); * ``` * @group Compare */ export function stopTextComparison(): Promise /** * Turns on side-by-side sync (zoom, scrolling / page turning). The primary key can only be 1 or 2; anything else means 1. Sync starts once both documents are loaded. * @param primaryViewerKey The key of the primary viewer. * @example * ```js * instance.UI.enableMultiViewerSync(1); * ``` * @group Compare */ export function enableMultiViewerSync(primaryViewerKey?: number): void /** * Turns off side-by-side sync. * @group Compare */ export function disableMultiViewerSync(): void /** * Tells whether side-by-side sync is turned on (the switch, not whether the panes are actually linked yet). * @returns `true` when sync is on. * @group Compare */ export function isMultiViewerSyncing(): boolean /** * Sets the sync scrolling mode: `'SYNC'` or `'SKIP_UNMATCHED'`; other values throw a TypeError. * Defaults to `'SYNC'`. `'SKIP_UNMATCHED'` needs page matching from the comparison result, which the core does not provide, so it is stored but behaves like `'SYNC'`. * @param mode `'SYNC'` or `'SKIP_UNMATCHED'`. * @group Compare */ export function setMultiViewerSyncScrollingMode(mode: MultiViewerSyncScrollMode): void /** * Sets a custom sync handler: when sync starts, `handler(primaryViewerKey, removeHandlerFunctions)` is called; * the handler pushes the removal functions of its listeners into the array, and they are all called when sync stops. The built-in zoom / scroll sync is set up first and the handler runs after it (it adds to, not replaces, the built-in sync). * Pass null / undefined to clear it. * @param handler The sync handler. * @group Compare */ export function setCustomMultiViewerSyncHandler(handler: CustomMultiViewerSyncHandler | null | undefined): void /** * Sets the file extensions accepted by the right pane's "choose file" (with or without the leading dot). * Only extensions the viewer can open are kept; pass null / undefined to restore the default. * @param formats The accepted extensions. * @example * ```js * instance.UI.setCustomMultiViewerAcceptedFileFormats(['pdf']); * ``` * @group Compare */ export function setCustomMultiViewerAcceptedFileFormats(formats: string[] | null | undefined): void /** * UI.hotkeys: keyboard shortcut controls for this instance. * - `on(key?, handler?)`: registers a custom handler (a function is called on keydown; `{ keydown, keyup }` is called on each). Without a handler, binds the key to its built-in shortcut * (for example `Keys.CTRL_EQUAL` zooms in). Without arguments, resumes all shortcuts. Keys are written like `ctrl+shift+=`, comma-separated for several. * - `off(key?, handler?)`: removes the key's custom handlers and stops its built-in shortcut; with a handler, removes only that one. Without arguments, pauses all shortcuts. * - `trigger(key, eventType?)`: runs the handler bound in the key map without a real key press; eventType is `'keydown'` (default) or `'keyup'`. * @group Keyboard shortcuts */ export namespace hotkeys { /** * Binds keys. With a handler, the handler is called on keydown (a function) or on keydown and keyup (`{ keydown, keyup }`). * Without a handler, the key gets its built-in shortcut back, for example `Keys.CTRL_EQUAL` zooms in. Without arguments, all shortcuts resume. * @param key Keys such as `ctrl+shift+=`; separate several with commas. * @param handler The function or `{ keydown, keyup }` object to call. * @example * ```js * // A custom shortcut * instance.UI.hotkeys.on('ctrl+shift+d, command+shift+d', (event) => { * event.preventDefault(); * instance.UI.downloadPdf(); * }); * // Give back a built-in shortcut that was turned off * instance.UI.hotkeys.on(instance.UI.hotkeys.Keys.CTRL_EQUAL); * ``` */ export function on(key?: string, handler?: ((event: KeyboardEvent) => unknown) | { /** Called when the shortcut key is pressed. */ keydown?: (event: KeyboardEvent) => unknown /** Called when the shortcut key is released. */ keyup?: (event: KeyboardEvent) => unknown }): void /** * Unbinds keys. With a handler, only that handler is removed; otherwise the key's custom handlers and its built-in shortcut stop. * Without arguments, all shortcuts pause. * @param key Keys such as `ctrl+shift+=`; separate several with commas. * @param handler The handler to remove. * @example * ```js * // Turn off the built-in undo and redo shortcuts * const { Keys } = instance.UI.hotkeys; * instance.UI.hotkeys.off(`${Keys.CTRL_Z},${Keys.COMMAND_Z},${Keys.CTRL_Y},${Keys.COMMAND_SHIFT_Z}`); * ``` */ export function off(key?: string, handler?: ((event: KeyboardEvent) => unknown) | { /** Called when the shortcut key is pressed. */ keydown?: (event: KeyboardEvent) => unknown /** Called when the shortcut key is released. */ keyup?: (event: KeyboardEvent) => unknown }): void /** * Runs the handler bound to a key without a real key press. * @param shortcut The key, for example `ctrl+z`. * @param eventType `'keydown'` (the default) or `'keyup'`. * @example * ```js * instance.UI.hotkeys.trigger(instance.UI.hotkeys.Keys.CTRL_Z); * ``` */ export function trigger(shortcut: string, eventType?: string): void /** Key strings for `UI.hotkeys.on` (`UI.hotkeys.Keys`). On macOS `command` is the Command key. */ export const Keys: { /** Key combination `ctrl+shift+=`. */ readonly CTRL_SHIFT_EQUAL: 'ctrl+shift+=' /** Key combination `command+shift+=`. */ readonly COMMAND_SHIFT_EQUAL: 'command+shift+=' /** Key combination `ctrl+shift+-`. */ readonly CTRL_SHIFT_MINUS: 'ctrl+shift+-' /** Key combination `command+shift+-`. */ readonly COMMAND_SHIFT_MINUS: 'command+shift+-' /** Key combination `ctrl+shift+num_add`. */ readonly CTRL_SHIFT_NUM_ADD: 'ctrl+shift+num_add' /** Key combination `command+shift+num_add`. */ readonly COMMAND_SHIFT_NUM_ADD: 'command+shift+num_add' /** Key combination `ctrl+shift+num_subtract`. */ readonly CTRL_SHIFT_NUM_SUBTRACT: 'ctrl+shift+num_subtract' /** Key combination `command+shift+num_subtract`. */ readonly COMMAND_SHIFT_NUM_SUBTRACT: 'command+shift+num_subtract' /** Key combination `ctrl+alt+shift+m`. */ readonly CTRL_ALT_SHIFT_M: 'ctrl+alt+shift+m' /** Key combination `command+alt+shift+m`. */ readonly COMMAND_ALT_SHIFT_M: 'command+alt+shift+m' /** Key combination `ctrl+c`. */ readonly CTRL_C: 'ctrl+c' /** Key combination `command+c`. */ readonly COMMAND_C: 'command+c' /** Key combination `ctrl+x`. */ readonly CTRL_X: 'ctrl+x' /** Key combination `command+x`. */ readonly COMMAND_X: 'command+x' /** Key combination `ctrl+v`. */ readonly CTRL_V: 'ctrl+v' /** Key combination `command+v`. */ readonly COMMAND_V: 'command+v' /** Key combination `ctrl+z`. */ readonly CTRL_Z: 'ctrl+z' /** Key combination `command+z`. */ readonly COMMAND_Z: 'command+z' /** Key combination `ctrl+y`. */ readonly CTRL_Y: 'ctrl+y' /** Key combination `command+shift+z`. */ readonly COMMAND_SHIFT_Z: 'command+shift+z' /** Key combination `ctrl+o`. */ readonly CTRL_O: 'ctrl+o' /** Key combination `command+o`. */ readonly COMMAND_O: 'command+o' /** Key combination `ctrl+f`. */ readonly CTRL_F: 'ctrl+f' /** Key combination `command+f`. */ readonly COMMAND_F: 'command+f' /** Key combination `ctrl+=`. */ readonly CTRL_EQUAL: 'ctrl+=' /** Key combination `command+=`. */ readonly COMMAND_EQUAL: 'command+=' /** Key combination `ctrl+-`. */ readonly CTRL_MINUS: 'ctrl+-' /** Key combination `command+-`. */ readonly COMMAND_MINUS: 'command+-' /** Key combination `ctrl+num_add`. */ readonly CTRL_NUM_ADD: 'ctrl+num_add' /** Key combination `command+num_add`. */ readonly COMMAND_NUM_ADD: 'command+num_add' /** Key combination `ctrl+num_subtract`. */ readonly CTRL_NUM_SUBTRACT: 'ctrl+num_subtract' /** Key combination `command+num_subtract`. */ readonly COMMAND_NUM_SUBTRACT: 'command+num_subtract' /** Key combination `ctrl+up`. */ readonly CTRL_UP: 'ctrl+up' /** Key combination `command+up`. */ readonly COMMAND_UP: 'command+up' /** Key combination `ctrl+down`. */ readonly CTRL_DOWN: 'ctrl+down' /** Key combination `command+down`. */ readonly COMMAND_DOWN: 'command+down' /** Key combination `ctrl+left`. */ readonly CTRL_LEFT: 'ctrl+left' /** Key combination `command+left`. */ readonly COMMAND_LEFT: 'command+left' /** Key combination `ctrl+right`. */ readonly CTRL_RIGHT: 'ctrl+right' /** Key combination `command+right`. */ readonly COMMAND_RIGHT: 'command+right' /** Key combination `ctrl+a`. */ readonly CTRL_A: 'ctrl+a' /** Key combination `command+a`. */ readonly COMMAND_A: 'command+a' /** Key combination `shift+up`. */ readonly SHIFT_UP: 'shift+up' /** Key combination `shift+down`. */ readonly SHIFT_DOWN: 'shift+down' /** Key combination `shift+left`. */ readonly SHIFT_LEFT: 'shift+left' /** Key combination `shift+right`. */ readonly SHIFT_RIGHT: 'shift+right' /** Key combination `ctrl+0`. */ readonly CTRL_0: 'ctrl+0' /** Key combination `command+0`. */ readonly COMMAND_0: 'command+0' /** Key combination `ctrl+p`. */ readonly CTRL_P: 'ctrl+p' /** Key combination `command+p`. */ readonly COMMAND_P: 'command+p' /** Key combination `ctrl+b`. */ readonly CTRL_B: 'ctrl+b' /** Key combination `command+b`. */ readonly COMMAND_B: 'command+b' /** Key combination `ctrl+i`. */ readonly CTRL_I: 'ctrl+i' /** Key combination `command+i`. */ readonly COMMAND_I: 'command+i' /** Key combination `ctrl+u`. */ readonly CTRL_U: 'ctrl+u' /** Key combination `command+u`. */ readonly COMMAND_U: 'command+u' /** Key combination `ctrl+k`. */ readonly CTRL_K: 'ctrl+k' /** Key combination `command+k`. */ readonly COMMAND_K: 'command+k' /** The enter key. */ readonly ENTER: 'enter' /** The pageup key. */ readonly PAGE_UP: 'pageup' /** The pagedown key. */ readonly PAGE_DOWN: 'pagedown' /** The up key. */ readonly UP: 'up' /** The down key. */ readonly DOWN: 'down' /** The left key. */ readonly LEFT: 'left' /** The right key. */ readonly RIGHT: 'right' /** The tab key. */ readonly TAB: 'tab' /** The space key. */ readonly SPACE: 'space' /** The escape key. */ readonly ESCAPE: 'escape' /** The home key. */ readonly HOME: 'home' /** The end key. */ readonly END: 'end' /** The delete key. */ readonly DELETE: 'delete' /** The P key. */ readonly P: 'p' /** The A key. */ readonly A: 'a' /** The C key. */ readonly C: 'c' /** The E key. */ readonly E: 'e' /** The F key. */ readonly F: 'f' /** The I key. */ readonly I: 'i' /** The L key. */ readonly L: 'l' /** The N key. */ readonly N: 'n' /** The O key. */ readonly O: 'o' /** The R key. */ readonly R: 'r' /** The Q key. */ readonly Q: 'q' /** The T key. */ readonly T: 't' /** The S key. */ readonly S: 's' /** The G key. */ readonly G: 'g' /** The H key. */ readonly H: 'h' /** The K key. */ readonly K: 'k' /** The U key. */ readonly U: 'u' /** The X key. */ readonly X: 'x' } /** Keyboard events a hotkey handler can run on. */ export const EventTypes: { /** Handle the shortcut on `keydown`. */ readonly KEYDOWN: 'keydown' /** Handle the shortcut on `keyup`. */ readonly KEYUP: 'keyup' } } /** * Sets the allowed swipe directions for turning pages: `'horizontal'`, `'vertical'` or `'both'`. * Defaults to `'both'`; swipe page turning only exists in full screen presentation. Invalid values are ignored with a warning. * @param swipeOrientation `'horizontal'`, `'vertical'` or `'both'`. * @group Mobile and touch */ export function setSwipeOrientation(swipeOrientation: string): void /** * Uses the browser's native scrolling on mobile. The state is stored only; the UI does not read it. * @group Mobile and touch */ export function enableNativeScrolling(): void /** * Turns native scrolling off. See `enableNativeScrolling`. * @group Mobile and touch */ export function disableNativeScrolling(): void /** * Fades the page navigation when idle. The state is stored only; the page number overlay stays visible. * @group Mobile and touch */ export function enableFadePageNavigationComponent(): void /** * Turns page navigation fading off. See `enableFadePageNavigationComponent`. * @group Mobile and touch */ export function disableFadePageNavigationComponent(): void /** * Uses the desktop layout on small screens too. The state is stored only; device detection is still the snapshot taken at load. * @group Mobile and touch */ export function enableDesktopOnlyMode(): void /** * Turns desktop-only mode off. See `enableDesktopOnlyMode`. * @group Mobile and touch */ export function disableDesktopOnlyMode(): void /** * Tells whether desktop-only mode is on. * @returns `true` when `enableDesktopOnlyMode` is in effect. * @group Mobile and touch */ export function isInDesktopOnlyMode(): boolean /** * Appends toggle rows (label, description, isChecked, onToggled) to the settings dialog. Toggling calls back immediately, without Save. * The settings dialog has no tabs, so the rows are appended at the end of its content; pass [] to remove them. * @param customSettings The rows to add. * @group Settings */ export function setCustomSettings(customSettings: CustomSettingItem[]): void /** * Exports the current user settings as a JSON object (`disableXxx: true` means the item is turned off). * @returns The user settings. * @group Settings */ export function exportUserSettings(): UserSettings /** * Imports user settings; only the given items change. * keyboardShortcut replaces the whole key map; shortcuts it does not list are unbound (set to an empty string). UI.hotkeys and key presses then follow the new map. * @param userSettings The user settings, as returned by `exportUserSettings`. * @group Settings */ export function importUserSettings(userSettings: { /** Language code of the UI, for example 'en'. */ language?: string /** UI theme: 'light' or 'dark'. */ theme?: string /** Key of each keyboard shortcut, keyed by shortcut name; an empty string means unbound. Importing it replaces the whole map, so shortcuts it does not list are unbound. */ keyboardShortcut?: Record /** Page navigation fading is off. Kept with the settings; it does not affect the UI (the page number overlay stays visible). */ disableFadePageNavigationComponent?: boolean /** Native scrolling on mobile is off. Kept with the settings; it does not affect the UI. */ disableNativeScrolling?: boolean /** Style changes made on an annotation are not copied to the tool defaults. Kept with the settings; the style panel follows UI.enableAnnotationToolStyleSyncing instead. */ disableToolDefaultStyleUpdateFromAnnotationPopup?: boolean /** Pressing Enter in the reply box adds a new line instead of submitting. */ disableNoteSubmissionWithEnter?: boolean /** Replies in the notes panel are shown only for the selected item, instead of expanded for every item. */ disableAutoExpandCommentThread?: boolean /** Reply collapsing in the notes panel is off. Kept with the settings; it does not affect the notes panel. */ disableReplyCollapse?: boolean /** Long note collapsing in the notes panel is off. Kept with the settings; it does not affect the notes panel. */ disableTextCollapse?: boolean /** Search results are kept when the search panel closes. */ disableClearSearchOnPanelClose?: boolean /** Pasted annotations keep their page positions instead of following their positions in the viewport. */ disableViewportRelativePositioning?: boolean /** The thumbnails panel is not in multi-select mode (see UI.ThumbnailsPanel.enableMultiSelect). Kept with the settings; it does not affect the thumbnails panel. */ disableThumbnailMultiselect?: boolean /** Deleting pages in the page editor does not ask for confirmation. */ disablePageDeletionConfirmationModal?: boolean }): void /** * Classes of the modular UI components, used to build headers, grouped items, flyouts and panels. * @group Modular UI */ export namespace Components { /** Base class of the items placed in modular headers, grouped items and flyouts. It cannot be instantiated directly; use one of its subclasses. */ export class Item { /** * Sets the options shared by all items (called by subclasses). * @param props Common options: dataElement, title, disabled, style, className and hidden. */ constructor(props?: { [x: string]: unknown; }) /** Unique name of the item; used to find, show, hide or update it later. */ dataElement: string /** Tooltip text, or a translation key that is resolved in the current language. */ title?: string | undefined /** Whether the item is disabled (rendered but not clickable). */ disabled?: boolean | undefined /** Item type (for example 'customButton', 'toolButton', 'divider'); set by each subclass. */ type?: string | undefined /** Inline CSS styles applied to the item's element. */ style?: Record | undefined /** Extra CSS class names added to the item's element. */ className?: string | undefined /** * Hides the item: `true` always hides it; an array of screen sizes (`'desktop'`, `'tablet'`, `'mobile'`, `'small-mobile'`) * hides it only on those screen sizes. */ hidden?: boolean | string[] | undefined /** * Replaces the inline CSS styles of the item and updates it on screen when it is already in the UI. * @param style CSS property names (camelCase) mapped to their values. */ setStyle(style: Record): void } /** * A group of items laid out together in a modular header; gap, grow and justifyContent control the layout. * @example * ```js * const { GroupedItems, PresetButton } = instance.UI.Components; * const historyGroup = new GroupedItems({ * dataElement: 'historyGroup', * gap: 4, * alwaysVisible: true, // otherwise a group in a header only shows while its ribbon item is active * items: [ * new PresetButton({ dataElement: 'myUndoButton', buttonType: instance.UI.PRESET_BUTTON_TYPES.UNDO }), * new PresetButton({ dataElement: 'myRedoButton', buttonType: instance.UI.PRESET_BUTTON_TYPES.REDO }), * ], * }); * const header = instance.UI.getModularHeader('default-top-header'); * header.setItems([...header.getItems(), historyGroup]); * ``` */ export class GroupedItems { /** * Creates a group of items. * @param props dataElement (required), items, gap, grow, justifyContent, alwaysVisible, style, hidden, label. */ constructor(props: ItemOptions) /** Optional label of the group. */ label?: string | undefined /** Unique name of the group. */ dataElement: string /** Placement value kept with the group's data; it does not affect the layout. */ placement?: string | undefined /** Position value kept with the group's data; it does not affect the layout. */ position?: string | undefined /** Items in the group, in display order; strings refer to existing items by dataElement. */ items: (string | object)[] /** Item type: 'groupedItems' ('ribbonGroup' for ribbon groups). */ type: string /** Whether the group stays visible regardless of the active ribbon item. */ alwaysVisible: boolean /** Inline CSS styles applied to the group's element. */ style: Record /** Hides the group: `true` always; an array of screen sizes (`'desktop'`, `'tablet'`, `'mobile'`, `'small-mobile'`) only on those. */ hidden?: boolean | string[] | undefined /** For flattening: the instance's own fields plus its own gap / grow / justifyContent (not read from the store, so a new instance with the same name does not bring back old values). */ toData(): Record /** Space between items, in pixels. */ gap: number /** Flex grow factor of the group within its header (0 means it does not grow). */ grow: number /** How items are distributed along the group ('start', 'end', 'center', 'space-between', 'space-around' or 'space-evenly'). */ justifyContent: string | undefined /** * Sets the space between items. Invalid values (negative or not a number) are ignored with a warning. * @param gap Space in pixels. */ setGap(gap: number): void /** * Sets how much the group grows to fill its header. Invalid values (negative or not a number) are ignored with a warning. * @param grow Flex grow factor. */ setGrow(grow: number): void /** * Sets how items are distributed along the group. Values outside the supported list are ignored with a warning. * @param justifyContent One of 'start', 'end', 'center', 'space-between', 'space-around', 'space-evenly'. */ setJustifyContent(justifyContent: string): void /** * Replaces the inline CSS styles of the group and updates it on screen. * @param style CSS property names (camelCase) mapped to their values. */ setStyle(style: Record): void /** Ribbon groups only accept RibbonItem, and other groups do not accept RibbonItem. Returns the error message, or false. */ getItemsValidationError(items: (string | object)[]): string | false /** * Replaces the items of the group. New item objects are registered in the UI; a ribbon group only accepts ribbon items and other groups do not accept them (invalid lists are ignored with a warning). * @param items Item objects, or dataElements of existing items. */ setItems(items: (string | object)[]): void } /** * A header bar placed on one side of the viewer that holds items and groups. * @example * ```js * const { ModularHeader, PresetButton, Zoom } = instance.UI.Components; * const bottomHeader = new ModularHeader({ * dataElement: 'myBottomHeader', * placement: 'bottom', * justifyContent: 'center', * items: [ * new Zoom({ dataElement: 'bottomZoom' }), * new PresetButton({ dataElement: 'bottomDownloadButton', buttonType: instance.UI.PRESET_BUTTON_TYPES.DOWNLOAD }), * ], * }); * instance.UI.addModularHeaders([bottomHeader]); * ``` */ export class ModularHeader { /** * Creates a header. * @param props dataElement and placement (required), items, gap, grow, justifyContent, position, float, maxWidth, maxHeight, opacityMode, opacity, stroke, style, label. */ constructor(props: ItemOptions) /** Item type: 'modularHeader'. */ type: string /** Optional label of the header. */ label?: string | undefined /** Unique name of the header. */ dataElement: string /** Side of the viewer the header is placed on: 'top', 'bottom', 'left' or 'right'. */ placement: string /** How items are distributed along the header ('start', 'end', 'center', 'space-between', 'space-around' or 'space-evenly'). */ justifyContent?: string | undefined /** Flex grow factor of the header (kept with the header data). */ grow: number /** Space between items, in pixels. */ gap: number /** Position of a floating header along its side: 'start' (default), 'center' or 'end'. */ position?: string | undefined /** Whether the header floats over the document instead of taking its own space. */ float: boolean /** Maximum width of the header, in pixels. */ maxWidth?: number | undefined /** Maximum height of the header, in pixels. */ maxHeight?: number | undefined /** Items in the header, in display order. */ items: (string | object)[] /** Opacity mode of a floating header: 'static' (default) or 'dynamic' (becomes opaque on hover or focus). */ opacityMode?: string | undefined /** Opacity level of a floating header: 'full' (default), 'low' or 'none'. */ opacity?: string | undefined /** Whether the header draws a border on the side facing the document; true by default. */ stroke: boolean /** Inline CSS styles applied to the header element. */ style: Record /** * Returns the items of the header, optionally only those of one type. * @param type Item type to keep, for example 'groupedItems' or 'toolButton'. * @returns The matching items. */ getItems(type?: string): (string | object)[] /** * Returns the grouped items of the header. * @returns Items whose type is 'groupedItems'. */ getGroupedItems(): (string | object)[] /** * Replaces the items of the header. Items of unknown types are dropped with a warning; new item objects are registered in the UI. * @param newItems An item or an array of items (objects or dataElements of existing items). * @example * ```js * const header = instance.UI.getModularHeader('default-top-header'); * // Remove the search button * header.setItems(header.getItems().filter(item => item.dataElement !== 'searchPanelToggle')); * ``` */ setItems(newItems: (string | object)[] | object): void /** * Sets the space between items. Invalid values are ignored with a warning. * @param gap Space in pixels. */ setGap(gap: number): void /** * Sets how items are distributed along the header. Invalid values are ignored with a warning. * @param justifyContent One of 'start', 'end', 'center', 'space-between', 'space-around', 'space-evenly'. */ setJustifyContent(justifyContent: string): void /** * Sets the maximum width of the header. Negative or non-numeric values are ignored with a warning. * @param maxWidth Width in pixels. */ setMaxWidth(maxWidth: number): void /** * Sets the maximum height of the header. Negative or non-numeric values are ignored with a warning. * @param maxHeight Height in pixels. */ setMaxHeight(maxHeight: number): void /** * Replaces the inline CSS styles of the header and updates it on screen. * @param style CSS property names (camelCase) mapped to their values. */ setStyle(style: Record): void } /** The same class as `ModularHeader`, named for a header at the top. */ export const TopHeader: typeof ModularHeader /** The same class as `ModularHeader`, named for a header at the bottom. */ export const BottomHeader: typeof ModularHeader /** The same class as `ModularHeader`, named for a header on the left. */ export const LeftHeader: typeof ModularHeader /** The same class as `ModularHeader`, named for a header on the right. */ export const RightHeader: typeof ModularHeader /** * A button with a custom label or icon that runs a callback when clicked. * @example * ```js * const button = new instance.UI.Components.CustomButton({ * dataElement: 'saveToServerButton', * img: 'Download', // a built-in icon name; an image URL or inline SVG markup also works * title: 'Save to server', * onClick: async () => { * const data = await instance.Core.documentViewer.getDocument().getFileData(); * // upload data ... * }, * }); * const header = instance.UI.getModularHeader('default-top-header'); * header.setItems([...header.getItems(), button]); * ``` */ export class CustomButton extends UI.Components.Item { /** * Creates a custom button. * @param props dataElement (required), label, img, title, onClick, isActive, disabled, style, className, hidden. */ constructor(props: ItemOptions) /** Text shown on the button, or a translation key. */ label?: string | undefined /** Icon of the button: a built-in icon name, an image URL or inline SVG markup (starting with ` 'Off', onClick: (update) => update('On') }, * On: { getContent: () => 'On', onClick: (update) => update('Off') }, * }, * }); * const header = instance.UI.getModularHeader('default-top-header'); * header.setItems([...header.getItems(), countButton]); * ``` */ export class StatefulButton extends UI.Components.Item { /** * Creates a stateful button. * @param props initialState and states (required), mount, unmount, dataElement, title. */ constructor(props: { [x: string]: unknown; }) /** Name of the state the button starts in. */ initialState: string /** The states of the button, keyed by state name. Each state may define img, title, getContent(state) and onClick(update, state). */ states: Record> /** Called when the button is added to the UI with update(stateName), which switches the state (without an argument it refreshes the content). */ mount?: unknown /** Called when the button is removed from the UI. */ unmount?: unknown } /** * A built-in button such as undo, redo, download or print, selected by `buttonType` (a value of `UI.PRESET_BUTTON_TYPES`). * @example * ```js * const printButton = new instance.UI.Components.PresetButton({ * dataElement: 'headerPrintButton', * buttonType: instance.UI.PRESET_BUTTON_TYPES.PRINT, * }); * const header = instance.UI.getModularHeader('default-top-header'); * header.setItems([...header.getItems(), printButton]); * ``` */ export class PresetButton extends UI.Components.Item { /** * Creates a built-in button. * @param props buttonType (required), dataElement (defaults to buttonType), img, label, title. */ constructor(props: { [x: string]: unknown; }) /** The built-in button to create (a value of UI.PRESET_BUTTON_TYPES). It is also used as the dataElement when none is given. */ buttonType: string /** Icon that replaces the built-in icon. */ img?: string | undefined /** Text shown on the button, or a translation key. */ label?: string | undefined /** Icon name of the built-in button. */ icon?: string | undefined } /** * A separator line between items. * @example * ```js * const divider = new instance.UI.Components.Divider({ dataElement: 'myDivider' }); * ``` */ export class Divider extends UI.Components.Item { /** * Creates a divider. * @param props dataElement (required), className, style. */ constructor(props: { [x: string]: unknown; }) /** Extra data kept with the divider. */ divider?: unknown } /** * An item rendered by your own function, for content the built-in items cannot express. * @example * ```js * const pageInfo = new instance.UI.Components.CustomElement({ * dataElement: 'pageInfo', * render: () => { * const span = document.createElement('span'); * span.textContent = 'Draft'; * return span; * }, * }); * const header = instance.UI.getModularHeader('default-top-header'); * header.setItems([...header.getItems(), pageInfo]); * ``` */ export class CustomElement extends UI.Components.Item { /** * Creates a custom element. * @param props dataElement and render (required), renderArguments, className, title. */ constructor(props: { [x: string]: unknown; }) /** Returns the content of the item: an HTMLElement or an HTML string. */ render: unknown /** Arguments passed to render. */ renderArguments?: unknown[] | undefined } /** The zoom control (zoom in, zoom out and the zoom level menu). Its dataElement defaults to 'zoom-container'. */ export class Zoom extends UI.Components.Item { /** * Creates the zoom control. * @param props dataElement (defaults to 'zoom-container'), className, hidden. */ constructor(props?: { [x: string]: unknown; }) } /** Text label: label is required; disabled defaults to false. */ export class Label extends UI.Components.Item { /** * Creates a label. * @param props dataElement and label (required), title, style. */ constructor(props: { [x: string]: unknown; }) /** Text of the label, or a translation key. */ label: string } /** Preset page navigation control: dataElement / title / icon are fixed; style it only through className and external stylesheets. */ export class PageControls extends UI.Components.Item { /** * Creates the page navigation control. * @param props className and hidden; dataElement, title and icon are fixed. */ constructor(props?: { [x: string]: unknown; }) /** Icon of the control (fixed). */ icon: string } /** Preset view controls: like PageControls, with the fixed dataElement view-controls. */ export class ViewControls extends UI.Components.Item { /** * Creates the view controls. * @param props className and hidden; dataElement, title and icon are fixed. */ constructor(props?: { [x: string]: unknown; }) /** Icon of the control (fixed). */ icon: string } /** * A pop-up menu of items, opened by a button whose toggleElement is the flyout's dataElement. Add it with UI.Flyouts.addFlyouts. * @example * ```js * const { Flyout, ToggleElementButton } = instance.UI.Components; * const exportFlyout = new Flyout({ * dataElement: 'exportFlyout', * items: [ * { label: 'Download PDF', onClick: () => instance.UI.downloadPdf() }, * 'divider', * { label: 'Print', onClick: () => instance.UI.print() }, * ], * }); * instance.UI.Flyouts.addFlyouts([exportFlyout]); * const header = instance.UI.getModularHeader('default-top-header'); * header.setItems([ * ...header.getItems(), * new ToggleElementButton({ dataElement: 'exportFlyoutToggle', toggleElement: 'exportFlyout', img: 'Download' }), * ]); * ``` */ export class Flyout { /** * Creates a flyout. * @param options The flyout's dataElement, items and toggleElement. */ constructor(options: FlyoutOptions) /** The flyout's data as added to the viewer by `UI.Flyouts.addFlyouts`. */ properties: FlyoutData /** Unique name of the flyout. */ dataElement: string /** Item type: 'flyout'. */ type: string /** dataElement of the element that opens the flyout. */ toggleElement?: string | undefined /** * Replaces the items of the flyout and updates it on screen. * @param items Flyout items: objects with label, onClick, icon or children, component instances, 'divider', or dataElements of existing items. */ setItems(items: unknown[]): void /** Items of the flyout; assigning a new array is the same as calling setItems. */ items: FlyoutItem[] } /** * The main ("more") menu: a Flyout whose dataElement defaults to `'MainMenuFlyout'`, so adding it with `UI.Flyouts.addFlyouts` replaces the default menu. * Its items are the default menu items followed by `additionalItems`. * @example * ```js * const mainMenu = new instance.UI.Components.MainMenu({ * additionalItems: [ * { label: 'About', onClick: () => instance.UI.openElements(['aboutModal']) }, * ], * }); * instance.UI.Flyouts.addFlyouts([mainMenu]); * ``` */ export class MainMenu extends UI.Components.Flyout { /** * Creates the main menu flyout. * @param options dataElement and additionalItems. */ constructor(options?: MainMenuOptions) } /** * A panel that shows other panels as tabs, passed to `UI.addPanel` or `UI.setPanels`. * Panels that cannot be shown as tabs (text editing, stamps) are dropped with an error message. * To change a tab panel that is already in the viewer, use the panel objects returned by `UI.getPanels()`. */ export class TabPanel { /** * Creates a tab panel. Panels that cannot be shown as tabs are dropped with an error message. * @param props dataElement, panelsList and location. */ constructor(props: TabPanelOptions) /** Unique name of the tab panel. */ dataElement: string /** Panels shown as tabs, in order. */ panelsList: TabPanelItem[] /** Side of the viewer the panel opens on: 'left' (default) or 'right'. */ location: string /** Always 'tabPanel'. */ render: string /** Always 'tabPanel'. */ type: string } } /** * Turns page focus on or off. When on, clicking a page highlights it until another page is clicked. Has no effect in the Compare, Document and Separation groups. * @param enabled `true` to turn page focus on. * @param key The document viewer key; defaults to `1`. * @group View */ export function setPageFocusEnabled(enabled: boolean, key?: number): void /** * Removes the highlight from the focused page. * @param key The document viewer key; defaults to `1`. * @group View */ export function clearPageFocus(key?: number): void /** * Types of the built-in redaction search patterns, as used by `replaceRedactionSearchPattern` and `removeRedactionSearchPattern`. * @group Constants */ export const RedactionSearchPatterns: { /** Email addresses. */ readonly EMAILS: 'emails' /** Credit card numbers (13 to 16 digits, optionally separated by spaces or dashes). */ readonly CREDIT_CARDS: 'creditCards' /** Phone numbers. */ readonly PHONE_NUMBERS: 'phoneNumbers' } /** * Names of the built-in sort strategies of the notes panel, as used by `setNotesPanelSortStrategy`. * @example * ```js * instance.UI.setNotesPanelSortStrategy(instance.UI.NotesPanelSortStrategy.AUTHOR); * ``` * @group Constants */ export const NotesPanelSortStrategy: { /** Groups notes by page, in document order (the default). */ readonly POSITION: 'position' /** Sorts by creation date, oldest first, with a separator per date. */ readonly CREATED_DATE: 'createdDate' /** Sorts by the latest change of the note or its replies, newest first, with a separator per date. */ readonly MODIFIED_DATE: 'modifiedDate' /** Sorts by review status, with a separator per status. */ readonly STATUS: 'status' /** Sorts by author name, with a separator per author. */ readonly AUTHOR: 'author' /** Sorts by annotation type, with a separator per type. */ readonly TYPE: 'type' /** Sorts by annotation color, with a separator per color. */ readonly COLOR: 'color' } /** * Names of the shortcuts the viewer implements (`UI.Shortcuts`); use them with `UI.hotkeys` and the keyboardShortcut user setting. * The standard keys listed for each are the keys `UI.hotkeys.on(key)` maps to the shortcut. By default only copy, paste, undo, redo and Escape (select) are bound. * @group Constants */ export const Shortcuts: { /** Rotates the view clockwise. Standard keys: ctrl+shift+=, command+shift+=. */ readonly ROTATE_CLOCKWISE: 'rotateClockwise' /** Rotates the view counterclockwise. Standard keys: ctrl+shift+-, command+shift+-. */ readonly ROTATE_COUNTER_CLOCKWISE: 'rotateCounterClockwise' /** Rotates the view clockwise (numeric keypad keys). Standard keys: ctrl+shift+num_add, command+shift+num_add. */ readonly NUMPAD_ROTATE_CLOCKWISE: 'numpadRotateClockwise' /** Rotates the view counterclockwise (numeric keypad keys). Standard keys: ctrl+shift+num_subtract, command+shift+num_subtract. */ readonly NUMPAD_ROTATE_COUNTER_CLOCKWISE: 'numpadRotateCounterClockwise' /** Copies the selected annotations, text or content boxes. Standard keys: ctrl+c, command+c. */ readonly COPY: 'copy' /** Pastes copied annotations or content boxes. Standard keys: ctrl+v, command+v. */ readonly PASTE: 'paste' /** Undoes the last change. Standard keys: ctrl+z, command+z. */ readonly UNDO: 'undo' /** Redoes the last undone change. Standard keys: ctrl+y, command+shift+z. */ readonly REDO: 'redo' /** Opens or closes the search panel. Standard keys: ctrl+f, command+f. */ readonly SEARCH: 'search' /** Zooms in. Standard keys: ctrl+=, command+=. */ readonly ZOOM_IN: 'zoomIn' /** Zooms out. Standard keys: ctrl+-, command+-. */ readonly ZOOM_OUT: 'zoomOut' /** Zooms in (numeric keypad keys). Standard keys: ctrl+num_add, command+num_add. */ readonly NUMPAD_ZOOM_IN: 'numpadZoomIn' /** Zooms out (numeric keypad keys). Standard keys: ctrl+num_subtract, command+num_subtract. */ readonly NUMPAD_ZOOM_OUT: 'numpadZoomOut' /** Fits the whole page in the viewer (fits the width on mobile devices). Standard keys: ctrl+0, command+0. */ readonly FIT_SCREEN_WIDTH: 'fitScreenWidth' /** Opens the print dialog. Standard keys: ctrl+p, command+p. */ readonly PRINT: 'print' /** Goes to the previous page. Standard keys: pageup. */ readonly PREVIOUS_PAGE: 'previousPage' /** Goes to the next page. Standard keys: pagedown. */ readonly NEXT_PAGE: 'nextPage' /** Switches to the pan tool while the key is held. Standard keys: space. */ readonly SWITCH_PAN: 'switchPan' /** Switches to the selection tool. Standard keys: escape. */ readonly SELECT: 'select' /** Switches to the pan tool. Standard keys: p. */ readonly PAN: 'pan' /** Selects the arrow tool. Standard keys: a. */ readonly ARROW: 'arrow' /** Selects the callout tool. Standard keys: c. */ readonly CALLOUT: 'callout' /** Selects the eraser tool. Standard keys: e. */ readonly ERASER: 'eraser' /** Selects the freehand tool. Standard keys: f. */ readonly FREEHAND: 'freehand' /** Selects the image stamp tool. Standard keys: i. */ readonly IMAGE: 'image' /** Selects the line tool. Standard keys: l. */ readonly LINE: 'line' /** Selects the sticky note tool. Standard keys: n. */ readonly STICKY_NOTE: 'stickyNote' /** Selects the ellipse tool. Standard keys: o. */ readonly ELLIPSE: 'ellipse' /** Selects the rectangle tool. Standard keys: r. */ readonly RECTANGLE: 'rectangle' /** Selects the rubber stamp tool. Standard keys: q. */ readonly RUBBER_STAMP: 'rubberStamp' /** Selects the free text tool. Standard keys: t. */ readonly FREETEXT: 'freetext' /** Selects the signature tool. Standard keys: s. */ readonly SIGNATURE: 'signature' /** Selects the squiggly underline tool. Standard keys: g. */ readonly SQUIGGLY: 'squiggly' /** Selects the highlight tool. Standard keys: h. */ readonly HIGHLIGHT: 'highlight' /** Selects the strikeout tool. Standard keys: k. */ readonly STRIKEOUT: 'strikeout' /** Selects the underline tool. Standard keys: u. */ readonly UNDERLINE: 'underline' /** Closes the open tooltip. Standard keys: x. */ readonly CLOSE: 'close' } /** * Loads a document into the active viewer, or into the viewer with the given key. * Resets the UI, asks for a password when needed, shows the loading overlay and recovers from errors. Rejects on an invalid key or arguments. * @param src The document source (URL, File, Blob, ArrayBuffer...) or a loaded Document. * @param options Load options. * @param documentViewerKey The viewer key; the active viewer by default. * @returns A Promise that resolves when the document is loaded. * @example * ```js * await instance.UI.loadDocument('https://example.com/sample.pdf', { filename: 'sample.pdf' }); * ``` * @group Document */ export function loadDocument(src: DocumentSource | Document, options?: UILoadDocumentOptions, documentViewerKey?: number): Promise /** * Closes the document of the active viewer. * @returns A Promise that resolves when the document is closed. * @example * ```js * await instance.UI.closeDocument(); * ``` * @group Document */ export function closeDocument(): Promise /** * Verifies an owner password and refreshes the UI permission state for this viewer. * @param password The owner (permission) password. * @param documentViewerKey The viewer key; the active viewer by default. * @returns `true` when the password is correct. * @example * ```js * const ok = await instance.UI.checkPermissionPassword('owner-password'); * ``` * @group Document */ export function checkPermissionPassword(password: string, documentViewerKey?: number | undefined): Promise /** * Gets the password the user entered when opening the document. * @returns The password, or an empty string. * @group Document */ export function getPassword(): string /** * Downloads the document of the active viewer. Rejects with NOT_INITIALIZED when no document is open. * @param options Download options. * @returns A Promise that resolves when the download starts. * @example * ```js * // Download a copy without annotations * await instance.UI.downloadPdf({ filename: 'contract.pdf', includeAnnotations: false }); * ``` * @group Document */ export function downloadPdf(options?: DownloadPdfOptions): Promise /** * Exports XFDF and POSTs it to the `serverUrl` constructor option (see helpers/flows/saveAnnotations). * @returns A Promise that resolves once the request completes. * @group Document */ export function saveAnnotations(): Promise /** * Gets the `custom` string passed to the constructor options. * @returns The original string, or `null` when none was given. * @group Document */ export function getCustomData(): string | null /** * Subscribes to this instance's UI event bus. * `options.once` removes the listener after the first call. VIEWER_LOADED is sticky: registering after it happened still calls back once in a microtask. * @param eventName The event name, from `UI.Events`. * @param listener The listener. * @param options Listener options. * @param options.once When true, the listener is removed after its first call. * @example * ```js * instance.UI.addEventListener(instance.UI.Events.VIEWER_LOADED, () => console.log('ready')); * ``` * @group Events */ export function addEventListener(eventName: string, listener: (...args: any[]) => void, options?: { once?: boolean }): void /** * Removes a listener. The listener is required: without it, the core would remove every listener of the event, * so a missing listener is ignored with a warning. * @param eventName The event name. * @param listener The listener to remove. * @example * ```js * const onThemeChanged = (theme) => console.log('theme:', theme); * instance.UI.addEventListener(instance.UI.Events.THEME_CHANGED, onThemeChanged); * // later * instance.UI.removeEventListener(instance.UI.Events.THEME_CHANGED, onThemeChanged); * ``` * @group Events */ export function removeEventListener(eventName: string, listener: (...args: any[]) => void): void /** * Opens several elements (not mutually exclusive). A single string is accepted too. * @param dataElements A dataElement or an array of them. * @example * ```js * instance.UI.openElements([instance.UI.Panels.NOTES]); * ``` * @group Elements */ export function openElements(dataElements: string | string[]): void /** * Opens an element and closes the other panels on the same side. * @param dataElement The dataElement of the element. * @example * ```js * instance.UI.openElement(instance.UI.Panels.THUMBNAIL); * ``` * @group Elements */ export function openElement(dataElement: string): void /** * Closes elements. A single string is accepted too (replaces the 2.x closeElement). * @param dataElements A dataElement or an array of them. * @example * ```js * instance.UI.closeElements([instance.UI.Panels.NOTES, instance.UI.Panels.SEARCH]); * ``` * @group Elements */ export function closeElements(dataElements: string | string[]): void /** * Opens the element when it is closed, closes it when it is open. * @param dataElement The dataElement of the element. * @example * ```js * instance.UI.toggleElementVisibility(instance.UI.Panels.SEARCH); * ``` * @group Elements */ export function toggleElementVisibility(dataElement: string): void /** * Tells whether an element is open. The state is read synchronously, so it reflects `openElements` / `closeElements` calls made just before. * @param dataElement The dataElement of the element. * @returns `true` when the element is open. * @example * ```js * if (!instance.UI.isElementOpen(instance.UI.Panels.NOTES)) { * instance.UI.openElements([instance.UI.Panels.NOTES]); * } * ``` * @group Elements */ export function isElementOpen(dataElement: string): boolean /** * Disables elements, hiding them from the UI. Elements disabled through this API cannot be re-enabled by the viewer itself, only by `enableElements`. * A single string is accepted too. * @param dataElements A dataElement or an array of them. * @example * ```js * instance.UI.disableElements(['printButton', 'downloadButton']); * ``` * @group Elements */ export function disableElements(dataElements: string | string[]): void /** * Enables elements disabled by `disableElements`. A single string is accepted too. * @param dataElements A dataElement or an array of them. * @example * ```js * instance.UI.enableElements(['printButton', 'downloadButton']); * ``` * @group Elements */ export function enableElements(dataElements: string | string[]): void /** * Disables a single element with PRIORITY_THREE (same path as `disableElements`). * @param dataElement The dataElement of the element. * @group Elements */ export function disableElement(dataElement: string): void /** * Enables a single element with PRIORITY_THREE. * @param dataElement The dataElement of the element. * @group Elements */ export function enableElement(dataElement: string): void /** * Resets the disabled-elements table to its initial state (elements disabled internally from the start stay disabled); open states are not touched. * @group Elements */ export function enableAllElements(): void /** * Tells whether an element is disabled. * @param dataElement The dataElement of the element. * @returns `true` when the element is disabled. * @example * ```js * const printDisabled = instance.UI.isElementDisabled('printButton'); * ``` * @group Elements */ export function isElementDisabled(dataElement: string): boolean /** * Overrides properties of a button or another element with `overrides` * (img / icon / label / title / disabled / hidden / className / style / onClick …, any field a component reads from its item; the overrides replace the element's previous overrides as a whole, `{}` clears them). * Matching items in headers, dropdowns and popups all change; the overrides go into the store's customElementOverrides and components merge them into their properties. * Non-object overrides are ignored with a warning; null / undefined are ignored silently. * `colorPalette` is a backward-compatible branch forwarded to setColorPalette (apis/palette). * @param dataElement The dataElement of the element. * @param overrides The properties to override. * @example * ```js * instance.UI.updateElement('downloadButton', { title: 'Save a copy' }); * ``` * @group Elements */ export function updateElement(dataElement: string, overrides: Record): void /** * Changes the HTML tag of an element. `dataElement` must be a value of UI.ElementTagTarget (currently only the document area); * `tag` must be a non-empty string (the caller makes sure the tag is valid and semantically suitable). The default document area is a div. * @param dataElement A value of `UI.ElementTagTarget`. * @param tag The HTML tag name. * @group Elements */ export function setElementTag(dataElement: string, tag: string): void /** * Sets a function called with `(dataElement, { type })` when a button is clicked, before the default handling; `type` is one of UI.ClickedItemTypes. * Stored per instance; buttons without a dataElement do not trigger it. * @param middleware The click middleware. * @example * ```js * instance.UI.setClickMiddleware((dataElement, { type }) => { * if (type === instance.UI.ClickedItemTypes.BUTTON) * console.log('clicked', dataElement); * }); * ``` * @group Elements */ export function setClickMiddleware(middleware: ClickMiddleware): void /** * Closes the tooltip currently shown on hover; does nothing when there is none. * @group Elements */ export function closeTooltip(): void /** * Sets the selected tab of a tab container. * Only the signature dialog `signatureModal` (text / ink / image buttons) and the rubber stamp panel `rubberStampTab` * (standard / dynamic / custom buttons, the tabs' own dataElements STANDARD / DYNAMIC / CUSTOM, and custom tabs added by setStampPanelTabs such as IMPORT) are supported; * other containers (such as `linkModal`) and unknown tabs are ignored with a warning. * @param id The tab container id. * @param dataElement The dataElement of the tab to select. * @group Elements */ export function setSelectedTab(id: string, dataElement: string): void /** * Enables UI features. * @param features A feature name or an array of them, from `UI.Feature`. * @param priority The priority (`2` by default). * @example * ```js * instance.UI.enableFeatures([instance.UI.Feature.Measurement, instance.UI.Feature.Redaction]); * ``` * @group Features */ export function enableFeatures(features: string | string[], priority?: 1 | 2 | 3): void /** * Disables UI features. * @param features A feature name or an array of them, from `UI.Feature`. * @param priority The priority (`2` by default). * @example * ```js * instance.UI.disableFeatures([instance.UI.Feature.Print, instance.UI.Feature.Download]); * ``` * @group Features */ export function disableFeatures(features: string | string[], priority?: 1 | 2 | 3): void /** * Enables a feature flag. Unknown names are ignored with a warning. * @param featureFlag One of `UI.FeatureFlags`. * @group Features */ export function enableFeatureFlag(featureFlag: string): void /** * Disables a feature flag. Unknown names are ignored with a warning; `customizableUI` cannot be disabled. * @param featureFlag One of `UI.FeatureFlags`. * @group Features */ export function disableFeatureFlag(featureFlag: string): void /** * Sets the zoom level of the active document viewer. * The value is kept between the minimum and maximum zoom levels (5% and 1000% by default, see `setMinZoomLevel` and `setMaxZoomLevel`). * Invalid values are ignored with a warning. * @param zoomLevel A number where `1` is 100%, or a percentage string such as `'125%'`. * @example * ```js * instance.UI.setZoomLevel(1.5); // 150% * instance.UI.setZoomLevel('75%'); // 75% * ``` * @group View */ export function setZoomLevel(zoomLevel: string | number): void /** * Gets the zoom level of the active document viewer. * @returns The zoom level, where `1` is 100%. * @example * ```js * const percent = Math.round(instance.UI.getZoomLevel() * 100); * ``` * @group View */ export function getZoomLevel(): number /** * Sets the zoom presets offered in the zoom dropdown (`1` is 100%). Ignored with a warning unless every item is a positive number. * @param zoomList The zoom levels. * @example * ```js * instance.UI.setZoomList([0.5, 1, 2, 4]); * ``` * @group View */ export function setZoomList(zoomList: number[]): void /** * Sets the maximum zoom level. Ignored with a warning when invalid or below the current minimum. * Applies to the zoom buttons, the zoom input, wheel / pinch zoom and `setZoomLevel`. * @param zoomLevel A number where `1` is 100%, or a percentage string such as `'150%'`. * @group View */ export function setMaxZoomLevel(zoomLevel: string | number): void /** * Gets the maximum zoom level. * @returns The maximum zoom level, where `1` is 100% (`10` by default). * @group View */ export function getMaxZoomLevel(): number /** * Sets the minimum zoom level. Ignored with a warning when invalid or above the current maximum. * @param zoomLevel A number where `1` is 100%, or a percentage string such as `'10%'`. * @group View */ export function setMinZoomLevel(zoomLevel: string | number): void /** * Gets the minimum zoom level. * @returns The minimum zoom level, where `1` is 100% (`0.05` by default). * @group View */ export function getMinZoomLevel(): number /** * Sets the step table used by the zoom in / zoom out buttons. `step` and `startZoom` are percentages (a number, or a string such as `'25'` / `'25%'`). * At least one item must have `startZoom` 0 and every `step` must be positive; otherwise the call is ignored with a warning. * Once set, the buttons add or subtract the step of the range the current zoom falls in, instead of multiplying / dividing by 1.1. * @param zoomStepFactors The step table. * @example * ```js * instance.UI.setZoomStepFactors([ * { step: 10, startZoom: 0 }, * { step: 50, startZoom: 200 }, * ]); * ``` * @group View */ export function setZoomStepFactors(zoomStepFactors: ZoomStepFactorInput[]): void /** * Gets the zoom step table set by `setZoomStepFactors`. * @returns The step table in percentages; an empty array when it was never set (the built-in steps apply). * @group View */ export function getZoomStepFactors(): ZoomStepFactor[] /** * Sets how pages fit in the active document viewer. Unknown values are ignored with a warning. * @param fitMode One of `UI.FitMode`: `'FitPage'` shows the whole page, `'FitWidth'` fills the width of the viewer, * `'Zoom'` keeps the current zoom level. * @example * ```js * instance.UI.setFitMode(instance.UI.FitMode.FitWidth); * ``` * @group View */ export function setFitMode(fitMode: string): void /** * Gets how pages fit in the active document viewer. * @returns One of `UI.FitMode`: `'FitPage'`, `'FitWidth'` or `'Zoom'`. * @example * ```js * if (instance.UI.getFitMode() !== instance.UI.FitMode.FitPage) { * instance.UI.setFitMode(instance.UI.FitMode.FitPage); * } * ``` * @group View */ export function getFitMode(): string /** * Sets the page layout of the active document viewer. Unknown values are ignored with a warning. * @param layoutMode One of `UI.LayoutMode` except `'Custom'`: * - `'Single'`: one page at a time. * - `'Continuous'`: all pages in one scrolling column. * - `'Facing'`: two pages side by side, one pair at a time. * - `'FacingContinuous'`: two pages side by side, all pairs in one scrolling column. * - `'CoverFacing'`: like `'Facing'`, with the first page on its own as a cover. * - `'Cover'`: like `'FacingContinuous'`, with the first page on its own as a cover. * @example * ```js * instance.UI.setLayoutMode(instance.UI.LayoutMode.FacingContinuous); * ``` * @group View */ export function setLayoutMode(layoutMode: string): void /** * Gets the page layout of the active document viewer. * @returns One of `UI.LayoutMode`. It is `'Custom'` while the pages are laid out in one row (see {@link setScrollMode}). * @group View */ export function getLayoutMode(): string /** * Sets the scroll direction of the pages in the active document viewer. * `'Horizontal'` lays all pages out in one row and scrolls sideways (a two-page layout switches to single pages first); * `'Vertical'` returns to the continuous single-page layout. Unknown values are ignored with a warning. * @param scrollMode `'Vertical'` or `'Horizontal'`. * @example * ```js * instance.UI.setScrollMode('Horizontal'); * instance.UI.getScrollMode(); // 'Horizontal' * ``` * @group View */ export function setScrollMode(scrollMode: ScrollMode): void /** * Gets the scroll direction of the pages in the active document viewer. * @returns `'Horizontal'` when all pages are laid out in one row, otherwise `'Vertical'` * @group View */ export function getScrollMode(): ScrollMode /** * Enters or leaves full screen mode for the viewer. * The `fullscreenModeToggled` event is triggered once the browser has switched. If the browser refuses * (for example, when the call does not come from a user gesture), nothing changes. * @example * ```js * button.addEventListener('click', () => instance.UI.toggleFullScreen()); * ``` * @group View */ export function toggleFullScreen(): void /** * Tells whether the viewer is in full screen mode. * @returns `true` while an element of the viewer's page is shown full screen. * @example * ```js * instance.UI.addEventListener(instance.UI.Events.FULLSCREEN_MODE_TOGGLED, () => { * console.log('full screen:', instance.UI.isFullscreen()); * }); * ``` * @group View */ export function isFullscreen(): boolean /** * Gets a document viewer by key. A missing key (or 0) returns viewer 1, not the active viewer. * An unknown key returns an inert viewer whose calls do nothing. * @param documentViewerKey The viewer key, `1` by default. * @returns The document viewer. * @example * ```js * const documentViewer = instance.UI.getDocumentViewer(instance.UI.getActiveDocumentViewerKey()); * ``` * @group View */ export function getDocumentViewer(documentViewerKey?: number): DocumentViewer /** * Gets the key of the active document viewer. * @returns The key of the active viewer (`1` unless multi-viewer mode switched it). * @group View */ export function getActiveDocumentViewerKey(): number /** * Switches the active document viewer (the left / right pane in side-by-side or compare mode). * Only registered keys are accepted; others are ignored with a warning. Triggers activeDocumentViewerChanged ([new, old]) when the key changes. * @param documentViewerKey The viewer key. * @group View */ export function setActiveDocumentViewerKey(documentViewerKey: number): void /** * The bundled languages: `ZH_CN` → `'zh-CN'`, the codes `setLanguage` takes. * @group Constants */ export const Languages: Readonly> /** * Alignment values of modular components. * @group Constants */ export const JustifyContent: { /** Items are packed at the start. */ readonly START: 'start' /** Items are centered. */ readonly CENTER: 'center' /** Items are packed at the end. */ readonly END: 'end' /** Equal space between items, none at the ends. */ readonly SPACE_BETWEEN: 'space-between' /** Equal space around each item. */ readonly SPACE_AROUND: 'space-around' /** Equal space between items and at the ends. */ readonly SPACE_EVENLY: 'space-evenly' } /** * Values of the `buttonType` of a PresetButton. * @group Constants */ export const PRESET_BUTTON_TYPES: { /** Undoes the last annotation change. */ readonly UNDO: 'undoButton' /** Redoes the last undone annotation change. */ readonly REDO: 'redoButton' /** Opens a file from the user's computer. */ readonly FILE_PICKER: 'filePickerButton' /** Downloads the document. */ readonly DOWNLOAD: 'downloadButton' /** Turns full screen mode on or off. */ readonly FULLSCREEN: 'fullscreenButton' /** Prints the document. */ readonly PRINT: 'printButton' /** Opens the settings dialog. */ readonly SETTINGS: 'settingsButton' /** Downloads the document with its annotations flattened. */ readonly FLATTEN_DOWNLOAD: 'flattenDownloadButton' /** Switches to the light theme. */ readonly LIGHT_THEME: 'lightThemeButton' /** Switches to the dark theme. */ readonly DARK_THEME: 'darkThemeButton' /** Opens or closes the view settings panel. */ readonly VIEW_SETTINGS: 'viewSettingsButton' /** Opens the left panel, with a menu of its tabs. */ readonly LEFT_PANEL: 'leftPanelButton' /** Selection tools menu (annotation and text selection). */ readonly SELECT_TOOLS: 'selectToolsButton' /** Switches between form design mode and form filling mode. */ readonly FILL_FORM: 'fillFormButton' /** Adds a digital signature. */ readonly DIGITAL_SIGNATURE: 'digitalSignatureButton' /** Adds an electronic signature. */ readonly ELECTRONIC_SIGNATURE: 'electronicSignatureButton' /** Verifies the digital signatures of the document. */ readonly VERIFY_SIGNATURE: 'verifySignatureButton' /** Opens the dialog that sets a document password. */ readonly SET_PASSWORD: 'setPasswordButton' /** Removes the document password. */ readonly REMOVE_PASSWORD: 'removePasswordButton' /** Undoes the last text or image edit. */ readonly CONTENT_EDIT_UNDO: 'contentEditUndoButton' /** Redoes the last undone text or image edit. */ readonly CONTENT_EDIT_REDO: 'contentEditRedoButton' /** Leaves the page editor without saving. */ readonly PAGE_EDITOR_CANCEL: 'pageEditorCancelButton' /** Saves the page editor changes. */ readonly PAGE_EDITOR_SAVE: 'pageEditorSaveButton' /** Downloads the edited document and stays in the page editor. */ readonly PAGE_EDITOR_SAVE_AS: 'pageEditorSaveAsButton' /** Shows the comparison result in full screen. */ readonly COMPARE_FULLSCREEN: 'compareFullscreenButton' /** Starts comparing the two documents. */ readonly START_COMPARE: 'startCompareButton' /** Leaves document comparison. */ readonly EXIT_COMPARE: 'exitCompareButton' /** Downloads the comparison result. */ readonly COMPARE_DOWNLOAD: 'compareDownloadButton' /** Prints the comparison result. */ readonly COMPARE_PRINT: 'comparePrintButton' } /** * Names of experimental feature flags. * @group Constants */ export const FeatureFlags: { /** The customizable (modular) UI; always enabled. */ readonly CUSTOMIZABLE_UI: 'customizableUI' } /** * Targets of setElementTag. * @group Constants */ export const ElementTagTarget: { /** The element that contains the document pages. */ readonly DOCUMENT_CONTAINER: 'documentContainer' } /** * The `type` passed to the setClickMiddleware callback. * @group Constants */ export const ClickedItemTypes: { /** A button was clicked. */ readonly BUTTON: 'button' } /** * How the zoom level is chosen. * @group Constants */ export const FitMode: typeof Core.FitMode /** * Page layout modes of `setLayoutMode`, the same values as `Core.DisplayModes`. Available as `UI.LayoutMode`. * @group Constants */ export const LayoutMode: typeof DisplayModes /** * `UI.Feature`: the features `enableFeatures` / `disableFeatures` can switch; other values warn and are ignored. * @group Constants */ export const Feature: { /** The measurement toolbar. */ readonly Measurement: 'Measurement' /** The ribbon tabs of the default header. */ readonly Ribbons: 'Ribbons' /** Annotation creation: the annotation toolbar and ribbons, the notes, stamp and style panels. */ readonly Annotations: 'Annotations' /** The download button. */ readonly Download: 'Download' /** The open file button. */ readonly FilePicker: 'FilePicker' /** Saving UI settings in the browser's local storage for this viewer. */ readonly LocalStorage: 'LocalStorage' /** The notes panel. */ readonly NotesPanel: 'NotesPanel' /** The print button. */ readonly Print: 'Print' /** The redaction toolbar. */ readonly Redaction: 'Redaction' /** Text selection: the text selection tool and the text popup. */ readonly TextSelection: 'TextSelection' /** The copy text button. */ readonly Copy: 'Copy' /** Selecting several pages through the thumbnails panel API (on by default). */ readonly ThumbnailMultiselect: 'ThumbnailMultiselect' /** The search button. */ readonly Search: 'Search' /** Text and image editing: the edit toolbar and its button. */ readonly ContentEdit: 'ContentEdit' /** The left panel and its toggle button. */ readonly Panel: 'Panel' /** Signature templates: the template tab and "Save as template" in the signature dialog. */ readonly SignatureTemplates: 'SignatureTemplates' /** Jumping to the next empty signature field after a field is signed. */ readonly AutoJumpNextSignature: 'AutoJumpNextSignature' /** Highlighting of link areas on the page. */ readonly LinkHighlighting: 'LinkHighlighting' } /** * Names of the events of `addEventListener`. Available as `UI.Events`. * @group Constants */ export const Events: { /** The viewer finished loading. Listeners added afterwards are still called once. */ readonly VIEWER_LOADED: 'viewerLoaded' /** An action was refused because the document does not allow it; the listener receives the permission, the action and the viewer key. */ readonly PERMISSION_DENIED: 'permissionDenied' /** The owner password was verified; the listener receives the viewer key. */ readonly PERMISSION_VERIFIED: 'permissionVerified' /** Loading a document failed; the listener receives the error. */ readonly LOAD_ERROR: 'loaderror' /** An element was opened or closed; the listener receives `(dataElement, isVisible)`. */ readonly VISIBILITY_CHANGED: 'visibilityChanged' /** The active toolbar group changed; the listener receives the new group, one of {@link UI.ToolbarGroup}. */ readonly TOOLBAR_GROUP_CHANGED: 'toolbarGroupChanged' /** The theme changed; the listener receives the new theme, one of {@link UI.Theme}. */ readonly THEME_CHANGED: 'themeChanged' /** The language changed; the listener receives `(previousLanguage, newLanguage)` as language codes. */ readonly LANGUAGE_CHANGED: 'languageChanged' /** A panel width changed; the listener receives `(dataElement, width)` with the width in pixels. */ readonly PANEL_RESIZED: 'panelResized' /** `importModularComponents` finished applying the imported layout. */ readonly MODULAR_UI_IMPORTED: 'modularUIImported' /** The active document viewer changed; the listener receives `(newKey, previousKey)`. */ readonly ACTIVE_DOCUMENT_VIEWER_CHANGED: 'activeDocumentViewerChanged' /** Full-screen mode was entered or left; the listener receives `true` when entering. */ readonly FULLSCREEN_MODE_TOGGLED: 'fullscreenModeToggled' /** A tooltip was shown. */ readonly TOOLTIP_OPENED: 'tooltipOpened' /** `downloadPdf` finished saving the file. */ readonly FILE_DOWNLOADED: 'fileDownloaded' /** A custom text note panel should open; the listener receives the note annotation. */ readonly OPEN_CUSTOM_TEXT_NOTE_PANEL: 'openCustomTextNotePanel' /** A custom text note panel should close; the listener receives the note annotation. */ readonly CLOSE_CUSTOM_TEXT_NOTE_PANEL: 'closeCustomTextNotePanel' /** The selected thumbnails changed; the listener receives the array of selected 0-based page indexes. */ readonly SELECTED_THUMBNAIL_CHANGED: 'selectedThumbnailChanged' /** The second viewer of the side-by-side view is ready, after `enterMultiViewerMode`. */ readonly MULTI_VIEWER_READY: 'multiViewerReady' /** Note text was saved automatically after typing stopped (only with `enableAutosave`); the listener receives `{ annotationId }`. */ readonly NOTE_AUTOSAVED: 'wv-note-autosaved' /** * The user added a signer certificate to the trust list from the certificate viewer; the listener receives `{ fieldName, certificate }`, * with `certificate` a copy of the DER bytes. Not fired by `UI.VerificationOptions.addTrustedCertificates`. The trust list is kept in memory only: * store the certificate yourself and pass it to `addTrustedCertificates` after the viewer loads to trust it again. */ readonly TRUSTED_CERTIFICATE_ADDED: 'trustedCertificateAdded' } /** * Names of the toolbar groups of the default ribbon, as used by `setToolbarGroup`. Available as `UI.ToolbarGroup`. * @group Constants */ export const ToolbarGroup: { /** The View group. */ readonly VIEW: 'toolbarGroup-View' /** The Annotate group. */ readonly ANNOTATE: 'toolbarGroup-Annotate' /** The Measure group. */ readonly MEASURE: 'toolbarGroup-Measure' /** The Edit group for editing page text and images. */ readonly EDIT_TEXT: 'toolbarGroup-EditText' /** The Fill and Sign group. */ readonly FILL_AND_SIGN: 'toolbarGroup-FillAndSign' /** The Forms group for creating form fields. */ readonly FORMS: 'toolbarGroup-Forms' /** The Redact group. */ readonly REDACT: 'toolbarGroup-Redact' /** The Security group (passwords and permissions). */ readonly SECURITY: 'toolbarGroup-Security' /** The Compare group. */ readonly COMPARE: 'toolbarGroup-Compare' /** The Document group; selecting it opens the page editor. */ readonly DOCUMENT: 'toolbarGroup-Document' /** The Separation group (color separation preview). */ readonly SEPARATION: 'toolbarGroup-Separation' } /** * Themes of `setTheme`. Available as `UI.Theme`. * @group Constants */ export const Theme: { /** The light theme. */ readonly LIGHT: 'light' /** The dark theme. */ readonly DARK: 'dark' } /** * Names of the built-in panels, as used by `openElements`, `setActiveLeftPanel` and `setPanelWidth`. Available as `UI.Panels`. * @group Constants */ export const Panels: { /** The outline panel. */ readonly OUTLINE: 'outlinesPanel' /** The signature panel that lists the signatures of the document. */ readonly SIGNATURE: 'signaturePanel' /** The bookmarks panel. */ readonly BOOKMARKS: 'bookmarksPanel' /** The page thumbnails panel. */ readonly THUMBNAIL: 'thumbnailsPanel' /** The layers panel. */ readonly LAYERS: 'layersPanel' /** The panel with the text and image properties used while editing content. */ readonly TEXT_EDITING: 'textEditingPanel' /** The annotation style panel. */ readonly STYLE: 'stylePanel' /** The search panel. */ readonly SEARCH: 'searchPanel' /** The notes (comments) panel. */ readonly NOTES: 'notesPanel' /** The tab panel that groups other panels. */ readonly TABS: 'tabPanel' /** The stamp panel. */ readonly RUBBER_STAMP: 'rubberStampPanel' /** The form field properties panel. */ readonly FORM_FIELD: 'formFieldPanel' /** The color separation panel. */ readonly COLOR_SEPARATION: 'colorSeparationPanel' /** The view settings panel (page layout, scrolling and theme). */ readonly PAGE_MODE: 'pageModePanel' /** The link properties panel. */ readonly LINK: 'linkPanel' /** The redaction style panel. */ readonly REDACTION_STYLE: 'redactionStylePanel' } /** * Closes this WebViewer instance: closes its documents, removes its iframe and releases its resources. Other members only warn after this. * @returns Resolves when the instance is closed. * @group Document */ export function dispose(): Promise } /** * The type of `instance.UI`. * @hidden */ type UI = typeof UI /** Options of a WebViewer call. */ interface WebViewerOptions { [key: string]: unknown /** Required: URL of the folder that contains the `webviewer/` UI folder (absolute, or relative to the host page). */ path: string /** Defaults to `${path}webviewer/` (the layout of the SDK package). */ uiPath?: string /** How the UI is mounted. Only 'iframe' (the default) is supported in this version; other values are rejected with INVALID_OPTIONS. */ mount?: MountMode /** Prefix of persisted keys; defaults to element.id, then 'default'. */ instanceId?: string /** The license key. Without it the viewer opens but reports a missing license. */ licenseKey?: string /** Core assets directory (PDFWorker.js and so on); defaults to `${uiPath}lib/`. */ workerPath?: string /** Defaults to true; 'pdf' / 'all' are treated as true. */ preloadWorker?: boolean | 'pdf' | 'all' /** Turns off the SDK's console logs. */ disableLogs?: boolean /** Creates workers from the worker script URL instead of a blob: URL, for pages whose Content Security Policy forbids blob: workers. */ disableObjectURLBlobs?: boolean /** Number of render workers. */ renderWorkerCount?: number /** Fallback font; defaults to `${workerPath}DroidSansFallbackFull.ttf`; null turns it off. */ customFontURL?: string | null /** Font group directory (its fonts.json lists the fonts). The core loads the whole group and the font dropdown reads the same list. */ webFontURL?: string /** Defaults to false: Core.resetWorker() is called when the last instance of this realm is destroyed; true keeps the worker. */ keepWorkerOnDispose?: boolean /** The document opened after the viewer loads: a URL, File, Blob, ArrayBuffer, Uint8Array or base64 data. With an array, only the first item is opened. */ initialDoc?: DocumentSource | DocumentSource[] /** File name of initialDoc; used when it cannot be taken from the source (for example a Blob) and when downloading. */ filename?: string /** File extension of initialDoc, for sources without one (such as a URL without a file name). */ extension?: string /** Identifier of initialDoc, kept with the document. */ documentId?: string /** Author name written on the annotations created by this user. */ annotationUser?: string /** Whether the current user is an admin, who can change the annotations of other users; defaults to true. */ isAdminUser?: boolean /** Opens documents read-only: annotations and form fields cannot be changed. */ isReadOnly?: boolean /** Shows annotations; true by default. With false, annotations are hidden in every viewer of the instance. */ enableAnnotations?: boolean /** dataElement names of UI elements to disable (hide) from the start, as with `UI.disableElements`. */ disabledElements?: string[] /** Reserved; currently has no effect. */ enableFilePicker?: boolean /** Shows the measurement tools; with false they are hidden. */ enableMeasurement?: boolean /** Enables redaction; true by default. With false, redaction is turned off and its UI hidden. */ enableRedaction?: boolean /** Shows the top header; with false it is hidden. */ showToolbarControl?: boolean /** Initial color theme: 'light' or 'dark'. */ theme?: 'light' | 'dark' /** Initial UI language code, for example 'en' or 'zh-CN'; a language the user picked earlier takes precedence. */ defaultLanguage?: string /** URL of a stylesheet added to the viewer, for custom styles. A relative URL is resolved against the UI page (`uiPath`). */ css?: string /** Nonce added to the style elements the viewer creates, for pages with a strict Content Security Policy. */ cspNonce?: string /** URL of a modular UI JSON file applied with UI.importModularComponents when the viewer starts. */ uiConfig?: string /** * URL of a config script run inside the viewer iframe before the UI is mounted; iframe mode only. * A relative URL is resolved against the UI page (`uiPath`). With a cross-origin UI this script is the place for code and callbacks, * since WebViewer() then resolves undefined and function options are not passed into the iframe. */ config?: string /** Custom string passed to the viewer; read it with UI.getCustomData(). */ custom?: string /** URL that UI.saveAnnotations posts the exported XFDF to. */ serverUrl?: string /** HTTP headers sent with the UI.saveAnnotations request. */ serverUrlHeaders?: Record /** Reserved; currently has no effect. */ autoJumpNextSign?: boolean /** Reserved; currently has no effect. */ disableI18n?: boolean /** Hides the document comparison feature of multi-viewer mode. */ disableMultiViewerComparison?: boolean /** Selects each annotation right after it is created. */ selectAnnotationOnCreation?: boolean /** Settings of the 2.x compatibility layer: `silent` turns off console notices, `onDeprecated` hands them to the integrator; by default each call to an old API logs a console notice. */ compat?: CompatOptions /** * Marks a creation that came through the old `ComPDFKitViewer.init` entry. Set internally by that entry only; integrators should not pass it. * @internal */ compatEntry?: 'v2.9.4' } /** Constructor options of a component; the fields each component accepts are described on its class. */ interface ItemOptions { [key: string]: unknown /** Unique name of the component; used to find, show, hide or update it later. */ dataElement: string } /** Layout fields held by a GroupedItems instance itself. */ interface OwnLayout { /** Space between items, in pixels. */ gap: number /** Flex grow factor. */ grow: number /** How items are distributed along the group. */ justifyContent?: string } /** Stored data of a modular header. */ interface ModularHeaderData { [key: string]: unknown /** Unique name of the header. */ dataElement: string /** Always 'modularHeader'. */ type?: 'modularHeader' /** Side of the viewer the header is placed on. */ placement: 'left' | 'right' | 'top' | 'bottom' /** Position of a floating header along its side; 'start' by default. */ position?: 'start' | 'center' | 'end' /** Whether the header floats over the document. */ float?: boolean /** dataElements of the header's items, in display order. */ items: string[] } /** Stored data of a flyout. */ interface FlyoutData { /** Unique name of the flyout. */ dataElement: string /** Those added through UI.Components.Flyout carry 'flyout'; the default configuration ones do not. */ type?: string /** Items of the flyout, in display order. */ items: FlyoutItem[] /** Extra CSS class names added to the flyout. */ className?: string /** dataElement of the element that opens the flyout. */ toggleElement?: string /** May come with imported JSON; turned into disableElements on import and written from the disabled state on export. */ disabled?: boolean } /** An item of a flyout: the dataElement of an existing item, or an object with label, icon, onClick and optional nested children. */ type FlyoutItem = string | { [key: string]: unknown /** Unique name of the item; disabling this name hides the item, and it is passed to the click middleware. */ dataElement?: string /** Items of a submenu opened by clicking this item. */ children?: FlyoutItem[] } /** Constructor options of UI.Components.Flyout. */ interface FlyoutOptions { [key: string]: unknown /** Unique name of the flyout. */ dataElement: string /** Flyout items: objects with label, onClick, icon or children, component instances, 'divider', or dataElements of existing items. */ items: unknown[] /** dataElement of the element that opens the flyout. */ toggleElement?: string } /** Constructor options of UI.Components.MainMenu. */ interface MainMenuOptions { [key: string]: unknown /** Unique name of the menu; defaults to 'MainMenuFlyout', which replaces the default main menu. */ dataElement?: string /** Items added after the default main menu items. */ additionalItems?: unknown[] } /** A tab of a tab panel. */ interface TabPanelItem { /** Built-in panel name, or a function that returns the panel content. */ render: FunctionRef /** Unique name of the tab. */ dataElement?: string /** Label of the tab, or a translation key. */ label?: string /** Icon of the tab. */ icon?: string /** Kept with the tab's data; it does not change how the tab is drawn. */ useIcon?: boolean } /** Constructor options of UI.Components.TabPanel. */ interface TabPanelOptions { /** Unique name of the tab panel. */ dataElement: string /** Panels shown as tabs, in order. */ panelsList: TabPanelItem[] /** Side of the viewer the panel opens on: 'left' (default) or 'right'. */ location?: string } /** Stored data of a panel. */ interface PanelData { [key: string]: unknown /** Unique name of the panel. */ dataElement: string /** Built-in panel name (for example 'outlinePanel', 'thumbnailsPanel', 'tabPanel'), or a function that returns the panel content. */ render: FunctionRef /** Side of the viewer the panel opens on. */ location: PanelLocation /** Icon of the panel. */ icon?: string /** Title of the panel, or a translation key. */ title?: string /** Only for render === 'tabPanel'. */ panelsList?: TabPanelItem[] /** The panel takes the full height of the side area. */ isFullHeight?: boolean } /** An ICC output profile: file data (File, Blob, ArrayBuffer or typed array), a URL to fetch it from, or `null` for the default CoatedFOGRA39 profile. */ type ColorSeparationProfile = string | ArrayBuffer | Blob | File | ArrayBufferView | null /** A language offered in the language menu. */ interface LanguageItem { /** Language code, for example 'en' or 'zh-CN'. */ code: string /** Name shown in the language menu. */ name: string } /** Core tool type (named alias: Tools.Tool cannot be named in inferred declarations, so it is referenced through this alias). */ type CoreTool = Core.Tools.Tool /** Parameters of UI.registerTool. */ interface ToolRegistration { /** Name of the tool; used with setToolMode and as the toolName of tool buttons. */ toolName: string /** The tool instance; its name is set to toolName. */ toolObject: object /** dataElement of the tool's button; disabling the tool disables this element. */ buttonName?: string /** Icon used by tool buttons of this tool that have no icon of their own. */ buttonImage?: string /** Tool group of the button. Stored only; currently has no effect. */ buttonGroup?: string /** Title (or translation key) used by tool buttons of this tool that have no title of their own. */ tooltip?: string /** When the button shows the tool color; 'active' by default. Stored only; currently has no effect. */ showColor?: string /** Whether the tool shows style presets; true by default. Stored only; currently has no effect. */ showPresets?: boolean /** Number of the document viewer to register the tool with; 1 by default or when that viewer does not exist. */ documentViewerNumber?: number } /** Tool button properties UI.updateTool can change. */ type ToolButtonUpdate = { /** dataElement of the tool's button; disabling the tool disables this element. */ buttonName?: string /** Title (or translation key) used by tool buttons of this tool that have no title of their own. */ tooltip?: string /** Tool group of the button. Stored only; currently has no effect. */ buttonGroup?: string /** Icon used by tool buttons of this tool that have no icon of their own. */ buttonImage?: string } /** Colors of the color palette for specific tools, passed to UI.setColorPalette. */ interface PaletteOption { /** Tools that use these colors. */ toolNames: string[] /** Hex colors (#rrggbb); 'transparency' means transparent. */ colors: string[] } /** Options of UI.registerCustomFillStyle. */ interface CustomFillStyleOptions { /** Unique key of the style; an annotation uses the style when its `FillStyle` property is set to this key. 'solid' is reserved. Registering the same key again replaces the style. */ key: string /** Annotation types the style applies to: 'all' (default), 'rectangle', 'ellipse' or 'polygon'. */ appliesTo?: string[] /** Display name of the style; defaults to the key. Kept with the style; it is not shown (there is no fill style dropdown). */ title?: string /** SVG preview of the style. Kept with the style; it is not shown (there is no fill style dropdown). */ svg?: string /** When true, drawing is clipped with clipToShapeFn instead of the built-in clipping to the annotation shape; false by default. */ clipToShape?: boolean /** * Clips the canvas to the annotation shape; required when clipToShape is true. * @param ctx The canvas context being drawn on. * @param annotation The annotation being drawn. */ clipToShapeFn?: (ctx: CanvasRenderingContext2D, annotation: unknown) => void /** * Draws the fill of an annotation; the canvas is already clipped to the annotation shape. * @param ctx The canvas context being drawn on. * @param pageMatrix Transform from page coordinates to canvas coordinates. * @param rotation Rotation of the page. * @param options `{ annotation, originalDraw, originalDrawWithoutFill, clipToShape }`: the annotation, a function drawing its original appearance (once), a function asking for the original appearance to be drawn with no fill after the handler returns (so the border goes over the custom fill), and a function clipping to the shape again. */ drawHandler(ctx: CanvasRenderingContext2D, pageMatrix: unknown, rotation: number | undefined, options: Record): void } /** * A panel returned by `UI.getPanels()`. Changing its `dataElement`, `render` or `location`, or calling `setLocation` / `delete`, * updates the panel in the viewer right away. * @example * ```js * const stylePanel = instance.UI.getPanels().find(panel => panel.dataElement === instance.UI.Panels.STYLE); * stylePanel.setLocation('left'); * ``` */ interface Panel { /** Unique name of the panel; assigning a new name renames the panel. */ dataElement: string /** Built-in panel name, or a function that returns the panel content. */ render: FunctionRef | undefined /** Side of the viewer the panel opens on: 'left' or 'right'. */ location: string | undefined /** * Moves the panel to the other side of the viewer. Values other than 'left' and 'right' are ignored with a warning. * @param location 'left' or 'right'. */ setLocation(location: string): void /** Removes the panel from the UI. */ delete(): void /** * Returns the panel's data. * @returns A copy of the stored panel data, or undefined when the panel no longer exists. */ toObject(): PanelData | undefined } /** A function, or the name of a function in the function map passed to UI.importModularComponents. */ type FunctionRef = string | ((...args: any[]) => unknown) /** Modular UI data used by UI.importModularComponents and UI.exportModularComponents. In each table the key is the dataElement. */ interface ModularComponentsData { /** Components (buttons, groups, dividers and so on) keyed by dataElement. */ modularComponents?: Record> /** Headers keyed by dataElement. */ modularHeaders?: Record> /** Panels keyed by dataElement. */ panels?: Record> /** Flyouts keyed by dataElement. */ flyouts?: Record> /** Items of each popup, keyed by popup dataElement. */ popups?: Record } /** Modular component (union of all kinds; the store only reads type / items / groupedItems / toggleElement / toolName / buttonType). */ interface ModularComponent { [key: string]: unknown /** Unique name of the component. */ dataElement: string /** Component type, for example 'customButton', 'toolButton', 'groupedItems' or 'divider'. */ type: string /** dataElements of the child components (groups only). */ items?: string[] /** dataElements of the grouped items a ribbon item or tool group toggle button shows. */ groupedItems?: string[] /** dataElement of the element a toggle button opens and closes. */ toggleElement?: string /** Tool activated by a tool button. */ toolName?: string /** Built-in button type of a preset button. */ buttonType?: string /** Toolbar group activated by a ribbon item. */ toolbarGroup?: string } /** An item of a popup (annotation, text, context menu and similar popups). */ interface PopupItem { [key: string]: unknown /** Unique name of the item. */ dataElement: string /** Item type of a custom item: 'actionButton', 'statefulButton', 'toggleElementButton', 'toolButton' or 'divider'; omitted for built-in items. */ type?: string } /** Selects which grouped items the UI.setGroupedItems* functions change. */ interface GroupedItemsSelectors { /** dataElement of the grouped items to change; when omitted, every group of the viewer changes. */ groupedItemsDataElement?: string } /** UI.Flyouts: adds, removes, finds and shows flyouts. */ interface FlyoutsAPI { /** * Adds flyouts created with UI.Components.Flyout. Stops with a console error at the first invalid item (flyouts already added are kept); a duplicate name is made unique. * @param flyoutList Flyout instances to add. */ addFlyouts(flyoutList: UI.Components.Flyout[]): void /** * Removes a flyout; if it is shown, it is closed. * @param dataElement Name of the flyout. */ removeFlyout(dataElement: string): void /** * Shows a flyout, closing the one shown before. A flyout with a toggle button opens as that button's dropdown; others are drawn at the position set with setFlyoutPosition. Disabled flyouts do not open. * @param dataElement Name of the flyout; `null` or `undefined` closes the flyout shown. */ setActiveFlyout(dataElement: string | null | undefined): void /** * Sets where a flyout without a toggle button is drawn; the flyout is kept 5 px inside the viewer. * @param position Top left corner in px, relative to the viewer's root element. * @param position.x Distance from the left edge of the viewer's root element, in px. * @param position.y Distance from the top edge of the viewer's root element, in px. */ setFlyoutPosition(position: { x: number y: number }): void /** * Finds a flyout by name. * @param dataElement Name of the flyout. * @returns A Flyout instance holding a copy of the stored data, or `null` when no flyout has this name. */ getFlyout(dataElement: string): null | UI.Components.Flyout /** * Returns every flyout of the viewer, including those of the default UI. * @returns Flyout instances holding copies of the stored data. */ getAllFlyouts(): UI.Components.Flyout[] } /** Reads and writes the items of one popup (UI.annotationPopup, UI.textPopup and the other popup objects). */ interface PopupAPI { /** Inserts after the item whose dataElement is `after` (at the start when omitted or not found). Returns this. */ add(items: PopupItem | PopupItem[], after?: string): PopupAPI /** Replaces all items (no argument clears them; a single item is accepted too). Returns this. */ update(items?: PopupItem | PopupItem[]): PopupAPI /** The current items (shallow copy of the array; the items themselves are not copied). */ getItems(): PopupItem[] } /** UI.settingsMenuOverlay: reads and writes the items of the settings (more) menu, including the built-in ones. */ interface MenuOverlayAPI { /** Inserts after the item with this dataElement (at the start when omitted or not found). Returns this. */ add(buttons: PopupItem | PopupItem[], dataElement?: string): MenuOverlayAPI /** Replaces all items (no argument clears them). Returns this. */ update(items?: PopupItem | PopupItem[]): MenuOverlayAPI /** The current items (shallow copy of the array). */ getItems(): FlyoutItem[] } /** Options of `UI.addCustomModal`. */ interface CustomModalOptions { [key: string]: unknown /** Unique name of the modal; used to open and close it. */ dataElement: string } /** Options of UI.setCustomLoading. */ interface CustomLoadingOptions { /** Content of the loading row: an HTML string, or an element placed as is. */ element?: string | HTMLElement /** Inline styles applied to the loading row, keyed by CSS property. */ styles?: Record } /** Options of UI.showWarningMessage. */ interface WarningMessageOptions { [key: string]: unknown /** Text of the message, or a translation key. */ message?: string /** Title of the dialog, or a translation key. */ title?: string /** Text of the confirm button, or a translation key. */ confirmBtnText?: string /** Called when the confirm button is clicked. */ onConfirm?: () => unknown /** Called when the dialog is cancelled. */ onCancel?: () => unknown } /** Options of a text search. */ interface SearchOptions { /** Matches letter case exactly. */ caseSensitive?: boolean /** Matches whole words only. */ wholeWord?: boolean /** Treats the search term as a wildcard pattern. */ wildcard?: boolean /** Treats the search term as a regular expression. */ regex?: boolean /** Searches backwards from the current position (step-by-step search only). */ searchUp?: boolean /** Includes the text around each hit in the result (step-by-step search only; full searches always include it). */ ambientString?: boolean } /** Options of UI.printInBackground. */ interface PrintInBackgroundOptions { /** Print only these pages (1-based); all pages by default. An empty array warns and prints nothing. */ pagesToPrint?: number[] /** Include annotations and form fields; false by default (print() and the print button include them). */ includeAnnotations?: boolean /** Called once per rendered page; the second argument (the page's HTML element) is not provided. */ onProgress?: (pageNumber: number) => void /** The three options below have no counterpart here (no comments page, no current-view printing, output already follows each page's orientation); they are ignored with a warning. */ includeComments?: boolean /** Not supported; ignored with a warning when true. */ isPrintCurrentView?: boolean /** Not supported; ignored with a warning when true. */ maintainPageOrientation?: boolean } /** Options of UI.setDefaultPrintOptions; merged with the defaults already set. */ interface PrintDefaults { /** Reserved; currently has no effect (there is no printed comments page). Warns when true. */ includeComments?: boolean /** Whether print() and the print button include annotations and form fields; true by default. */ includeAnnotations?: boolean /** Reserved; currently has no effect (each page is already printed in its own orientation). Warns when true. */ maintainPageOrientation?: boolean /** Page margins: one to four lengths in CSS margin shorthand order, for example "0.5in" or "0.5in 0.4in 0.3in 0.2in" (units in, cm, mm, pt, px or pc); 0 by default. */ margins?: string } /** Options of UI.NotesPanel.setCustomHeader. */ interface CustomHeaderOptions { /** When true, the element replaces the panel's title bar; otherwise it is placed before the title bar. */ overwriteDefaultHeader?: boolean /** * Builds the custom header. * @param notes The annotations listed in the panel (after filtering). * @returns The element to show. */ render(notes: unknown[]): HTMLElement } /** Options of UI.NotesPanel.setCustomEmptyPanel: what the notes panel shows when it lists no annotations. */ interface CustomEmptyPanelOptions { /** Text shown instead of the default empty message. */ message?: string /** Text shown instead of `message` when the document is read-only or does not allow changes. */ readOnlyMessage?: string /** Inline SVG markup drawn above the text. */ icon?: string /** When true, the icon is not drawn. */ hideIcon?: boolean /** * Builds the whole empty panel content; when given, the message and icon options are not used. * @returns The element to show. */ render?: () => HTMLElement } /** A sort strategy of the notes panel, registered with UI.addSortStrategy. */ interface SortStrategy { /** Name of the strategy, used by UI.setNotesPanelSortStrategy; a built-in strategy with the same name is replaced. Required by UI.addSortStrategy. */ name?: string /** * Sorts the notes listed in the panel. * @param notes The listed annotations (a copy that may be sorted in place). * @param options Context of the notes panel. * @returns The annotations in display order. */ getSortedNotes(notes: Annotation[], options: SortOptions): Annotation[] /** * Decides whether a separator starts before a note. Separators are only drawn when getSeparatorContent is given too. * @param prevNote The note before it. * @param currNote The note being placed. * @param options Context of the notes panel. * @param documentViewerKey Key of the document viewer whose notes are listed. * @returns Whether a new group starts at currNote. */ shouldRenderSeparator?: (prevNote: Annotation, currNote: Annotation, options: SortOptions, documentViewerKey?: number) => boolean /** * Returns the title of the separator that starts a group; also called for the first note to title the first group. * @param prevNote The note before it; undefined for the first note. * @param currNote The first note of the group. * @param options Context of the notes panel. * @param documentViewerKey Key of the document viewer whose notes are listed. * @returns The title; undefined or null shows an empty title. */ getSeparatorContent?: (prevNote: Annotation | undefined, currNote: Annotation, options: SortOptions, documentViewerKey?: number) => string | number | undefined | null } /** Function of UI.setCustomOutlineJumpHandler: replaces the default jump when an outline item is clicked; defaultJump runs the default jump. */ type OutlineJumpHandler = (outline: Bookmark, defaultJump: () => void) => void /** UI.OutlinesPanel: outline panel settings. */ interface OutlinesPanelAPI { /** * Sets the defaults applied when a document's outline is loaded. Options left out keep their current value. * @param options The defaults to change. * @param options.autoExpandOutlines Whether the outline of a newly opened document is fully expanded; false (collapsed) by default. */ setDefaultOptions(options?: { /** Whether the outline of a newly opened document is fully expanded; false (collapsed) by default. */ autoExpandOutlines?: boolean }): void } /** Thumbnail selection mode: 'checkbox' (default, select pages only by clicking checkboxes) | 'thumbnail' (click the whole thumbnail to select). */ type ThumbnailSelectionMode = 'checkbox' | 'thumbnail' /** UI.pageManipulationOverlay: item list plus the right-click switch. */ interface PageManipulationOverlayAPI { /** Disables opening the page menu by right-clicking a thumbnail (stored only: the default thumbnails have no such menu). */ disableOpeningByRightClick(): void /** Allows opening the page menu by right-clicking a thumbnail (stored only: the default thumbnails have no such menu). */ enableOpeningByRightClick(): void /** Inserts after the item whose dataElement is `after` (at the start when omitted or not found). Returns undefined for an empty argument, otherwise this. */ add(items: PageManipulationItem | PageManipulationItem[], dataElementToInsertAfter?: string): ItemListAPI | undefined /** Replaces all items (no argument clears them). Returns this. */ update(items?: PageManipulationItem[] | undefined): ItemListAPI /** The current items (shallow copy of the array). */ getItems(): PageManipulationItem[] } /** Common shape of the item list objects (the same add / update / getItems). */ interface ItemListAPI { /** Inserts after the item whose dataElement is `after` (at the start when omitted or not found). Returns undefined for an empty argument, otherwise this. */ add(items: T | T[], dataElementToInsertAfter?: string): ItemListAPI | undefined /** Replaces all items (no argument clears them). Returns this. */ update(items?: T[]): ItemListAPI /** The current items (shallow copy of the array). */ getItems(): T[] } /** One entry of the page operation menu / bulk action bar: preset items only have dataElement; custom groups have header and operations; dividers have type = 'divider'. */ interface PageManipulationItem { [key: string]: unknown /** Item kind: 'divider' for a divider, 'customPageOperation' for a custom group; omitted for preset items. */ type?: string /** Heading of a custom group. */ header?: string /** Name of a preset item or of a custom group. */ dataElement?: string /** Buttons of a custom group. */ operations?: PageOperation[] } /** One entry of the thumbnail more menu. */ interface ThumbnailMenuItem { [key: string]: unknown /** Label of a custom item. */ title?: string /** Icon of a custom item. */ img?: string /** Called with the page numbers of the selected thumbnails when a custom item is clicked. */ onClick?: (selectedPageNumbers: number[]) => void /** Name of a preset item (for example 'thumbRotateClockwise', 'thumbDelete') or unique name of a custom item. */ dataElement?: string } /** Crop preset (inches): yOffset / xOffset are distances from the top / left of the page, width / height the crop area size. */ interface PresetCropDimension { /** Distance from the top of the page, in inches. */ yOffset: number /** Height of the crop area, in inches. */ height: number /** Distance from the left of the page, in inches. */ xOffset: number /** Width of the crop area, in inches. */ width: number } /** New page preset (inches). */ interface PresetNewPageDimension { /** Page height, in inches. */ height: number /** Page width, in inches. */ width: number } /** File dropdown item of the replace page dialog: id / filename and onSelect (a function returning a Document). */ interface PageReplacementFile { [key: string]: unknown /** Identifier of the file. */ id?: string /** File name shown in the dropdown. */ filename?: string /** Returns the Document to take the replacement pages from. */ onSelect?: () => unknown } /** * Handler that replaces the default redaction applying after Save is clicked in the redaction confirmation; cleanup waits for the Promise it returns. * @param annotationsToRedact The redaction annotations to apply. * @param originalApplyRedactions Performs the default applying. * @returns Any value; a returned Promise is awaited. */ type CustomApplyRedactionsHandler = (annotationsToRedact: unknown[], originalApplyRedactions: () => Promise) => unknown /** A redaction search pattern. Stored only: the default UI has no redaction search. */ interface RedactionSearchPattern { /** Label of the pattern, or a translation key. */ label: string /** Icon of the pattern. */ icon?: string /** Unique key of the pattern; adding a pattern with an existing type replaces it. */ type: string /** Regular expression the pattern matches. */ regex: RegExp } /** Measurement system of a scale preset list. */ type MeasurementSystem = 'metric' | 'imperial' /** Corner of the viewer for the scale overlay. Stored only: the default UI has no scale overlay. */ type ScaleOverlayPosition = 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right' /** UI.Fonts: the font lists offered by the font dropdowns, the typed signature tab and the content editing font size dropdown. */ interface FontsAPI { /** * Returns the fonts of the font dropdowns (annotation style, form field and content editing panels). * @returns A copy of the font items. */ getAnnotationFonts(): FontItem[] /** * Appends a font to the font dropdowns; warns and does nothing when an equal font is already listed. * @param font A font name, or a font item. * @example * ```js * instance.UI.Fonts.addAnnotationFont('Helvetica'); * ``` */ addAnnotationFont(font: FontInput): void /** * Removes the first matching font from the font dropdowns; warns when none matches. A string matches the family or the name; an item must match both. * @param font A font name, or a font item. */ removeAnnotationFont(font: FontInput): void /** * Replaces all fonts of the font dropdowns. * @param fonts Font names or font items, in display order. * @example * ```js * instance.UI.Fonts.setAnnotationFonts(['Helvetica', 'Times-Roman']); * ``` */ setAnnotationFonts(fonts: FontInput[]): void /** * Returns the fonts offered by the type tab of the signature dialog. * @returns A copy of the font names. */ getSignatureFonts(): string[] /** * Appends a font to the type tab of the signature dialog; warns and does nothing when it is already listed. * @param font Font name. */ addSignatureFont(font: string): void /** * Removes a font from the type tab of the signature dialog; warns when it is not listed. * @param font Font name. */ removeSignatureFont(font: string): void /** * Replaces all fonts of the type tab of the signature dialog. * @param fonts Font names, in display order. * @example * ```js * instance.UI.Fonts.setSignatureFonts(['Arial', 'Times New Roman']); * ``` */ setSignatureFonts(fonts: string[]): void /** * Returns the font size options of the content editing panel. * @returns A copy of the sizes. */ getFontSizes(): number[] /** * Replaces the font size options of the content editing panel. * @param fontSizes Font sizes, in display order. * @example * ```js * instance.UI.Fonts.setFontSizes([8, 10, 12, 14, 18, 24, 36]); * ``` */ setFontSizes(fontSizes: number[]): void } /** * Stamp panel tabs: `type: 'tab'` are built-in pages (dataElement STANDARD / DYNAMIC / CUSTOM), `type: 'custom'` are import pages (showing importStamps); * text defaults to panels.stamp. (StampPanel.vue). */ interface StampPanelTab { /** 'tab' for a built-in page (STANDARD, DYNAMIC or CUSTOM); 'custom' for a page listing the images set with UI.setImportStamps. */ type: 'tab' | 'custom' /** Unique name of the tab; for built-in pages, STANDARD, DYNAMIC or CUSTOM. */ dataElement: string /** Tab label; defaults to the translation of panels.stamp.. */ text?: string } /** Signing method tabs of the signature dialog (DataElements.KEYBOARD / TRACKPAD and 'image'). */ type SignatureDialogTab = 'image' | 'keyboard' | 'trackpad' /** Properties of one tab of the signature dialog, passed to UI.setSignatureDialogProperties. */ interface SignatureDialogPropertiesArg { /** Color swatches offered in the tab, in display order. */ colors?: SignatureColorInput[] /** Whether the tab shows a custom color picker next to the swatches. */ enableCustomColor?: boolean /** keyboard (type tab) only. */ fonts?: SignatureFontInput[] /** trackpad (draw tab) only. */ enableLineWidth?: boolean /** trackpad only: the default line width (dialog slider 1 to 10). */ lineWidth?: number } /** UI.VerificationOptions: settings of digital signature verification. */ interface VerificationOptionsAPI { /** * Adds certificates to the trust list used when verifying signatures (the list only grows); an open document is verified again right away. * Files and bytes are read now (items that cannot be read are skipped with a warning). URLs are kept and downloaded again at every verification (each document load and re-verification), * so certificates changed on the server apply to the next verification; a URL that cannot be downloaded is skipped for that verification with a console error. * The trust list is kept in memory only. To keep certificates the user trusts in the certificate viewer, store them on `UI.Events.TRUSTED_CERTIFICATE_ADDED` * and pass them here after the viewer loads; certificates added here do not fire that event. * @param certificates Certificates in PEM or DER form: URLs, Files / Blobs, ArrayBuffers or typed arrays. * @returns A Promise that resolves once the certificates are read and the document is verified again. * @example * ```js * await instance.UI.VerificationOptions.addTrustedCertificates(['/certs/root-ca.pem']); * * // Keep the certificates the user trusts on your server and trust them again next time * instance.UI.addEventListener(instance.UI.Events.TRUSTED_CERTIFICATE_ADDED, ({ fieldName, certificate }) => { * fetch('/api/trusted-certificates', { method: 'POST', body: certificate }); * }); * // Certificate URLs are downloaded again on every document load, so newly saved ones are picked up * await instance.UI.VerificationOptions.addTrustedCertificates(['https://example.com/api/trusted-certificates/1.cer']); * ``` */ addTrustedCertificates(certificates: CertificateInput[]): Promise } /** Consecutive form filling settings of one document viewer (UI.FormFill.getSettings / setSettings). */ interface FormFillSettings { /** Which fields the form fill navigator steps through; false turns consecutive filling off. */ type: FormFillConsecutive /** Only required fields are visited and counted. */ skipNonRequired: boolean /** Whether fields to fill are outlined and filling a field moves to the next one after 500 ms; true by default. */ enabled: boolean /** Order of the fields: 'CREATE' keeps the document order, 'DISTANCE' (default) sorts by page, then from top to bottom. */ order: 'CREATE' | 'DISTANCE' /** Also visits fields marked as not shown on screen (NoView); false by default. */ includeNoView: boolean /** The current field follows the field that has focus (or the check box or radio button last changed) instead of the field reached with Previous / Next; false by default. */ preferFocused: boolean /** Forces fill mode on (true) or off (false) in the forms toolbar group; null (default) follows the form design mode. */ fillMode: boolean | null } /** Minimal shape of a form field (core WidgetAnnotation subclasses). */ interface WidgetLike { /** Annotation type, for example 'textWidget', 'checkButtonWidget' or 'signatureWidget'. */ elementName?: string /** Page number of the widget, starting at 1. */ PageNumber?: number /** Left edge of the widget in page coordinates. */ X?: number /** Top edge of the widget in page coordinates. */ Y?: number /** Whether the widget is hidden. */ Hidden?: boolean /** Whether the widget is invisible. */ Invisible?: boolean /** Whether the widget cannot be changed. */ ReadOnly?: boolean /** Whether the widget is not shown on screen. */ NoView?: boolean /** Name of the form field the widget belongs to. */ fieldName?: string /** * Returns the flags of the form field. * @returns An object whose `get(flag)` tells whether a flag such as 'Required' or 'ReadOnly' is set. */ getFieldFlags?: () => WidgetFieldFlags /** * Returns the value of the form field. * @returns The field value. */ getValue?: () => unknown /** * Tells whether a signature field is signed with an appearance only. * @returns Whether it is signed with an appearance. */ isSignedByAppearance?: () => boolean /** * Tells whether a signature field is digitally signed. * @returns Whether it is digitally signed. */ isDigitallySigned?: () => boolean /** * Returns the signature annotation placed on a signature field. * @returns The signature annotation, if any. */ getAssociatedSignatureAnnotation?: () => unknown } /** Which fields the form fill navigator steps through: off / signatures and forms / signatures only / forms only. */ type FormFillConsecutive = false | 'signForm' | 'sign' | 'form' /** ★FormFillNavigator position (px relative to the instance root element). */ interface FormFillNavigatorPosition { /** Distance from the left edge of the viewer, in px; 30 by default. */ left: number /** Distance from the top edge of the viewer, in px; 100 by default. */ top: number } /** Sync scrolling mode of the two viewers: 'SYNC' scrolls them together; 'SKIP_UNMATCHED' is stored but currently behaves like 'SYNC'. */ type MultiViewerSyncScrollMode = 'SYNC' | 'SKIP_UNMATCHED' /** Callback of UI.setCustomMultiViewerSyncHandler: (main view key, removeHandlerFunctions) — the handler pushes the remove functions of its listeners there, and all are called when sync stops. */ type CustomMultiViewerSyncHandler = (primaryDocumentViewerKey: number, removeHandlerFunctions: Array<() => void>) => void /** Shortcut handler: a function is called on keydown; an object has one handler each for keydown / keyup. */ type HotkeyHandler = ((event: KeyboardEvent) => unknown) | { /** Called when the shortcut key is pressed. */ keydown?: (event: KeyboardEvent) => unknown /** Called when the shortcut key is released. */ keyup?: (event: KeyboardEvent) => unknown } /** One item of UI.setCustomSettings: one switch row in the settings dialog (UI.CustomSettingItem). */ interface CustomSettingItem { /** Label of the row. */ label: string /** Description shown under the label. */ description: string /** State of the switch, or a function returning it (called again after each toggle). */ isChecked: boolean | (() => boolean) /** * Called immediately when the switch is toggled. * @param checked The new state of the switch. */ onToggled(checked: boolean): void } /** User settings returned by UI.exportUserSettings and accepted by UI.importUserSettings. A `disableXxx` key set to true means the item is turned off. */ interface UserSettings { /** Language code of the UI, for example 'en'. */ language: string /** UI theme: 'light' or 'dark'. */ theme: string /** Key of each keyboard shortcut, keyed by shortcut name; an empty string means unbound. Importing it replaces the whole map, so shortcuts it does not list are unbound. */ keyboardShortcut: Record /** Page navigation fading is off. Kept with the settings; it does not affect the UI (the page number overlay stays visible). */ disableFadePageNavigationComponent: boolean /** Native scrolling on mobile is off. Kept with the settings; it does not affect the UI. */ disableNativeScrolling: boolean /** Style changes made on an annotation are not copied to the tool defaults. Kept with the settings; the style panel follows UI.enableAnnotationToolStyleSyncing instead. */ disableToolDefaultStyleUpdateFromAnnotationPopup: boolean /** Pressing Enter in the reply box adds a new line instead of submitting. */ disableNoteSubmissionWithEnter: boolean /** Replies in the notes panel are shown only for the selected item, instead of expanded for every item. */ disableAutoExpandCommentThread: boolean /** Reply collapsing in the notes panel is off. Kept with the settings; it does not affect the notes panel. */ disableReplyCollapse: boolean /** Long note collapsing in the notes panel is off. Kept with the settings; it does not affect the notes panel. */ disableTextCollapse: boolean /** Search results are kept when the search panel closes. */ disableClearSearchOnPanelClose: boolean /** Pasted annotations keep their page positions instead of following their positions in the viewport. */ disableViewportRelativePositioning: boolean /** The thumbnails panel is not in multi-select mode (see UI.ThumbnailsPanel.enableMultiSelect). Kept with the settings; it does not affect the thumbnails panel. */ disableThumbnailMultiselect: boolean /** Deleting pages in the page editor does not ask for confirmation. */ disablePageDeletionConfirmationModal: boolean } /** Options of UI.loadDocument: the core document loading options, without the license key (the viewer's license is used). */ type UILoadDocumentOptions = { /** A wrong string reports PASSWORD_REQUIRED; the function form can ask repeatedly */ password?: string | ((checkPassword: (password: string) => void) => void) /** 0–1, (download progress + Worker load progress) / 2, never decreasing; reports 1 exactly once at the end on success */ onLoadingProgress?: (percent: number) => void /** On load failure, called back first, then rejects */ onError?: (error: ComPDFKitError) => void /** Takes precedence over the file name inferred from the source */ filename?: string /** Business id of the document (Document.getDocumentId(), the argument of setDocumentXFDFRetriever) */ documentId?: string /** An explicitly passed non-pdf type is rejected before reading; the format is decided by the file header */ extension?: string /** Request headers for URL sources */ customHeaders?: Record /** Send cookies for cross-origin URL sources */ withCredentials?: boolean /** Aborts the load when signaled. */ signal?: AbortSignal } & { /** Another name for `documentId`; used when `documentId` is not given. */ docId?: string } /** Options of UI.downloadPdf. */ interface DownloadPdfOptions { /** Name of the downloaded file; '.pdf' is added when missing. Defaults to the document's file name. */ filename?: string /** XFDF whose annotations replace the annotations in the downloaded file. */ xfdfString?: string /** When false, the downloaded file contains no annotations. */ includeAnnotations?: boolean /** Burns annotations, including form fields, into page content. */ flatten?: boolean /** Save flags, such as SaveOptions.INCREMENTAL. */ flags?: SaveOptions } /** * Callback of UI.setClickMiddleware: (dataElement of the clicked element, { type }). * @param dataElement The dataElement of the clicked element. * @param info Details of the click. * @param info.type Kind of the clicked element (a UI.ClickedItemTypes value; currently always 'button'). */ type ClickMiddleware = (dataElement: string, info: { type: string; }) => void /** One range of the zoom step table passed to `setZoomStepFactors`. */ interface ZoomStepFactorInput { /** Percentage added or subtracted by the zoom in / zoom out buttons in this range, as a number or a string such as '25' or '25%'; must be positive. */ step: string | number /** Zoom percentage where this range starts, as a number or a string such as '200' or '200%'; one range must start at 0. */ startZoom: string | number } /** One range of the zoom step table returned by `getZoomStepFactors`. */ interface ZoomStepFactor { /** Percentage added or subtracted by the zoom in / zoom out buttons in this range. */ step: number /** Zoom percentage where this range starts. */ startZoom: number } /** Scroll direction of the pages: `'Vertical'` (pages in a column) or `'Horizontal'` (all pages in one row). */ type ScrollMode = 'Vertical' | 'Horizontal' /** How the viewer is mounted. Only 'iframe' (the default) is available in this version; other values are rejected. */ type MountMode = 'inline' | 'iframe' | 'web-component' /** Settings of the compatibility layer for the 2.x API (WebViewerOptions.compat). By default, every call to a deprecated API logs a console notice. */ interface CompatOptions { /** Turns off console notices (onDeprecated is still called). */ silent?: boolean /** Hands notices to the integrator for reporting. */ onDeprecated?: (info: DeprecationInfo) => void } /** Side of the viewer a panel opens on: 'left' or 'right'; 'start' and 'end' are accepted too ('start' is the left side in a left-to-right layout). */ type PanelLocation = 'start' | 'end' | 'left' | 'right' /** An annotation of the core library. */ type Annotation = Core.Annotations.Annotation /** Context passed to the functions of a notes panel sort strategy. */ interface SortOptions { /** Page labels of the document, indexed by page number minus one. */ pageLabels: readonly string[] /** * Translates a key into the current UI language. * @param key Translation key. * @returns The translated text. */ t(key: string): string /** Key of the document viewer whose notes are listed (1 for the main viewer). */ documentViewerKey: number /** * Returns the name shown for an annotation author. * @param author The author stored on the annotation. * @returns The display name. */ getDisplayAuthor?: (author: string) => string } /** One button of a custom page operation group (`PageManipulationItem.operations`). */ interface PageOperation { [key: string]: unknown /** Label of the button. */ title: string /** Icon of the button. */ img: string /** * Called when the button is clicked. * @param selectedPageNumbers Page numbers of the selected thumbnails. */ onClick(selectedPageNumbers: number[]): void /** Unique name of the button. */ dataElement: string } /** Font dropdown item. */ interface FontItem { /** Label shown in the font dropdown. */ fontFamily: string /** Font name applied to the annotation, form field or text when the item is chosen. */ fontName: string } /** A font given to UI.Fonts: a font name (used as both the label and the applied font), or a font item. */ type FontInput = string | FontItem /** A swatch `{ type: 'color', value }` or a color string. */ type SignatureColorInput = string | { /** Kept for compatibility; it is not read. */ type?: string /** The color, for example '#000000'. */ value: string } /** A font `{ fontFamily, label }` or a font name. */ type SignatureFontInput = string | { /** Font name. */ fontFamily: string /** Text shown on the font's preview card before anything is typed; the font name by default. */ label?: string /** Weight the font is shown and drawn with, for example 700; 400 by default. */ fontWeight?: number } /** Certificate inputs: URL, File / Blob, ArrayBuffer, typed arrays. */ type CertificateInput = string | ArrayBuffer | Blob | ArrayBufferView /** Form field flags of a widget, as returned by `WidgetLike.getFieldFlags`. */ interface WidgetFieldFlags { /** * Tells whether the named flag is set. * @param flag Flag name, such as 'Required' or 'ReadOnly'. * @returns Whether the flag is set. */ get(flag: string): boolean } /** A deprecation notice handed to CompatOptions.onDeprecated, once per call to a deprecated API. */ interface DeprecationInfo { /** The deprecated name, for example `docViewer.addEvent`, `event:documentloaded` or `option:pdfUrl`. */ key: string /** The API to use instead; omitted when there is none. */ replacement?: string /** Link to the migration guide section for this name. */ docUrl: string } /** The object a WebViewer call resolves to. */ interface WebViewerInstance { /** The core namespace bound to this instance's main viewer. */ readonly Core: typeof Core & { /** The main document viewer of this instance. */ readonly documentViewer: DocumentViewer /** The annotation manager of the main document viewer. */ readonly annotationManager: AnnotationManager /** * Returns all document viewers of this instance. * @returns The document viewers; the second one exists while the side-by-side view is open. */ getDocumentViewers(): DocumentViewer[] } /** The UI namespace of this instance. */ readonly UI: typeof UI } /** * Code of a WebViewerError: * 'INVALID_OPTIONS' (missing path, element is not an HTMLElement, unsupported mount or invalid URL), 'ALREADY_MOUNTED' (a viewer is already mounted on the element), * 'UNSUPPORTED_BROWSER' (no Canvas, WebAssembly or Worker), 'UI_LOAD_FAILED' (the UI page did not load or register; check path / uiPath), * 'VERSION_MISMATCH' (the loader and UI versions differ), 'INIT_FAILED' (the UI failed to initialize), 'DESTROYED' (destroyed before it was ready). */ type WebViewerErrorCode = 'INVALID_OPTIONS' | 'ALREADY_MOUNTED' | 'UNSUPPORTED_BROWSER' | 'UI_LOAD_FAILED' | 'VERSION_MISMATCH' | 'INIT_FAILED' | 'DESTROYED' /** Error a WebViewer call rejects with. */ declare class WebViewerError extends Error { /** Always 'WebViewerError'. */ readonly name: 'WebViewerError' /** Code of the error. */ readonly code: WebViewerErrorCode /** Description of the error. */ message: string /** Stack trace, when the runtime provides one. */ stack?: string /** The underlying error, if any. */ cause?: unknown /** * Creates a WebViewerError. * @param message Description of the error. * @param code Code of the error. * @param options Error options. * @param options.cause The underlying error, if any. */ constructor(message: string, code: WebViewerErrorCode, options?: { cause?: unknown }) } /** Entry of the SDK: call it to create a viewer. */ declare const WebViewer: { /** * Creates a WebViewer inside `element`. * Resolves undefined when the UI is served from another origin (the instance cannot be reached from the host page). */ (options: WebViewerOptions, element: HTMLElement): Promise /** @deprecated The 2.x entry, kept for existing integrations. Use `WebViewer(options, element)`. */ init(options: Record, element: HTMLElement): Promise /** The WebViewer version. */ readonly version: string /** The WebViewerError class, for `err instanceof WebViewer.WebViewerError`. */ readonly WebViewerError: typeof WebViewerError } export { Core, UI, WebViewerError, WebViewer as default }; export type { Annotation, CertificateInput, ClickMiddleware, ColorSeparationProfile, CompatOptions, CoreTool, CustomApplyRedactionsHandler, CustomEmptyPanelOptions, CustomFillStyleOptions, CustomHeaderOptions, CustomLoadingOptions, CustomModalOptions, CustomMultiViewerSyncHandler, CustomSettingItem, DeprecationInfo, DownloadPdfOptions, FlyoutData, FlyoutItem, FlyoutOptions, FlyoutsAPI, FontInput, FontItem, FontsAPI, FormFillConsecutive, FormFillNavigatorPosition, FormFillSettings, FunctionRef, GroupedItemsSelectors, HotkeyHandler, ItemListAPI, ItemOptions, LanguageItem, MainMenuOptions, MeasurementSystem, MenuOverlayAPI, ModularComponent, ModularComponentsData, ModularHeaderData, MountMode, MultiViewerSyncScrollMode, OutlineJumpHandler, OutlinesPanelAPI, OwnLayout, PageManipulationItem, PageManipulationOverlayAPI, PageOperation, PageReplacementFile, PaletteOption, Panel, PanelData, PanelLocation, PopupAPI, PopupItem, PresetCropDimension, PresetNewPageDimension, PrintDefaults, PrintInBackgroundOptions, RedactionSearchPattern, ScaleOverlayPosition, ScrollMode, SearchOptions, SignatureColorInput, SignatureDialogPropertiesArg, SignatureDialogTab, SignatureFontInput, SortOptions, SortStrategy, StampPanelTab, TabPanelItem, TabPanelOptions, ThumbnailMenuItem, ThumbnailSelectionMode, ToolButtonUpdate, ToolRegistration, UILoadDocumentOptions, UserSettings, VerificationOptionsAPI, WarningMessageOptions, WebViewerErrorCode, WebViewerInstance, WebViewerOptions, WidgetFieldFlags, WidgetLike, ZoomStepFactor, ZoomStepFactorInput };