import { C as PdfRef, S as PdfObjectRegistry, T as PdfString, _ as PdfDict, h as PdfArray, t as PdfForm, w as PdfStream, x as PdfObject } from "./pdfForm-Ca86NDWn.mjs"; //#region src/core/operators/color.d.ts /** * @module core/operators/color * * PDF colour operators and convenience constructors for typed colour * values. * * Reference: PDF 1.7 spec, §8.6 (Colour Spaces). */ /** An RGB colour with components in the range `[0, 1]`. */ interface RgbColor { readonly type: "rgb"; readonly r: number; readonly g: number; readonly b: number; } /** A CMYK colour with components in the range `[0, 1]`. */ interface CmykColor { readonly type: "cmyk"; readonly c: number; readonly m: number; readonly y: number; readonly k: number; } /** A grayscale colour with the component in the range `[0, 1]`. */ interface GrayscaleColor { readonly type: "grayscale"; readonly gray: number; } /** A spot (Separation) colour with a named colorant and a fallback. */ interface SpotColor { readonly type: "spot"; /** Colorant name, e.g. `'PANTONE 185 C'`. */ readonly name: string; /** Fallback colour used when the spot ink is unavailable. */ readonly alternateColor: RgbColor | CmykColor | GrayscaleColor; /** Tint value `[0, 1]` — 0 = no ink, 1 = full ink. */ readonly tint: number; } /** A DeviceN colour for multi-ink printing. */ interface DeviceNColor { readonly type: "devicen"; /** Ordered list of colorant names. */ readonly colorants: string[]; /** Alternate colour space used for fallback rendering. */ readonly alternateSpace: "DeviceCMYK" | "DeviceRGB"; /** Tint value for each colorant `[0, 1]`. */ readonly tints: number[]; } /** Union of all supported colour value types. */ type Color = RgbColor | CmykColor | GrayscaleColor | SpotColor | DeviceNColor; /** * Create an RGB colour. * * @param r Red component `[0, 1]`. * @param g Green component `[0, 1]`. * @param b Blue component `[0, 1]`. */ declare function rgb(r: number, g: number, b: number): RgbColor; /** * Create a CMYK colour. * * @param c Cyan component `[0, 1]`. * @param m Magenta component `[0, 1]`. * @param y Yellow component `[0, 1]`. * @param k Black component `[0, 1]`. */ declare function cmyk(c: number, m: number, y: number, k: number): CmykColor; /** * Create a grayscale colour. * * @param gray Gray level `[0, 1]` where 0 = black, 1 = white. */ declare function grayscale(gray: number): GrayscaleColor; /** * Create a spot (Separation) colour. * * Spot colours map to a named ink (e.g. a Pantone shade) with a * device-space fallback and a tint value that controls intensity. * * @param name Colorant name, e.g. `'PANTONE 185 C'`. * @param alternate Fallback colour (RGB, CMYK, or grayscale). * @param tint Tint intensity `[0, 1]`. Defaults to `1`. */ declare function spotColor(name: string, alternate: RgbColor | CmykColor | GrayscaleColor, tint?: number): SpotColor; /** * Create a DeviceN colour for multi-ink printing. * * @param colorants Ordered list of colorant names. * @param alternateSpace Alternate colour space (`'DeviceCMYK'` or `'DeviceRGB'`). * @param tints Tint value per colorant `[0, 1]`. */ declare function deviceNColor(colorants: string[], alternateSpace: "DeviceCMYK" | "DeviceRGB", tints: number[]): DeviceNColor; /** * Convert RGB components to CMYK. * * Uses the standard RGB-to-CMYK formula: * ``` * K = 1 - max(R, G, B) * C = (1 - R - K) / (1 - K) * M = (1 - G - K) / (1 - K) * Y = (1 - B - K) / (1 - K) * ``` * * @returns A tuple `[C, M, Y, K]` with values in `[0, 1]`. */ declare function rgbToCmyk(r: number, g: number, b: number): [number, number, number, number]; /** * Convert CMYK components to RGB. * * Uses the standard CMYK-to-RGB formula: * ``` * R = (1 - C) * (1 - K) * G = (1 - M) * (1 - K) * B = (1 - Y) * (1 - K) * ``` * * @returns A tuple `[R, G, B]` with values in `[0, 1]`. */ declare function cmykToRgb(c: number, m: number, y: number, k: number): [number, number, number]; /** * Convert a base colour (RGB, CMYK, or grayscale) to a hex string. * * - RGB → `'#rrggbb'` * - CMYK → converted to RGB first, then `'#rrggbb'` * - Grayscale → `'#gggggg'` * - Spot → uses the alternate colour * - DeviceN → throws (no single representation) * * @returns A 7-character hex string like `'#ff0000'`. */ declare function colorToHex(color: Color): string; /** * Parse a hex colour string into an {@link RgbColor}. * * Accepts `'#rgb'`, `'#rrggbb'`, `'rgb'`, or `'rrggbb'` formats. */ declare function hexToColor(hex: string): RgbColor; /** * Set the fill colour in the DeviceRGB colour space (`rg`). * * @param r Red `[0, 1]`. * @param g Green `[0, 1]`. * @param b Blue `[0, 1]`. */ declare function setFillColorRgb(r: number, g: number, b: number): string; /** * Set the fill colour in the DeviceCMYK colour space (`k`). */ declare function setFillColorCmyk(c: number, m: number, y: number, k: number): string; /** * Set the fill colour in the DeviceGray colour space (`g`). */ declare function setFillColorGray(gray: number): string; /** * Set the stroke colour in the DeviceRGB colour space (`RG`). */ declare function setStrokeColorRgb(r: number, g: number, b: number): string; /** * Set the stroke colour in the DeviceCMYK colour space (`K`). */ declare function setStrokeColorCmyk(c: number, m: number, y: number, k: number): string; /** * Set the stroke colour in the DeviceGray colour space (`G`). */ declare function setStrokeColorGray(gray: number): string; /** * Set the current non-stroking colour space (`cs`). * * @param name Colour space name (e.g. `DeviceRGB`, `DeviceCMYK`, * `DeviceGray`, or a named resource). */ declare function setColorSpace(name: string): string; /** * Set the current stroking colour space (`CS`). */ declare function setStrokeColorSpace(name: string): string; /** * Set the non-stroking colour in the current colour space (`scn`). * * @param components One or more colour components. */ declare function setFillColor(...components: number[]): string; /** * Set the stroking colour in the current colour space (`SCN`). * * @param components One or more colour components. */ declare function setStrokeColor(...components: number[]): string; /** * Emit the appropriate fill-colour operator for a {@link Color} value. * * For spot colours, emits a `cs` (set colour space) followed by `scn` * (set colour in current space) using the spot colour's resource name. * The caller must ensure the Separation colour space is registered as * a page resource with the matching name. * * For DeviceN colours, emits `cs` + `scn` with the tint values. */ declare function applyFillColor(color: Color): string; /** * Emit the appropriate stroke-colour operator for a {@link Color} value. * * For spot colours, emits a `CS` (set stroking colour space) followed * by `SCN` (set stroking colour in current space). * * For DeviceN colours, emits `CS` + `SCN` with the tint values. */ declare function applyStrokeColor(color: Color): string; /** * Derive a PDF resource name from a spot colorant name. * * Replaces spaces and special characters with underscores to produce * a valid PDF name. * * @example * ```ts * spotResourceName('PANTONE 185 C') // 'CS_PANTONE_185_C' * ``` */ declare function spotResourceName(colorantName: string): string; /** * Derive a PDF resource name from a DeviceN colorant list. */ declare function deviceNResourceName(colorants: string[]): string; /** * Convert a numeric component array to a typed {@link Color}. * * - 1 component → grayscale * - 3 components → RGB * - 4 components → CMYK * * @param components Array of color component values `[0, 1]`. * @throws If the array length is not 1, 3, or 4. */ declare function componentsToColor(components: number[]): Color; /** * Convert a typed {@link Color} to a numeric component array. * * - Grayscale → `[gray]` * - RGB → `[r, g, b]` * - CMYK → `[c, m, y, k]` * - Spot → `[tint]` * - DeviceN → `[...tints]` */ declare function colorToComponents(color: Color): number[]; /** * Emit the appropriate fill-colour operator for a {@link Color} value. * * @deprecated Use {@link applyFillColor} instead. This alias exists only * for pdf-lib API compatibility and will be removed in v2.0. */ declare const setFillingColor: typeof applyFillColor; /** * Emit the appropriate stroke-colour operator for a {@link Color} value. * * @deprecated Use {@link applyStrokeColor} instead. This alias exists only * for pdf-lib API compatibility and will be removed in v2.0. */ declare const setStrokingColor: typeof applyStrokeColor; //#endregion //#region src/core/operators/state.d.ts /** A rotation / angle value in radians. */ interface Radians { readonly type: "radians"; readonly value: number; } /** A rotation / angle value in degrees. */ interface Degrees { readonly type: "degrees"; readonly value: number; } /** Union of angle representations. */ type Angle = Radians | Degrees; /** * Create an angle in degrees. * * @param deg Angle in degrees (positive = counter-clockwise). */ declare function degrees(deg: number): Degrees; /** * Create an angle in radians. * * @param rad Angle in radians (positive = counter-clockwise). */ declare function radians(rad: number): Radians; /** * Save the current graphics state on the graphics state stack (`q`). */ declare function saveState(): string; /** * Restore the most recently saved graphics state (`Q`). */ declare function restoreState(): string; /** * Concatenate the given matrix with the current transformation matrix * (`cm`). * * The six operands define the matrix: * * ``` * [ a b 0 ] * [ c d 0 ] * [ tx ty 1 ] * ``` * * @param a Horizontal scaling / rotation. * @param b Rotation / skew. * @param c Rotation / skew. * @param d Vertical scaling / rotation. * @param tx Horizontal translation. * @param ty Vertical translation. */ declare function concatMatrix(a: number, b: number, c: number, d: number, tx: number, ty: number): string; /** * Produce a `cm` operator that applies a **translation**. * * @param tx Horizontal distance. * @param ty Vertical distance. */ declare function translate(tx: number, ty: number): string; /** * Produce a `cm` operator that applies a **uniform scale** about the * origin. * * @param sx Horizontal scale factor. * @param sy Vertical scale factor. */ declare function scale(sx: number, sy: number): string; /** * Produce a `cm` operator that applies a **rotation** about the origin. * * @param angle Rotation angle. */ declare function rotate(angle: Angle): string; /** * Produce a `cm` operator that applies a **skew** (shear). * * @param xAngle Skew angle for the x axis. * @param yAngle Skew angle for the y axis. */ declare function skew(xAngle: Angle, yAngle: Angle): string; /** * Build the six-component matrix array for a rotation about an * arbitrary centre point `(cx, cy)`. * * Useful when you need to compose this with other transformations * before emitting operators. * * @returns `[a, b, c, d, tx, ty]` */ declare function rotationMatrix(angle: Angle, cx: number, cy: number): [number, number, number, number, number, number]; /** * Set the graphics state dictionary (`gs`). * * The `name` must refer to an entry in the page's `/Resources /ExtGState` * dictionary. * * @param name Graphics-state resource name (e.g. `GS1`). */ declare function setGraphicsState(name: string): string; /** * Convert degrees to radians. * * @param deg Angle in degrees. * @returns Angle in radians. */ declare function degreesToRadians(deg: number): number; /** * Convert radians to degrees. * * @param rad Angle in radians. * @returns Angle in degrees. */ declare function radiansToDegrees(rad: number): number; //#endregion //#region src/core/enums.d.ts /** * PDF blend modes (PDF 1.4+, Table 136). * Applied via ExtGState /BM key. */ declare const BlendMode: { readonly Normal: "Normal"; readonly Multiply: "Multiply"; readonly Screen: "Screen"; readonly Overlay: "Overlay"; readonly Darken: "Darken"; readonly Lighten: "Lighten"; readonly ColorDodge: "ColorDodge"; readonly ColorBurn: "ColorBurn"; readonly HardLight: "HardLight"; readonly SoftLight: "SoftLight"; readonly Difference: "Difference"; readonly Exclusion: "Exclusion"; }; /** A PDF blend mode name. */ type BlendMode = (typeof BlendMode)[keyof typeof BlendMode]; /** * PDF text rendering modes (Table 106). * Applied via the Tr operator inside a text object. */ declare const TextRenderingMode: { readonly Fill: 0; readonly Outline: 1; readonly FillAndOutline: 2; readonly Invisible: 3; readonly FillAndClip: 4; readonly OutlineAndClip: 5; readonly FillAndOutlineAndClip: 6; readonly Clip: 7; }; /** A PDF text rendering mode integer (0-7). */ type TextRenderingMode = (typeof TextRenderingMode)[keyof typeof TextRenderingMode]; /** * PDF line cap styles (Table 54). * Applied via the J operator. */ declare const LineCapStyle: { readonly Butt: 0; readonly Round: 1; readonly Projecting: 2; }; type LineCapStyle = (typeof LineCapStyle)[keyof typeof LineCapStyle]; /** * PDF line join styles (Table 55). * Applied via the j operator. */ declare const LineJoinStyle: { readonly Miter: 0; readonly Round: 1; readonly Bevel: 2; }; type LineJoinStyle = (typeof LineJoinStyle)[keyof typeof LineJoinStyle]; /** * Text alignment for form fields and layout operations. */ declare const TextAlignment: { readonly Left: 0; readonly Center: 1; readonly Right: 2; }; type TextAlignment = (typeof TextAlignment)[keyof typeof TextAlignment]; /** * Image alignment for layout operations. */ declare const ImageAlignment: { readonly Left: 0; readonly Center: 1; readonly Right: 2; }; type ImageAlignment = (typeof ImageAlignment)[keyof typeof ImageAlignment]; /** * Preset parsing speeds — maps to objectsPerTick values in LoadPdfOptions. * * Lower values keep the main thread more responsive but parse more slowly. */ declare const ParseSpeeds: { readonly Fastest: number; readonly Fast: 500; readonly Medium: 100; readonly Slow: 10; }; type ParseSpeeds = (typeof ParseSpeeds)[keyof typeof ParseSpeeds]; //#endregion //#region src/accessibility/structureTree.d.ts /** * Standard structure types defined by the PDF specification (ISO 32000-1, * Table 333 through Table 340), plus a `string` catch-all for custom * structure types. * * Groups: * - **Grouping**: Document, Part, Art, Sect, Div, BlockQuote, Caption, * TOC, TOCI, Index, NonStruct, Private * - **Block-level**: P, H, H1..H6 * - **List**: L, LI, Lbl, LBody * - **Table**: Table, TR, TH, TD, THead, TBody, TFoot * - **Inline-level**: Span, Quote, Note, Reference, BibEntry, Code, * Link, Annot * - **Ruby / Warichu**: Ruby, RB, RT, RP, Warichu, WT, WP * - **Illustration**: Figure, Formula, Form */ type StructureType = "Document" | "Part" | "Art" | "Sect" | "Div" | "BlockQuote" | "Caption" | "TOC" | "TOCI" | "Index" | "NonStruct" | "Private" | "P" | "H" | "H1" | "H2" | "H3" | "H4" | "H5" | "H6" | "L" | "LI" | "Lbl" | "LBody" | "Table" | "TR" | "TH" | "TD" | "THead" | "TBody" | "TFoot" | "Span" | "Quote" | "Note" | "Reference" | "BibEntry" | "Code" | "Link" | "Annot" | "Ruby" | "RB" | "RT" | "RP" | "Warichu" | "WT" | "WP" | "Figure" | "Formula" | "Form" | (string & {}); /** * Optional attributes for a structure element. */ interface StructureElementOptions { /** The element title (a human-readable label). */ title?: string | undefined; /** Alternative text for the element (required for images by PDF/UA). */ altText?: string | undefined; /** Replacement text that may be used instead of the element's content. */ actualText?: string | undefined; /** The natural language for this element (BCP 47, e.g. `"en-US"`). */ language?: string | undefined; /** An optional unique identifier for the element. */ id?: string | undefined; /** * Whether this element is an artifact (decorative, pagination, etc.). * Artifact elements are excluded from accessibility checks such as * alt text requirements. */ artifact?: boolean | undefined; /** * Presentational role hint for the element. Setting `role` to * `"presentation"` marks the element as layout-only (e.g. a layout * table that should not be treated as a data table). */ role?: "presentation" | (string & {}) | undefined; /** * Header scope for TH cells (`"Row"`, `"Column"`, or `"Both"`). * Used by table header validation. */ scope?: "Row" | "Column" | "Both" | undefined; /** * Number of columns this cell spans (for TH/TD elements). * Defaults to 1 when not specified. */ colSpan?: number | undefined; /** * Number of rows this cell spans (for TH/TD elements). * Defaults to 1 when not specified. */ rowSpan?: number | undefined; } /** * Describes a single accessibility issue found during validation. */ interface AccessibilityIssue { /** Severity of the issue. */ severity: "error" | "warning" | "info"; /** Machine-readable issue code. */ code: string; /** Human-readable description of the issue. */ message: string; /** The structure element related to the issue, if any. */ element?: PdfStructureElement | undefined; /** The zero-based page index related to the issue, if any. */ pageIndex?: number | undefined; } /** * A single node in the structure tree. * * Structure elements form a tree that mirrors the logical reading order * of the document. Each element has a type (e.g. `"P"`, `"H1"`, * `"Table"`), optional attributes, and may contain child elements or * marked-content references (MCIDs) that link to the actual page * content. */ declare class PdfStructureElement { /** The structure type of this element. */ readonly type: StructureType; /** Child structure elements. */ readonly children: PdfStructureElement[]; /** Optional attributes (alt text, language, title, etc.). */ readonly options: StructureElementOptions; /** Marked content ID linking this element to page content. */ mcid?: number | undefined; /** Zero-based page index this element's content appears on. */ pageIndex?: number | undefined; /** The parent element (undefined for the root). */ parent?: PdfStructureElement | undefined; /** * @param type The structure type (e.g. `"P"`, `"H1"`, `"Figure"`). * @param options Optional attributes for the element. */ constructor(type: StructureType, options?: StructureElementOptions); /** * Add a child element to this node. * * @param type The child's structure type. * @param options Optional attributes for the child. * @returns The newly created child element. */ addChild(type: StructureType, options?: StructureElementOptions): PdfStructureElement; /** * Remove a direct child element. * * @param element The child to remove. * @throws If the element is not a direct child. */ removeChild(element: PdfStructureElement): void; /** * Recursively collect all elements in the subtree (depth-first, * including this element). */ walk(): PdfStructureElement[]; /** * Find the first descendant (or self) matching the given type. */ find(type: StructureType): PdfStructureElement | undefined; /** * Find all descendants (and self) matching the given type. */ findAll(type: StructureType): PdfStructureElement[]; /** * Return the depth of this element in the tree (root = 0). */ depth(): number; /** * Serialize this element to a PDF dictionary. * * @param registry Object registry for allocating indirect references. * @param parentRef Reference to the parent element (or StructTreeRoot). * @param pageRefs Array of page references indexed by page number. * @returns An object containing the element's dict and its ref. */ toDict(registry: PdfObjectRegistry, parentRef: PdfRef, pageRefs: readonly PdfRef[]): { ref: PdfRef; dict: PdfDict; }; } /** * The structure tree for a tagged PDF document. * * Manages the root `Document` element, assigns marked-content IDs * (MCIDs), and provides serialization to/from PDF dictionaries. * * Usage: * ```ts * const tree = doc.createStructureTree(); * const heading = tree.addElement(null, 'H1', { altText: 'Main heading' }); * tree.assignMcid(heading, 0); * * const para = tree.addElement(null, 'P'); * tree.assignMcid(para, 0); * ``` */ declare class PdfStructureTree { /** The root `Document` structure element. */ readonly root: PdfStructureElement; /** Next available marked-content ID. */ private nextMcid; constructor(); /** * Add an element to the structure tree. * * @param parent The parent element, or `null` to add directly under * the root `Document` element. * @param type The structure type of the new element. * @param options Optional attributes for the element. * @returns The newly created element. */ addElement(parent: PdfStructureElement | null, type: StructureType, options?: StructureElementOptions): PdfStructureElement; /** * Remove an element from the tree. * * @param element The element to remove (must not be the root). * @throws If the element is the root or has no parent. */ removeElement(element: PdfStructureElement): void; /** * Assign a marked-content ID to an element and associate it with a * page. The MCID links the structure element to the actual content * on the page (via BMC/BDC operators in the content stream). * * @param element The element to assign an MCID to. * @param pageIndex The zero-based page index the content appears on. * @returns The assigned MCID. */ assignMcid(element: PdfStructureElement, pageIndex: number): number; /** * Return all elements in the tree (depth-first traversal from root). */ getAllElements(): PdfStructureElement[]; /** * Return the current MCID counter value (useful for testing). */ getNextMcid(): number; /** * Serialize the structure tree to a `/StructTreeRoot` dictionary. * * The resulting dict is suitable for embedding in the PDF catalog * as `/StructTreeRoot`. * * @param registry Object registry for allocating indirect references. * @param pageRefs Array of page references indexed by page number. * @returns An object containing the StructTreeRoot ref and dict. */ toDict(registry: PdfObjectRegistry, pageRefs: readonly PdfRef[]): { ref: PdfRef; dict: PdfDict; }; /** * Build the /ParentTree number tree. * * The parent tree maps each MCID to the structure element that * "owns" it. This is implemented as a number tree (a sorted * array of [key, value] pairs stored in /Nums). * * @internal */ private buildParentTree; /** * Build the /IDTree name tree. * * Maps element IDs (strings) to their structure element references. * * @internal */ private buildIdTree; /** * Reconstruct a structure tree from a `/StructTreeRoot` dictionary. * * @param dict The `/StructTreeRoot` dictionary. * @param resolver A function that resolves indirect references to * their underlying PDF objects. * @returns A new {@link PdfStructureTree}. */ static fromDict(dict: PdfDict, resolver: (ref: PdfRef) => PdfObject | undefined): PdfStructureTree; /** * Validate the structure tree for common accessibility issues. * * Checks: * - Heading hierarchy (no skipped levels) * - Table structure completeness * - Illustration elements have alt text * - List structure completeness * * @returns An array of {@link AccessibilityIssue} objects. */ validate(): AccessibilityIssue[]; /** * Validate heading hierarchy: headings should not skip levels * (e.g. H1 then H3 without H2). * * @internal */ private validateHeadingHierarchy; /** * Validate table structure: Table should contain TR, TR should * contain TH or TD. * * @internal */ private validateTableStructure; /** * Validate that illustration elements (Figure, Formula, Form) have * alt text. * * @internal */ private validateIllustrationAltText; /** * Validate list structure: L should contain LI, LI should contain * Lbl and/or LBody. * * @internal */ private validateListStructure; } //#endregion //#region src/annotation/pdfAnnotation.d.ts /** * All annotation subtypes defined in the PDF specification. */ type AnnotationType = "Text" | "Link" | "FreeText" | "Line" | "Square" | "Circle" | "Polygon" | "PolyLine" | "Highlight" | "Underline" | "Squiggly" | "StrikeOut" | "Stamp" | "Caret" | "Ink" | "Popup" | "FileAttachment" | "Sound" | "Movie" | "Widget" | "Screen" | "PrinterMark" | "TrapNet" | "Watermark" | "Redact" | "3D"; /** * Options for creating a new annotation. */ interface AnnotationOptions { /** Annotation rectangle [x1, y1, x2, y2] in default user space. */ rect: [number, number, number, number]; /** Text contents (displayed as tooltip or popup). */ contents?: string | undefined; /** Author / title of the annotation. */ author?: string | undefined; /** Last modification date. */ modificationDate?: Date | undefined; /** Colour in RGB (each component 0-1). */ color?: { r: number; g: number; b: number; } | undefined; /** Opacity (0 = transparent, 1 = opaque). */ opacity?: number | undefined; /** Annotation flags bitmask (PDF spec Table 165). */ flags?: number | undefined; /** Border specification. */ border?: { width: number; style?: "solid" | "dashed" | "beveled" | "inset" | "underline" | undefined; } | undefined; } /** Annotation flag bit positions. */ declare const AnnotationFlags: { readonly Invisible: number; readonly Hidden: number; readonly Print: number; readonly NoZoom: number; readonly NoRotate: number; readonly NoView: number; readonly ReadOnly: number; readonly Locked: number; readonly ToggleNoView: number; readonly LockedContents: number; }; /** * Create a PdfAnnotation from an existing dictionary. * * @param dict The annotation dictionary. * @param resolver Optional function to resolve indirect references. * @returns A PdfAnnotation instance. */ declare function annotationFromDict(dict: PdfDict, _resolver?: (ref: PdfRef) => PdfObject | undefined): PdfAnnotation; /** * Build an annotation dictionary from options. * * Used internally by subclass factory methods to populate common * annotation dictionary entries. * * @param type The annotation subtype. * @param options Creation options. * @returns A populated PdfDict. */ declare function buildAnnotationDict(type: AnnotationType, options: AnnotationOptions): PdfDict; /** * Create a new annotation with the given type and options. * * This is a convenience function that creates a generic PdfAnnotation. * For type-specific annotations, use the subclass `create()` methods. * * @param type The annotation subtype. * @param options Creation options (rect, contents, etc.). * @returns A new PdfAnnotation instance. */ declare function createAnnotation(type: AnnotationType, options: AnnotationOptions): PdfAnnotation; /** * Base class for all PDF annotations. * * Wraps a PdfDict representing the annotation dictionary. Subclasses * add type-specific getters/setters. */ declare class PdfAnnotation { /** The annotation subtype. */ readonly annotationType: AnnotationType; /** The underlying annotation dictionary. */ protected dict: PdfDict; constructor(type: AnnotationType, dict: PdfDict); /** Get the annotation subtype. */ getType(): AnnotationType; /** Get the annotation rectangle [x1, y1, x2, y2]. */ getRect(): [number, number, number, number]; /** Set the annotation rectangle. */ setRect(rect: [number, number, number, number]): void; /** Get the text contents (tooltip / popup text). */ getContents(): string | undefined; /** Set the text contents. */ setContents(contents: string): void; /** Get the author (PDF /T entry). */ getAuthor(): string | undefined; /** Set the author. */ setAuthor(author: string): void; /** Get the annotation colour. */ getColor(): { r: number; g: number; b: number; } | undefined; /** Set the annotation colour. */ setColor(color: { r: number; g: number; b: number; }): void; /** Get the annotation opacity (0-1). Defaults to 1. */ getOpacity(): number; /** Set the annotation opacity. */ setOpacity(opacity: number): void; /** Get the raw flags bitmask. */ private getFlags; /** Set the raw flags bitmask. */ private setFlags; /** Check if a specific flag bit is set. */ private hasFlag; /** Set or clear a specific flag bit. */ private setFlag; /** Whether the annotation is hidden. */ isHidden(): boolean; /** Set the hidden flag. */ setHidden(hidden: boolean): void; /** Whether the annotation should be printed. */ isPrintable(): boolean; /** Set the print flag. */ setPrintable(printable: boolean): void; /** Whether the annotation is locked (cannot be moved/resized). */ isLocked(): boolean; /** Set the locked flag. */ setLocked(locked: boolean): void; /** * Convert this annotation to a PdfDict suitable for embedding in a PDF. * * @param registry The object registry (used to register sub-objects). * @returns The annotation dictionary. */ toDict(registry: PdfObjectRegistry): PdfDict; /** * Generate an appearance stream for this annotation. * * The base implementation returns `undefined`. Subclasses override * to produce proper visual appearance. * * @returns A PdfStream for the /AP /N entry, or undefined. */ generateAppearance(): PdfStream | undefined; /** * Get the underlying dictionary (for internal use). * @internal */ getDict(): PdfDict; } //#endregion //#region src/assets/svg/svgParser.d.ts /** * @module assets/svg/svgParser * * Parse SVG XML into an intermediate representation of drawing commands. * * This parser uses a simple regex / state-machine approach (no DOMParser) * so that it works in every JavaScript runtime (Node, Deno, Bun, * Cloudflare Workers, browsers). * * Supported SVG elements: * ``, ``, ``, ``, ``, ``, * ``, ``, ``, `` (basic). * * Supported path commands: * M, m, L, l, H, h, V, v, C, c, S, s, Q, q, T, t, A, a, Z, z. */ /** A single drawing command produced from an SVG element. */ interface SvgDrawCommand { type: "moveTo" | "lineTo" | "curveTo" | "quadCurveTo" | "closePath" | "rect" | "circle" | "ellipse" | "arc"; params: number[]; } /** A single gradient colour stop. */ interface SvgGradientStop { /** Offset in range 0..1. */ offset: number; /** Stop colour (RGB, 0-255). */ color: { r: number; g: number; b: number; }; /** Stop opacity (0..1, default 1). */ opacity: number; } /** Parsed gradient definition from `` or ``. */ interface SvgGradient { /** Gradient type. */ type: "linearGradient" | "radialGradient"; /** Gradient XML id. */ id: string; /** Colour stops, sorted by offset. */ stops: SvgGradientStop[]; /** SVG `spreadMethod`: pad | reflect | repeat. Default: pad. */ spreadMethod: "pad" | "reflect" | "repeat"; /** SVG `gradientUnits`: objectBoundingBox | userSpaceOnUse. Default: objectBoundingBox. */ gradientUnits: "objectBoundingBox" | "userSpaceOnUse"; /** Optional `gradientTransform` as a 2D affine matrix [a,b,c,d,e,f]. */ gradientTransform?: [number, number, number, number, number, number] | undefined; x1?: number | undefined; y1?: number | undefined; x2?: number | undefined; y2?: number | undefined; cx?: number | undefined; cy?: number | undefined; r?: number | undefined; fx?: number | undefined; fy?: number | undefined; } /** Parsed representation of an SVG element. */ interface SvgElement { tag: string; attributes: Record; children: SvgElement[]; commands?: SvgDrawCommand[] | undefined; fill?: { r: number; g: number; b: number; a?: number | undefined; } | undefined; stroke?: { r: number; g: number; b: number; a?: number | undefined; } | undefined; strokeWidth?: number | undefined; transform?: [number, number, number, number, number, number] | undefined; opacity?: number | undefined; /** `evenodd` or `nonzero` (default). */ fillRule?: "nonzero" | "evenodd" | undefined; /** SVG `stroke-linecap`: butt | round | square. */ strokeLinecap?: "butt" | "round" | "square" | undefined; /** SVG `stroke-linejoin`: miter | round | bevel. */ strokeLinejoin?: "miter" | "round" | "bevel" | undefined; /** SVG `stroke-miterlimit`. */ strokeMiterlimit?: number | undefined; /** SVG `stroke-dasharray` as numeric array. */ strokeDasharray?: number[] | undefined; /** SVG `stroke-dashoffset`. */ strokeDashoffset?: number | undefined; /** Text content for `` / `` elements. */ textContent?: string | undefined; /** Font family name. */ fontFamily?: string | undefined; /** Font size in SVG user units. */ fontSize?: number | undefined; /** Font weight (e.g. `bold`, `normal`, or numeric). */ fontWeight?: string | undefined; /** Font style (e.g. `italic`, `normal`). */ fontStyle?: string | undefined; /** Text anchor: start | middle | end. */ textAnchor?: "start" | "middle" | "end" | undefined; /** Gradient definitions found in `` blocks, keyed by id. */ gradients?: Map | undefined; /** Fill gradient reference (resolved from `fill="url(#id)"`). */ fillGradientId?: string | undefined; /** Stroke gradient reference (resolved from `stroke="url(#id)"`). */ strokeGradientId?: string | undefined; } declare function parseSvgColor(colorStr: string): { r: number; g: number; b: number; a?: number | undefined; } | undefined; /** * Parse an SVG `transform` attribute into a 2D affine matrix. * * Returns `[a, b, c, d, e, f]` representing: * ``` * [ a c e ] * [ b d f ] * [ 0 0 1 ] * ``` * * Supports: `matrix`, `translate`, `scale`, `rotate`, `skewX`, `skewY`. * Multiple transforms are composed left-to-right. */ declare function parseSvgTransform(transformStr: string): [number, number, number, number, number, number]; /** * Parse an SVG path `d` attribute string into an array of drawing commands. * * Supports all SVG path commands (absolute and relative): * M, L, H, V, C, S, Q, T, A, Z. */ declare function parseSvgPath(d: string): SvgDrawCommand[]; /** * Interpolate between two colours in linear RGB space. * * Linear RGB interpolation converts sRGB (0-255) to linear light, * interpolates, then converts back. This produces perceptually * correct gradients. * * @param c0 Start colour (0-255 sRGB). * @param c1 End colour (0-255 sRGB). * @param t Interpolation factor (0..1). * @returns Interpolated colour (0-255 sRGB). */ declare function interpolateLinearRgb(c0: { r: number; g: number; b: number; }, c1: { r: number; g: number; b: number; }, t: number): { r: number; g: number; b: number; }; /** * Apply `spreadMethod` to a gradient parameter `t` outside [0, 1]. * * - `pad`: clamp to [0, 1] * - `reflect`: mirror at boundaries (0->1->0->1...) * - `repeat`: wrap around (0->1, 0->1, ...) */ declare function applySpreadMethod(t: number, method: "pad" | "reflect" | "repeat"): number; /** * Parse an SVG string into an {@link SvgElement} tree. * * The returned element represents the root `` element (or a * synthetic root if the input contains multiple top-level elements). */ declare function parseSvg(svgString: string): SvgElement; //#endregion //#region src/assets/svg/svgToPdf.d.ts /** Options for rendering an SVG onto a PDF page. */ interface SvgRenderOptions { /** Rendered width in PDF points. */ width?: number | undefined; /** Rendered height in PDF points. */ height?: number | undefined; /** X offset in PDF points. */ x?: number | undefined; /** Y offset in PDF points (bottom of the SVG). */ y?: number | undefined; /** Whether to preserve the aspect ratio of the SVG. */ preserveAspectRatio?: boolean | undefined; } /** * Convert an SVG element tree into PDF content stream operators. * * The returned string can be injected directly into a PDF page's * content stream. */ declare function svgToPdfOperators(element: SvgElement, options?: SvgRenderOptions): string; /** * Draw an SVG string onto a PDF page. * * Parses the SVG, converts it to PDF operators, and appends them * to the page's content stream. */ declare function drawSvgOnPage(page: PdfPage, svgString: string, options?: SvgRenderOptions): void; //#endregion //#region src/layers/optionalContent.d.ts /** * Represents a single optional content group (layer) in a PDF. * * Each layer has a name and a default visibility state. Content * can be associated with a layer using the `BDC`/`EMC` marked-content * operators in the content stream. */ declare class PdfLayer { readonly name: string; private visible; private ref; constructor(name: string, visible?: boolean); /** Check whether this layer is visible by default. */ isVisible(): boolean; /** Set the default visibility of this layer. */ setVisible(visible: boolean): void; /** Get the layer name. */ getName(): string; /** * Get the indirect reference for this layer's OCG dictionary. * Only available after `toDict()` has been called. */ getRef(): PdfRef | undefined; /** * Serialize this layer as an OCG dictionary and register it in the * object registry. * * @param registry The PDF object registry. * @returns The indirect reference to the OCG dictionary. */ toDict(registry: PdfObjectRegistry): PdfRef; /** * Parse a PdfLayer from an OCG dictionary. * * @param dict The OCG dictionary. * @returns A PdfLayer instance. */ static fromDict(dict: PdfDict): PdfLayer; } /** * Manages a collection of optional content groups (layers) for a PDF * document. * * Provides methods to add, remove, and query layers, and to serialize * the `/OCProperties` dictionary that goes into the catalog. */ declare class PdfLayerManager { private layers; /** * Add a new layer. * * @param name The display name for the layer. * @param visible Whether the layer is visible by default. * @returns The newly created layer. */ addLayer(name: string, visible?: boolean): PdfLayer; /** * Get a layer by name. * * @param name The layer name. * @returns The layer, or `undefined` if not found. */ getLayer(name: string): PdfLayer | undefined; /** * Get all layers. * * @returns A copy of the layers array. */ getLayers(): PdfLayer[]; /** * Remove a layer by name. * * @param name The layer name. */ removeLayer(name: string): void; /** * Build the `/OCProperties` dictionary for the document catalog. * * This dictionary describes all optional content groups and their * default configurations. * * @param registry The PDF object registry. * @returns The `/OCProperties` dictionary (not indirect). */ toOCProperties(registry: PdfObjectRegistry): PdfDict; /** * Parse a PdfLayerManager from an `/OCProperties` dictionary. * * @param dict The `/OCProperties` dictionary from the catalog. * @param resolver A function that resolves indirect references. * @returns A PdfLayerManager instance. */ static fromDict(dict: PdfDict, resolver: (ref: PdfRef) => PdfObject): PdfLayerManager; } /** * Generate the PDF operator to begin optional content for a layer. * * This produces a `BDC` (begin marked-content with properties) * operator that activates the given layer. * * @param layer The layer to activate. * @returns The PDF operator string: `/OC /LayerName BDC\n` */ declare function beginLayerContent(layer: PdfLayer): string; /** * Generate the PDF operator to end optional content. * * @returns The PDF operator string: `EMC\n` */ declare function endLayerContent(): string; //#endregion //#region src/core/redaction.d.ts /** Horizontal alignment for overlay text. */ type OverlayAlignment = "left" | "center" | "right"; /** Options for marking a region for redaction. */ interface RedactionOptions { /** The rectangle to redact: [x, y, width, height]. */ rect: [number, number, number, number]; /** Optional text to overlay on the redacted area. */ overlayText?: string | undefined; /** Colour for the redaction rectangle (default: black). */ color?: { r: number; g: number; b: number; } | undefined; /** Custom font name for overlay text (default: 'Helvetica'). */ overlayFont?: string | undefined; /** Custom font size for overlay text. When omitted, auto-calculated from rect height. */ overlayFontSize?: number | undefined; /** Horizontal alignment for overlay text (default: 'left'). */ overlayAlignment?: OverlayAlignment | undefined; /** Border width for the redaction rectangle outline (default: 0 — no border). */ borderWidth?: number | undefined; /** Border colour (default: same as fill colour). */ borderColor?: { r: number; g: number; b: number; } | undefined; /** Opacity for the redaction overlay, 0–1 (default: 1 — fully opaque). Useful for preview/draft mode. */ opacity?: number | undefined; } /** Redaction mark stored on a page. */ interface RedactionMark { rect: [number, number, number, number]; overlayText?: string | undefined; color: { r: number; g: number; b: number; }; overlayFont: string; overlayFontSize?: number | undefined; overlayAlignment: OverlayAlignment; borderWidth: number; borderColor: { r: number; g: number; b: number; }; opacity: number; } /** * Mark a rectangular region on a page for redaction. * * This does not immediately modify the page. Call * {@link applyRedactions} to draw the redaction rectangles. * * @param page The page to mark. * @param options The redaction options. */ declare function markForRedaction(page: PdfPage, options: RedactionOptions): void; /** * Apply all pending redactions across all pages in a document. * * For each redaction mark, this draws an opaque filled rectangle * over the marked region. If overlay text is specified, it is * drawn on top of the rectangle in a contrasting colour. * * @param doc The PDF document. */ declare function applyRedactions(doc: PdfDocument): void; /** * Get the pending redaction marks for a page. * * @param page The page to query. * @returns An array of redaction marks, or an empty array. */ declare function getRedactionMarks(page: PdfPage): readonly RedactionMark[]; //#endregion //#region src/core/pdfEmbed.d.ts /** * Handle for a page that has been embedded as a Form XObject. * * Returned by `PdfDocument.embedPdf()` and `PdfDocument.embedPage()`. * Pass it to `PdfPage.drawPage()` to paint the embedded page. */ interface EmbeddedPdfPage { /** XObject resource name (e.g. `'XF1'`). */ readonly name: string; /** Indirect reference to the Form XObject in the target registry. */ readonly ref: PdfRef; /** Original page width in points. */ readonly width: number; /** Original page height in points. */ readonly height: number; /** * Return the dimensions after applying a uniform scale factor. * * @param factor Scale factor (e.g. `0.5` for half size). */ scale(factor: number): { width: number; height: number; }; /** * Compute dimensions that fit within the given maximum size while * preserving the original aspect ratio. * * @param maxW Maximum width. * @param maxH Maximum height. */ scaleToFit(maxW: number, maxH: number): { width: number; height: number; }; } /** * Options for {@link PdfPage.drawPage}. */ interface DrawPageOptions { /** X coordinate of the lower-left corner. */ x?: number | undefined; /** Y coordinate of the lower-left corner. */ y?: number | undefined; /** Rendered width (defaults to the embedded page's original width). */ width?: number | undefined; /** Rendered height (defaults to the embedded page's original height). */ height?: number | undefined; /** Rotation angle. */ rotate?: Angle | undefined; /** Opacity `[0, 1]`. */ opacity?: number | undefined; /** Blend mode for compositing. */ blendMode?: BlendMode | undefined; /** Horizontal skew angle. */ xSkew?: Angle | undefined; /** Vertical skew angle. */ ySkew?: Angle | undefined; } /** * Options for embedding a page as a Form XObject. */ interface EmbedPageOptions { /** * Clip the embedded page to a sub-region (bounding box). * Coordinates are in the source page's coordinate system. */ boundingBox?: { x: number; y: number; width: number; height: number; } | undefined; /** * Apply an affine transformation matrix to the Form XObject. * The six values correspond to `[a, b, c, d, tx, ty]` in the * standard 3x3 PDF transformation matrix. */ transformationMatrix?: [number, number, number, number, number, number] | undefined; } /** * Embed a single page as a Form XObject in the target registry. * * The page's content stream(s) are decoded and concatenated. The * page's resources are deep-cloned into the target registry. The * result is a PdfStream of Subtype /Form registered in the target. * * @param page The source PdfPage to embed. * @param sourceRegistry The source document's object registry. * @param targetRegistry The target document's object registry. * @param xObjectName The resource name to assign (e.g. `'XF1'`). * @returns An EmbeddedPdfPage handle. */ declare function embedPageAsFormXObject(page: PdfPage, sourceRegistry: PdfObjectRegistry, targetRegistry: PdfObjectRegistry, xObjectName: string, options?: EmbedPageOptions): EmbeddedPdfPage; //#endregion //#region src/core/patterns.d.ts /** * A colour stop in a gradient, specifying the position (0..1) and colour. */ interface ColorStop { readonly offset: number; readonly color: Color; } /** * Options for creating a linear gradient (axial shading, ShadingType 2). */ interface LinearGradientOptions { /** Start X coordinate. */ readonly x1: number; /** Start Y coordinate. */ readonly y1: number; /** End X coordinate. */ readonly x2: number; /** End Y coordinate. */ readonly y2: number; /** * Colour stops. Each element is either a bare {@link Color} (positions * are distributed evenly) or a {@link ColorStop} with an explicit offset. */ readonly stops: readonly (Color | ColorStop)[]; /** * Whether to extend the gradient beyond the start and end points. * Default: `true`. */ readonly extend?: boolean; } /** * Options for creating a radial gradient (radial shading, ShadingType 3). */ interface RadialGradientOptions { /** Centre X of the start circle. */ readonly x0: number; /** Centre Y of the start circle. */ readonly y0: number; /** Radius of the start circle. */ readonly r0: number; /** Centre X of the end circle. */ readonly x1: number; /** Centre Y of the end circle. */ readonly y1: number; /** Radius of the end circle. */ readonly r1: number; /** * Colour stops (same semantics as {@link LinearGradientOptions.stops}). */ readonly stops: readonly (Color | ColorStop)[]; /** * Whether to extend the gradient beyond the start and end circles. * Default: `true`. */ readonly extend?: boolean; } /** * Options for creating a tiling pattern (PatternType 1). */ interface TilingPatternOptions { /** Width of one tile in user-space units. */ readonly width: number; /** Height of one tile in user-space units. */ readonly height: number; /** * Paint type. * - `1` (default) — coloured: the pattern's content stream specifies * its own colours. * - `2` — uncoloured: colours are supplied when the pattern is painted. */ readonly paintType?: 1 | 2; /** * Tiling type. * - `1` (default) — constant spacing. * - `2` — no distortion. * - `3` — constant spacing and faster tiling. */ readonly tilingType?: 1 | 2 | 3; /** Raw PDF content-stream operators that paint one tile. */ readonly ops: string; } /** * Descriptor for a gradient fill (linear or radial). * This is a lightweight value object — actual PDF objects are created * when {@link buildGradientObjects} is called. */ interface GradientFill { readonly kind: "gradient"; readonly shadingType: 2 | 3; readonly coords: readonly number[]; readonly normalizedStops: readonly NormalizedStop[]; readonly extend: boolean; } /** * Descriptor for a radial gradient fill. * Structurally identical to {@link GradientFill} but with `shadingType: 3`. */ type RadialGradientFill = GradientFill & { readonly shadingType: 3; }; /** * Descriptor for a tiling pattern fill. * This is a lightweight value object — actual PDF objects are created * when {@link buildPatternObjects} is called. */ interface PatternFill { readonly kind: "pattern"; readonly width: number; readonly height: number; readonly paintType: 1 | 2; readonly tilingType: 1 | 2 | 3; readonly ops: string; } /** A normalised colour stop with explicit offset and RGB values. */ interface NormalizedStop { readonly offset: number; readonly r: number; readonly g: number; readonly b: number; } /** * Create a linear (axial) gradient descriptor. * * The gradient runs from `(x1, y1)` to `(x2, y2)` through the given * colour stops. By default the gradient extends beyond its endpoints. * * @param options Gradient parameters. * @returns A {@link GradientFill} descriptor. */ declare function linearGradient(options: LinearGradientOptions): GradientFill; /** * Create a radial gradient descriptor. * * The gradient interpolates between two circles: the start circle at * `(x0, y0)` with radius `r0` and the end circle at `(x1, y1)` with * radius `r1`. * * @param options Gradient parameters. * @returns A {@link GradientFill} descriptor (with `shadingType: 3`). */ declare function radialGradient(options: RadialGradientOptions): GradientFill; /** * Create a tiling pattern descriptor. * * @param options Pattern parameters including the tile content stream. * @returns A {@link PatternFill} descriptor. */ declare function tilingPattern(options: TilingPatternOptions): PatternFill; /** * Materialise a {@link GradientFill} descriptor into actual PDF objects * in the given registry. * * @param gradient The gradient descriptor. * @param registry The document's object registry. * @returns An object with the pattern's indirect reference and a unique * resource name. */ declare function buildGradientObjects(gradient: GradientFill, registry: PdfObjectRegistry): { patternRef: PdfRef; patternName: string; }; /** * Materialise a {@link PatternFill} descriptor into actual PDF objects * in the given registry. * * @param pattern The tiling pattern descriptor. * @param registry The document's object registry. * @returns An object with the pattern's indirect reference and a unique * resource name. */ declare function buildPatternObjects(pattern: PatternFill, registry: PdfObjectRegistry): { patternRef: PdfRef; patternName: string; }; //#endregion //#region src/barcode/qr.d.ts /** Error correction level. */ type ErrorCorrectionLevel = "L" | "M" | "Q" | "H"; /** Options for rendering a QR code to PDF operators. */ interface QrCodeOptions { /** Error correction level. Default: `'M'`. */ readonly errorCorrection?: ErrorCorrectionLevel; /** Size of each module in PDF points. Default: `2`. */ readonly moduleSize?: number; /** Number of quiet-zone modules around the code. Default: `4`. */ readonly quietZone?: number; /** Foreground (dark module) colour. Default: black. */ readonly color?: Color; /** Background colour. Default: white. */ readonly backgroundColor?: Color; } /** The result of QR code encoding — a boolean matrix. */ interface QrCodeMatrix { /** Number of modules per side. */ readonly size: number; /** Row-major boolean array. `true` = dark module. */ readonly modules: readonly boolean[]; /** QR version (1-40). */ readonly version: number; } /** * Encode a string as a QR code matrix. * * @param data The string to encode. * @param errorCorrection Error correction level (default: `'M'`). * @returns A {@link QrCodeMatrix} with the encoded data. */ declare function encodeQrCode(data: string, errorCorrection?: ErrorCorrectionLevel): QrCodeMatrix; /** * Convert a {@link QrCodeMatrix} to PDF content-stream operators. * * The QR code is rendered as filled rectangles (one per dark module), * positioned at `(x, y)` in PDF user-space coordinates. The `y` * coordinate refers to the **bottom-left** corner of the QR code. * * @param matrix The QR code matrix from {@link encodeQrCode}. * @param x X position in PDF points. * @param y Y position in PDF points. * @param options Rendering options (module size, quiet zone, colours). * @returns A string of PDF content-stream operators. */ declare function qrCodeToOperators(matrix: QrCodeMatrix, x: number, y: number, options?: QrCodeOptions): string; //#endregion //#region src/layout/table.d.ts /** A styled text run within a cell -- allows inline style variation. */ interface TextRun { readonly text: string; readonly fontSize?: number; readonly color?: Color; readonly fontName?: string; } /** Content that can appear in a cell: plain text, styled text runs, or a nested table. */ type CellContent = string | TextRun[] | NestedTableContent; /** A nested table definition used as cell content. */ interface NestedTableContent { readonly type: "table"; readonly table: Omit; } /** Single table cell. */ interface TableCell { readonly content: CellContent; readonly colSpan?: number; readonly rowSpan?: number; readonly backgroundColor?: Color; readonly textColor?: Color; readonly fontSize?: number; readonly align?: "left" | "center" | "right"; readonly verticalAlign?: "top" | "middle" | "bottom"; readonly padding?: number | { top?: number; right?: number; bottom?: number; left?: number; }; /** Text overflow mode. Default: 'truncate'. */ readonly overflow?: "wrap" | "truncate" | "ellipsis" | "shrink"; } /** Table row. */ interface TableRow { readonly cells: readonly (TableCell | string)[]; readonly height?: number; readonly backgroundColor?: Color; } /** Column definition. */ interface TableColumn { /** Fixed width in points. */ readonly width?: number; /** Percentage of table width (e.g., '30%'). */ readonly percentage?: string; /** Flex weight (like CSS flex-grow). Default: 1 when no width/percentage. */ readonly flex?: number; /** Auto-fit: measure content and use minimum needed width. */ readonly autoFit?: boolean; readonly minWidth?: number; readonly maxWidth?: number; readonly align?: "left" | "center" | "right"; } /** Full table configuration. */ interface DrawTableOptions { readonly x: number; readonly y: number; readonly width: number; readonly rows: readonly TableRow[]; readonly columns?: readonly TableColumn[]; /** PDF font resource name, default 'Helvetica'. */ readonly fontName?: string; /** Default font size in points, default 12. */ readonly fontSize?: number; readonly textColor?: Color; readonly borderColor?: Color; /** Border line width in points, default 0.5. */ readonly borderWidth?: number; /** Number of header rows (reserved for future page-break support). */ readonly headerRows?: number; /** Default cell padding in points, default 4. */ readonly padding?: number; /** Alternating row background colors [even, odd]. */ readonly alternateRowColors?: readonly [Color, Color]; /** Header background color (overrides alternateRowColors for header rows). */ readonly headerBackgroundColor?: Color; /** Header text color. */ readonly headerTextColor?: Color; } /** Result of table rendering. */ interface TableRenderResult { readonly width: number; readonly height: number; readonly rowHeights: readonly number[]; readonly columnWidths: readonly number[]; readonly pagesUsed: number; } /** Content for a single page in a multi-page table render. */ interface PageContent { readonly ops: string; readonly pageIndex: number; } /** Result of multi-page table rendering. */ interface MultiPageTableResult { readonly pages: readonly PageContent[]; readonly result: TableRenderResult; } declare function renderTable(options: DrawTableOptions): { ops: string; result: TableRenderResult; }; /** * Render a table across multiple pages, breaking rows when content * would exceed the available vertical space. * * Header rows (specified by `options.headerRows`) are repeated at the * top of each new page. Rows are never split across pages. */ declare function renderMultiPageTable(options: DrawTableOptions, bottomMargin?: number): MultiPageTableResult; //#endregion //#region src/core/pdfPage.d.ts /** Pre-defined page sizes as `[width, height]` tuples in PDF points. */ declare const PageSizes: { readonly "4A0": readonly [4767.87, 6740.79]; readonly "2A0": readonly [3370.39, 4767.87]; readonly A0: readonly [2383.94, 3370.39]; readonly A1: readonly [1683.78, 2383.94]; readonly A2: readonly [1190.55, 1683.78]; readonly A3: readonly [841.89, 1190.55]; readonly A4: readonly [595.28, 841.89]; readonly A5: readonly [419.53, 595.28]; readonly A6: readonly [297.64, 419.53]; readonly A7: readonly [209.76, 297.64]; readonly A8: readonly [147.40, 209.76]; readonly A9: readonly [104.88, 147.40]; readonly A10: readonly [73.70, 104.88]; readonly B0: readonly [2834.65, 4008.19]; readonly B1: readonly [2004.09, 2834.65]; readonly B2: readonly [1417.32, 2004.09]; readonly B3: readonly [1000.63, 1417.32]; readonly B4: readonly [708.66, 1000.63]; readonly B5: readonly [498.90, 708.66]; readonly B6: readonly [354.33, 498.90]; readonly B7: readonly [249.45, 354.33]; readonly B8: readonly [175.75, 249.45]; readonly B9: readonly [124.72, 175.75]; readonly B10: readonly [87.87, 124.72]; readonly Letter: readonly [612, 792]; readonly Legal: readonly [612, 1008]; readonly Tabloid: readonly [792, 1224]; readonly Ledger: readonly [1224, 792]; readonly Executive: readonly [521.86, 756]; readonly Folio: readonly [612, 936]; readonly C0: readonly [2599.37, 3676.54]; readonly C1: readonly [1836.85, 2599.37]; readonly C2: readonly [1298.27, 1836.85]; readonly C3: readonly [918.43, 1298.27]; readonly C4: readonly [649.13, 918.43]; readonly C5: readonly [459.21, 649.13]; readonly C6: readonly [323.15, 459.21]; readonly C7: readonly [229.61, 323.15]; readonly C8: readonly [161.57, 229.61]; readonly C9: readonly [113.39, 161.57]; readonly C10: readonly [79.37, 113.39]; readonly RA0: readonly [2437.80, 3458.27]; readonly RA1: readonly [1729.13, 2437.80]; readonly RA2: readonly [1218.90, 1729.13]; readonly RA3: readonly [864.57, 1218.90]; readonly RA4: readonly [609.45, 864.57]; readonly SRA0: readonly [2551.18, 3628.35]; readonly SRA1: readonly [1814.17, 2551.18]; readonly SRA2: readonly [1275.59, 1814.17]; readonly SRA3: readonly [907.09, 1275.59]; readonly SRA4: readonly [637.80, 907.09]; }; /** Type for a page-size input: a `[width, height]` tuple or `{ width, height }` object. */ type PageSize = readonly [width: number, height: number] | { readonly width: number; readonly height: number; }; /** Options for {@link PdfPage.drawText}. */ interface DrawTextOptions { /** X coordinate. */ x?: number | undefined; /** Y coordinate. */ y?: number | undefined; /** * Font to use for rendering. * * Accepts either a {@link FontRef} object (returned by `doc.embedFont()`) * or a font resource name string (e.g. `'F1'`). * * When a `FontRef` is provided, its `name` property is used as the * resource name and its CID encoder (if any) is used automatically. */ font?: FontRef | string | undefined; /** Font size in points. */ size?: number | undefined; /** Text colour. Defaults to black. */ color?: Color | undefined; /** Rotation angle. */ rotate?: Angle | undefined; /** Line height for multi-line text. */ lineHeight?: number | undefined; /** Opacity `[0, 1]`. */ opacity?: number | undefined; /** Blend mode for compositing. */ blendMode?: BlendMode | undefined; /** Text rendering mode (fill, stroke, invisible, clip, etc.). */ renderingMode?: TextRenderingMode | undefined; /** Horizontal skew angle (italic-like effect). */ xSkew?: Angle | undefined; /** Vertical skew angle. */ ySkew?: Angle | undefined; /** * Maximum width in points before text is automatically wrapped. * * When provided with a {@link FontRef} font (which has `widthOfTextAtSize`), * the text is broken at word boundaries to fit within this width. * If a single word exceeds `maxWidth`, it is broken at character level. * * When the font is a plain string (no measurement available), this * option is ignored. */ maxWidth?: number | undefined; /** * Characters at which text may be broken when wrapping. * * Defaults to `[' ']` (space only). Pass additional characters such as * `[' ', '-', '/']` to allow breaks at hyphens, slashes, etc. * * The break character is kept at the **end** of the preceding line * (e.g. `'hello-'` / `'world'`), except for space which is consumed * as in the default behaviour. */ wordBreaks?: string[] | undefined; } /** Options for {@link PdfPage.drawImage}. */ interface DrawImageOptions { /** X coordinate of the lower-left corner. */ x?: number | undefined; /** Y coordinate of the lower-left corner. */ y?: number | undefined; /** Rendered width. */ width?: number | undefined; /** Rendered height. */ height?: number | undefined; /** Rotation angle. */ rotate?: Angle | undefined; /** Opacity `[0, 1]`. */ opacity?: number | undefined; /** Blend mode for compositing. */ blendMode?: BlendMode | undefined; /** Horizontal skew angle. */ xSkew?: Angle | undefined; /** Vertical skew angle. */ ySkew?: Angle | undefined; } /** Options for {@link PdfPage.drawRectangle}. */ interface DrawRectangleOptions { /** X coordinate. */ x?: number | undefined; /** Y coordinate. */ y?: number | undefined; /** Rectangle width. */ width?: number | undefined; /** Rectangle height. */ height?: number | undefined; /** Fill colour. Set to `undefined` for no fill. */ color?: Color | undefined; /** Border (stroke) colour. Set to `undefined` for no stroke. */ borderColor?: Color | undefined; /** Border width in points. */ borderWidth?: number | undefined; /** Rotation angle. */ rotate?: Angle | undefined; /** Opacity `[0, 1]`. */ opacity?: number | undefined; /** Blend mode for compositing. */ blendMode?: BlendMode | undefined; /** Horizontal skew angle. */ xSkew?: Angle | undefined; /** Vertical skew angle. */ ySkew?: Angle | undefined; /** Dash pattern for border `[dashLen, gapLen, ...]`. */ borderDashArray?: number[] | undefined; /** Dash phase offset for border. */ borderDashPhase?: number | undefined; /** Line cap style for border (0 = butt, 1 = round, 2 = projecting square). */ borderLineCap?: 0 | 1 | 2 | undefined; /** Border stroke opacity `[0, 1]`, separate from fill opacity. */ borderOpacity?: number | undefined; } /** Options for {@link PdfPage.drawLine}. */ interface DrawLineOptions { /** Start point. */ start: Point; /** End point. */ end: Point; /** Line colour. */ color?: Color | undefined; /** Line width. */ thickness?: number | undefined; /** Dash pattern `[dashLength, gapLength]`. */ dashArray?: number[] | undefined; /** Dash phase. */ dashPhase?: number | undefined; /** Opacity `[0, 1]`. */ opacity?: number | undefined; /** Blend mode for compositing. */ blendMode?: BlendMode | undefined; } /** Options for {@link PdfPage.drawCircle}. */ interface DrawCircleOptions { /** Centre x. */ x?: number | undefined; /** Centre y. */ y?: number | undefined; /** Radius of the circle. */ radius?: number | undefined; /** * Radius of the circle. * @deprecated Use `radius` instead. */ size?: number | undefined; /** Fill colour. */ color?: Color | undefined; /** Border colour. */ borderColor?: Color | undefined; /** Border width. */ borderWidth?: number | undefined; /** Opacity. */ opacity?: number | undefined; /** Blend mode for compositing. */ blendMode?: BlendMode | undefined; /** Dash pattern for border. */ borderDashArray?: number[] | undefined; /** Dash phase offset for border. */ borderDashPhase?: number | undefined; /** Line cap style for border. */ borderLineCap?: 0 | 1 | 2 | undefined; /** Border stroke opacity `[0, 1]`. */ borderOpacity?: number | undefined; } /** Options for {@link PdfPage.drawEllipse}. */ interface DrawEllipseOptions { /** Centre x. */ x?: number | undefined; /** Centre y. */ y?: number | undefined; /** Horizontal radius. */ xScale?: number | undefined; /** Vertical radius. */ yScale?: number | undefined; /** Fill colour. */ color?: Color | undefined; /** Border colour. */ borderColor?: Color | undefined; /** Border width. */ borderWidth?: number | undefined; /** Opacity `[0, 1]`. */ opacity?: number | undefined; /** Blend mode for compositing. */ blendMode?: BlendMode | undefined; /** Dash pattern for border. */ borderDashArray?: number[] | undefined; /** Dash phase offset for border. */ borderDashPhase?: number | undefined; /** Line cap style for border. */ borderLineCap?: 0 | 1 | 2 | undefined; /** Border stroke opacity `[0, 1]`. */ borderOpacity?: number | undefined; } /** Options for {@link PdfPage.drawSvgPath}. */ interface DrawSvgPathOptions { /** X translation (PDF coordinates). */ x?: number | undefined; /** Y translation (PDF coordinates). */ y?: number | undefined; /** Uniform scale factor applied to the path. */ scale?: number | undefined; /** Fill colour. */ color?: Color | undefined; /** Border (stroke) colour. */ borderColor?: Color | undefined; /** Border width in points. */ borderWidth?: number | undefined; /** Opacity `[0, 1]`. */ opacity?: number | undefined; /** Blend mode for compositing. */ blendMode?: BlendMode | undefined; /** Dash pattern for border. */ borderDashArray?: number[] | undefined; /** Dash phase offset for border. */ borderDashPhase?: number | undefined; /** Line cap style for border. */ borderLineCap?: 0 | 1 | 2 | undefined; /** Border stroke opacity `[0, 1]`. */ borderOpacity?: number | undefined; } /** Options for {@link PdfPage.drawQrCode}. */ interface DrawQrCodeOptions { /** X coordinate (bottom-left of QR code). */ x?: number | undefined; /** Y coordinate (bottom-left of QR code). */ y?: number | undefined; /** Error correction level. Default: `'M'`. */ errorCorrection?: ErrorCorrectionLevel | undefined; /** Size of each module in PDF points. Default: `2`. */ moduleSize?: number | undefined; /** Number of quiet-zone modules around the code. Default: `4`. */ quietZone?: number | undefined; /** Foreground (dark module) colour. Default: black. */ color?: Color | undefined; /** Background colour. Default: white. */ backgroundColor?: Color | undefined; } /** Options for {@link PdfPage.drawSquare}. */ interface DrawSquareOptions { /** X coordinate. */ x?: number | undefined; /** Y coordinate. */ y?: number | undefined; /** Side length of the square. Defaults to `100`. */ size?: number | undefined; /** Fill colour. */ color?: Color | undefined; /** Border (stroke) colour. */ borderColor?: Color | undefined; /** Border width in points. */ borderWidth?: number | undefined; /** Rotation angle. */ rotate?: Angle | undefined; /** Opacity `[0, 1]`. */ opacity?: number | undefined; /** Blend mode for compositing. */ blendMode?: BlendMode | undefined; /** Horizontal skew angle. */ xSkew?: Angle | undefined; /** Vertical skew angle. */ ySkew?: Angle | undefined; /** Dash pattern for border. */ borderDashArray?: number[] | undefined; /** Dash phase offset for border. */ borderDashPhase?: number | undefined; /** Line cap style for border. */ borderLineCap?: 0 | 1 | 2 | undefined; /** Border stroke opacity `[0, 1]`. */ borderOpacity?: number | undefined; } /** * A 2D point in PDF coordinate space. * * Used by drawing options that accept coordinate pairs (e.g. * {@link DrawLineOptions}). */ interface Point { /** X coordinate in PDF points. */ readonly x: number; /** Y coordinate in PDF points. */ readonly y: number; } /** Opaque handle for a font that has been embedded in the document. */ interface FontRef { /** Resource name used in content-stream operators (e.g. `F1`). */ readonly name: string; /** Indirect reference to the font dictionary. */ readonly ref: PdfRef; /** * Compute the width of a text string at the given font size (in points). * Available for both standard and TrueType fonts. * * @param text The text string to measure. * @param size Font size in points. * @returns Width of the text in points. */ widthOfTextAtSize(text: string, size: number): number; /** * Compute the height of the font at the given size (ascender - descender). * Available for both standard and TrueType fonts. * * @param size Font size in points. * @returns Height in points. */ heightAtSize(size: number): number; /** * Compute the font size needed to achieve a given height (ascender - descender). * This is the inverse of `heightAtSize()`. * * @param height Desired height in points. * @returns Font size in points. */ sizeAtHeight(height: number): number; /** * Return the set of Unicode codepoints supported by this font. * * For standard fonts, returns the WinAnsi character set. * For embedded fonts, returns all codepoints in the cmap table. * * @returns Array of Unicode codepoint numbers. */ getCharacterSet(): number[]; } /** Opaque handle for an image that has been embedded in the document. */ interface ImageRef { /** Resource name used in content-stream operators (e.g. `Im1`). */ readonly name: string; /** Indirect reference to the image XObject. */ readonly ref: PdfRef; /** Intrinsic width in pixels. */ readonly width: number; /** Intrinsic height in pixels. */ readonly height: number; /** * Return a new `{ width, height }` scaled by the given factor. * * @param factor Scale multiplier (e.g. `0.5` for half size). */ scale(factor: number): { width: number; height: number; }; /** * Return a new `{ width, height }` that fits within the given bounds * while preserving the aspect ratio. * * @param maxWidth Maximum allowed width. * @param maxHeight Maximum allowed height. */ scaleToFit(maxWidth: number, maxHeight: number): { width: number; height: number; }; } /** * Options for transparency groups. * * Transparency groups allow a set of drawing operations to be composited * as a single unit before being blended with the page content. */ interface TransparencyGroupOptions { /** * When `true`, the group is composited against a fully transparent * backdrop rather than the existing page content. Default: `true`. */ isolated?: boolean | undefined; /** * When `true`, earlier objects in the group are knocked out (replaced) * by later objects, rather than composited on top. Default: `false`. */ knockout?: boolean | undefined; /** * Color space for the transparency group. Default: `'DeviceRGB'`. */ colorSpace?: "DeviceRGB" | "DeviceCMYK" | "DeviceGray" | undefined; } /** * Builder interface for constructing soft mask content. * * All drawing is in grayscale: `1` = fully opaque, `0` = fully transparent. */ interface SoftMaskBuilder { /** * Draw a filled rectangle at the given position with the specified * grayscale value (`0` = black/transparent, `1` = white/opaque). */ drawRectangle(x: number, y: number, width: number, height: number, gray: number): void; /** * Draw a filled circle at the given center with the specified radius * and grayscale value. */ drawCircle(cx: number, cy: number, radius: number, gray: number): void; /** * Append raw PDF content-stream operators to the mask. */ pushRawOperators(ops: string): void; } /** * Opaque reference to a soft mask Form XObject. * * Created by {@link PdfDocument.createSoftMask} and consumed by * {@link PdfPage.applySoftMask}. */ interface SoftMaskRef { readonly _tag: "softMask"; readonly ref: PdfRef; } /** * A single page in a PDF document. * * Drawing methods are synchronous and append PDF operators to an * internal string buffer. The buffer is converted to a content stream * when the document is saved. */ declare class PdfPage { /** Object registry for allocating refs. */ private readonly registry; /** Content-stream operators accumulated so far. */ private ops; /** Fonts referenced by this page — maps resource name → PdfRef. */ private readonly fonts; /** * CID font text encoders — maps resource name → encode function. * Only present for TrueType (CIDFont Type 2) fonts. * @internal */ private readonly cidFontEncoders; /** XObjects (images) referenced by this page. */ private readonly xObjects; /** * ExtGState dictionaries referenced by this page. * Maps a resource name (e.g. `GS1`) to its indirect reference. * Used for opacity and other graphics state parameters. */ private readonly extGStates; /** * Pattern resources referenced by this page. * Maps a resource name (e.g. `Pat5`) to its indirect reference. * Used for gradient fills and tiling patterns. */ private readonly patterns; /** * Counter for ExtGState resource names (`GS1`, `GS2`, ...). */ private extGStateCounter; /** * Counter for transparency group XObject resource names (`TG1`, `TG2`, ...). */ private transparencyGroupCounter; /** * Stack of transparency group state. Each entry records the ops length * at the time `beginTransparencyGroup()` was called, plus the options. */ private readonly transparencyGroupStack; /** * Cache mapping composite keys (opacity + blend mode) to their ExtGState * resource names, so the same combination reuses the same graphics state * dictionary. */ private readonly extGStateCache; /** Default font used by `drawText()` when no `font` option is provided. */ private _defaultFont?; /** Default font size used by `drawText()` when no `size` option is provided. */ private _defaultFontSize?; /** Default font colour used by `drawText()` when no `color` option is provided. */ private _defaultFontColor?; /** Default line height used by `drawText()` when no `lineHeight` option is provided. */ private _defaultLineHeight?; /** Current cursor X coordinate (used as fallback when x is not specified). */ private _cursorX; /** Current cursor Y coordinate (used as fallback when y is not specified). */ private _cursorY; /** Pre-allocated indirect reference for this page's /Page dictionary. */ readonly pageRef: PdfRef; /** Pre-allocated indirect reference for this page's content stream. */ readonly contentStreamRef: PdfRef; /** * Page rotation in degrees (0, 90, 180, or 270). * This is written to the /Rotate entry in the page dictionary at save time. * @internal */ private rotation; /** * Tab order for the page. * - `'S'` — Structure order (follows the logical structure tree) * - `'R'` — Row order * - `'C'` — Column order * * Written to the /Tabs entry in the page dictionary at save time. * PDF/UA requires `'S'` (structure order). * @internal */ private tabOrder; /** * Optional crop box `[llx, lly, urx, ury]`. * When set, written to the /CropBox entry in the page dictionary at save time. * @internal */ private cropBox; /** * Optional bleed box `[llx, lly, urx, ury]`. * When set, written to the /BleedBox entry in the page dictionary at save time. * @internal */ private bleedBox; /** * Optional art box `[llx, lly, urx, ury]`. * When set, written to the /ArtBox entry in the page dictionary at save time. * @internal */ private artBox; /** * Optional trim box `[llx, lly, urx, ury]`. * When set, written to the /TrimBox entry in the page dictionary at save time. * @internal */ private trimBox; /** * Mutable media box origin and dimensions. Initially set from constructor. * @internal */ private mediaX; /** @internal */ private mediaY; /** @internal */ private mediaWidth; /** @internal */ private mediaHeight; /** Original page width from construction time (used by resetSize). */ private readonly _originalWidth; /** Original page height from construction time (used by resetSize). */ private readonly _originalHeight; /** * @internal Original content stream refs from a loaded PDF. * These are indirect references to PdfStream objects already in the registry. */ private _originalContentRefs; /** * @internal Original resources dictionary from a loaded PDF. * Merged with new resources in `buildResources()`. */ private _originalResources; /** * @internal Original annotation refs from a loaded PDF. * Combined with new annotations in `finalize()`. */ private _originalAnnotRefs; constructor(w: number, h: number, registry: PdfObjectRegistry); /** * @internal Create a PdfPage pre-loaded with content from a parsed PDF. * * Unlike the normal constructor which creates a blank page, this factory * preserves the original content streams, resources, annotations, and * other page attributes from the parsed PDF. */ static _fromParsed(width: number, height: number, registry: PdfObjectRegistry, opts: { contentRefs?: PdfRef[] | undefined; resources?: PdfDict | undefined; rotation?: number | undefined; cropBox?: [number, number, number, number] | undefined; bleedBox?: [number, number, number, number] | undefined; artBox?: [number, number, number, number] | undefined; trimBox?: [number, number, number, number] | undefined; annotRefs?: PdfRef[] | undefined; }): PdfPage; /** Page width in points. */ get width(): number; /** Page height in points. */ get height(): number; /** @internal Register a font resource on this page. */ registerFont(name: string, ref: PdfRef): void; /** * @internal Register a CID font encoder for a font resource on this page. * When drawText is called with this font, text will be encoded using the * provided encoder function (producing hex glyph IDs) instead of literal strings. */ registerCIDFont(name: string, encoder: (text: string) => string): void; /** @internal Register an image XObject resource on this page. */ registerXObject(name: string, ref: PdfRef): void; /** @internal Register an ExtGState resource on this page. */ registerExtGState(name: string, ref: PdfRef): void; /** @internal Register a Pattern resource on this page. */ registerPattern(name: string, ref: PdfRef): void; /** * Set the default font used by {@link drawText} when the `font` option * is not provided. * * @param font A {@link FontRef} returned by `doc.embedFont()`. */ setFont(font: FontRef): void; /** * Set the default font size (in points) used by {@link drawText} when * the `size` option is not provided. * * @param size Font size in points. */ setFontSize(size: number): void; /** * Set the default font colour used by {@link drawText} when the `color` * option is not provided. * * @param color A {@link Color} value (e.g. from `rgb()`, `cmyk()`, etc.). */ setFontColor(color: Color): void; /** * Set the default line height used by {@link drawText} when the * `lineHeight` option is not provided. * * @param height Line height in points. */ setLineHeight(height: number): void; /** * Get the current cursor position. * * @returns An object with `x` and `y` properties (in points). */ getPosition(): { x: number; y: number; }; /** * Get the current cursor X coordinate. * * @returns The X coordinate in points. */ getX(): number; /** * Get the current cursor Y coordinate. * * @returns The Y coordinate in points. */ getY(): number; /** * Move the cursor to an absolute position. * * Drawing methods that accept optional `x` / `y` parameters will use the * cursor position as a fallback when those parameters are omitted. * * @param x The X coordinate in points. * @param y The Y coordinate in points. */ moveTo(x: number, y: number): void; /** * Move the cursor upward by the given amount (increases Y). * * @param amount Distance in points. */ moveUp(amount: number): void; /** * Move the cursor downward by the given amount (decreases Y). * * @param amount Distance in points. */ moveDown(amount: number): void; /** * Move the cursor to the right by the given amount (increases X). * * @param amount Distance in points. */ moveRight(amount: number): void; /** * Move the cursor to the left by the given amount (decreases X). * * @param amount Distance in points. */ moveLeft(amount: number): void; /** * Reset the cursor position to `(0, 0)`. */ resetPosition(): void; /** * Get or create an ExtGState resource for the given opacity and/or * blend mode. * * Creates a PDF ExtGState dictionary with `/ca` + `/CA` (when opacity * is less than 1) and `/BM` (when a non-Normal blend mode is specified). * The dictionary is registered in the object registry and cached so that * the same combination of parameters shares a single resource. * * @param opacity Opacity value in the range `[0, 1]` (optional). * @param blendMode A PDF blend mode name (optional). * @returns The resource name (e.g. `GS1`) to use in content stream operators. * @internal */ private getOrCreateExtGState; /** * Draw a text string at the specified position. * * @param text The text to render. * @param options Position, font, size, colour, rotation. */ drawText(text: string, options?: DrawTextOptions): void; /** * Draw an embedded image on this page. * * @param image Image reference returned by `doc.embedPng()` or * `doc.embedJpeg()`. * @param options Position, dimensions, rotation. */ drawImage(image: ImageRef, options?: DrawImageOptions): void; /** * Draw an embedded PDF page (Form XObject) on this page. * * The embedded page is painted at the given position and scaled to the * specified dimensions. If `width` or `height` is omitted, the * original page dimensions are used. * * @param embeddedPage An embedded page returned by `doc.embedPdf()` or * `doc.embedPage()`. * @param options Position, dimensions, rotation, opacity. * * @example * ```ts * const [embedded] = await doc.embedPdf(otherPdfBytes, [0]); * page.drawPage(embedded, { x: 50, y: 50, width: 300, height: 400 }); * ``` */ drawPage(embeddedPage: EmbeddedPdfPage, options?: DrawPageOptions): void; /** * Draw a rectangle. * * By default the rectangle is filled with black. Set `color` to * `undefined` and provide `borderColor` for stroke-only. */ drawRectangle(options?: DrawRectangleOptions): void; /** * Draw a square (convenience wrapper around {@link drawRectangle}). * * @param options Position, size, colours, rotation, opacity, blend mode. */ drawSquare(options?: DrawSquareOptions): void; /** * Draw a straight line. */ drawLine(options: DrawLineOptions): void; /** * Draw a circle. */ drawCircle(options?: DrawCircleOptions): void; /** * Draw an ellipse. */ drawEllipse(options?: DrawEllipseOptions): void; /** * Push the current graphics state onto the stack (`q`). * * Must be balanced with a matching {@link popGraphicsState} call. */ pushGraphicsState(): void; /** * Pop the most recently saved graphics state (`Q`). */ popGraphicsState(): void; /** * Concatenate an arbitrary transformation matrix with the CTM (`cm`). * * @param a Horizontal scaling / rotation. * @param b Rotation / skew. * @param c Rotation / skew. * @param d Vertical scaling / rotation. * @param tx Horizontal translation. * @param ty Vertical translation. */ setTransform(a: number, b: number, c: number, d: number, tx: number, ty: number): void; /** * Append raw PDF operator string(s) to the content stream. * * Use with caution — no validation is performed. */ pushOperators(operators: string): void; /** * Get the current page rotation in degrees. * @returns The rotation angle (0, 90, 180, or 270). */ getRotation(): number; /** * Set the page rotation in degrees. * * @param angle Must be 0, 90, 180, or 270. * @internal */ setRotation(angle: number): void; /** * Get the current tab order for this page. * * @returns `'S'` (structure), `'R'` (row), `'C'` (column), or * `undefined` if not set. */ getTabOrder(): "S" | "R" | "C" | undefined; /** * Set the tab order for this page. * * PDF/UA requires `'S'` (structure order) so that assistive technology * follows the logical structure tree. * * @param order `'S'` (structure), `'R'` (row), or `'C'` (column). */ setTabOrder(order: "S" | "R" | "C"): void; /** Get the page width in points. Alias for the `width` getter. */ getWidth(): number; /** Get the page height in points. Alias for the `height` getter. */ getHeight(): number; /** Set the page width in points. */ setWidth(w: number): void; /** Set the page height in points. */ setHeight(h: number): void; /** Set both page width and height in points. */ setSize(w: number, h: number): void; /** Get the page width and height as an object. */ getSize(): { width: number; height: number; }; /** Reset page dimensions to their original values from creation time. */ resetSize(): void; /** Translate all page content by (x, y) points. Prepends a cm operator. */ translateContent(x: number, y: number): void; /** Scale page content by the given factors. Prepends a cm operator. */ scaleContent(xFactor: number, yFactor: number): void; /** Scale annotation rectangles by the given factors. */ scaleAnnotations(xFactor: number, yFactor: number): void; /** Scale page dimensions, content, and annotations together. */ scale(xFactor: number, yFactor: number): void; /** Get the media box for this page. */ getMediaBox(): { x: number; y: number; width: number; height: number; }; /** Set the media box (page dimensions) for this page. */ setMediaBox(x: number, y: number, width: number, height: number): void; /** Get the crop box if set, or undefined. */ getCropBox(): { x: number; y: number; width: number; height: number; } | undefined; /** Set the crop box for this page. */ setCropBox(x: number, y: number, width: number, height: number): void; /** Get the bleed box if set, or undefined. */ getBleedBox(): { x: number; y: number; width: number; height: number; } | undefined; /** Set the bleed box for this page. */ setBleedBox(x: number, y: number, width: number, height: number): void; /** Get the trim box if set, or undefined. */ getTrimBox(): { x: number; y: number; width: number; height: number; } | undefined; /** Set the trim box for this page. */ setTrimBox(x: number, y: number, width: number, height: number): void; /** Get the art box if set, or undefined. */ getArtBox(): { x: number; y: number; width: number; height: number; } | undefined; /** Set the art box for this page. */ setArtBox(x: number, y: number, width: number, height: number): void; /** Remove the crop box from this page (it will default to the media box). */ removeCropBox(): void; /** Remove the bleed box from this page (it will default to the crop box). */ removeBleedBox(): void; /** Remove the trim box from this page (it will default to the crop box). */ removeTrimBox(): void; /** Remove the art box from this page (it will default to the crop box). */ removeArtBox(): void; /** * Validate that page boxes conform to the PDF specification nesting rules. * * PDF spec §14.11.2 requirements: * - MediaBox is required on every page. * - CropBox defaults to MediaBox. * - BleedBox, TrimBox, and ArtBox default to CropBox. * - All boxes must be within or equal to the MediaBox. * * @returns An object with `valid` (boolean) and `issues` (string array). */ validateBoxes(): { valid: boolean; issues: string[]; }; /** * Alt text entries for images, keyed by image resource name. * Used during structure tree serialization. * @internal */ private readonly imageAltTexts; /** * Wrap the current content-stream operators in a marked-content * sequence. * * This wraps ALL currently accumulated content in a BDC/EMC pair * with the given structure tag and marked-content ID (MCID). The * MCID links the content to a structure element in the document's * structure tree. * * Call this after adding content to the page and before adding * more content that belongs to a different structure element. * * @param tag The structure type tag (e.g. `"P"`, `"H1"`, `"Span"`). * @param mcid The marked-content ID assigned by the structure tree. */ markContent(tag: StructureType, mcid: number): void; /** * Begin a marked-content sequence in the content stream. * * Must be paired with a call to {@link endMarkedContentSequence}. * Content added between the two calls will be associated with the * given structure element. * * @param tag The structure type tag. * @param mcid The marked-content ID. */ beginMarkedContent(tag: StructureType, mcid: number): void; /** * End a marked-content sequence in the content stream. * * Must be preceded by a call to {@link beginMarkedContent}. */ endMarkedContentSequence(): void; /** * Associate alt text with an image reference on this page. * * The alt text is stored and used during structure tree serialization * to create a Figure structure element with the `/Alt` attribute. * * @param imageRef The image reference returned by `doc.embedPng()` * or `doc.embedJpeg()`. * @param altText The alternative text describing the image. */ addAltText(imageRef: ImageRef, altText: string): void; /** * Get the alt text for an image, if set. * * @param imageRef The image reference. * @returns The alt text, or `undefined`. */ getAltText(imageRef: ImageRef): string | undefined; /** * Annotations on this page. * @internal */ private readonly annotations; /** Raw widget annotation dicts added via addWidgetAnnotation. */ private readonly widgetDicts; /** * Get all annotations on this page. * * @returns An array of PdfAnnotation instances. */ getAnnotations(): PdfAnnotation[]; /** * Add an annotation to this page. * * @param type The annotation subtype. * @param options Annotation options (rect, contents, color, etc.). * @returns The created PdfAnnotation. */ addAnnotation(type: AnnotationType, options: AnnotationOptions): PdfAnnotation; /** * Add a pre-created annotation to this page. * * @param annotation The annotation to add. * @internal */ addExistingAnnotation(annotation: PdfAnnotation): void; /** * Remove an annotation from this page. * * @param annotation The annotation to remove. */ removeAnnotation(annotation: PdfAnnotation): void; /** * Add a raw widget annotation dictionary to this page. * * Used by form fields' `addToPage()` to register their widget * annotation without wrapping in a `PdfAnnotation` instance. * * @param widgetDict The widget annotation dictionary. */ addWidgetAnnotation(widgetDict: PdfDict): void; /** * Flatten all annotations into the page content stream. * * After flattening, annotations are rendered as part of the page * content and are no longer interactive. The annotations are * removed from the page's annotation list. */ flattenAnnotations(): void; /** * @internal Get annotation refs for the page dictionary /Annots array. */ getAnnotationRefs(registry: PdfObjectRegistry): PdfRef[]; /** * Draw an SVG image onto this page. * * @param svgString The SVG markup string. * @param options Rendering options (position, size). */ drawSvg(svgString: string, options?: SvgRenderOptions): void; /** * Draw an SVG path data string onto this page. * * The `pathData` parameter uses the same syntax as the SVG `` * attribute (M, L, C, Q, H, V, S, T, A, Z commands). * * **Important:** SVG path coordinates use a top-down Y axis. This * method applies a Y-axis flip so that the path renders correctly in * PDF's bottom-up coordinate system. The `x` / `y` options position * the origin of the path in PDF space. * * @param pathData SVG path data string (e.g. `"M 0 0 L 100 0 L 100 100 Z"`). * @param options Drawing options (position, scale, colours). */ drawSvgPath(pathData: string, options?: DrawSvgPathOptions): void; /** * Draw a QR code at the specified position. * * The QR code is rendered as native PDF vector graphics (filled * rectangles for each dark module), producing resolution-independent * output. * * @param data The string to encode in the QR code. * @param options Position, error correction level, colours, module size. */ drawQrCode(data: string, options?: DrawQrCodeOptions): void; /** * Draw a table on this page. * * The table is rendered as native PDF vector graphics (rectangles, * borders, and text operators). The top-left corner of the table is * at `(options.x, options.y)` and rows extend downward. * * @param options Table configuration: position, size, rows, columns, * fonts, colours, borders, and padding. * @returns A {@link TableRenderResult} with the computed * dimensions and layout metrics. * * @example * ```ts * const result = page.drawTable({ * x: 50, * y: 700, * width: 500, * rows: [ * { cells: ['Name', 'Age', 'City'] }, * { cells: ['Alice', '30', 'London'] }, * { cells: ['Bob', '25', 'Paris'] }, * ], * }); * ``` */ drawTable(options: DrawTableOptions): TableRenderResult; /** * Draw a gradient fill (linear or radial) clipped to a rectangle. * * The gradient is registered as a `/Pattern` resource on this page * and painted within the specified rectangular region. * * @param gradient A gradient descriptor from {@link linearGradient} * or {@link radialGradient}. * @param rect The rectangle to fill. */ drawGradient(gradient: GradientFill, rect: { x: number; y: number; width: number; height: number; }): void; /** * Draw a tiling pattern fill clipped to a rectangle. * * The pattern is registered as a `/Pattern` resource on this page * and painted within the specified rectangular region. * * @param pattern A pattern descriptor from {@link tilingPattern}. * @param rect The rectangle to fill. */ drawPattern(pattern: PatternFill, rect: { x: number; y: number; width: number; height: number; }): void; /** * Begin layer-specific content. * * Content drawn after this call and before {@link endLayer} will be * associated with the given layer and can be shown/hidden by the * viewer. * * @param layer The layer to begin. */ beginLayer(layer: PdfLayer): void; /** * End layer-specific content. * * Must be preceded by a call to {@link beginLayer}. */ endLayer(): void; /** * Begin a transparency group. All drawing operations until * {@link endTransparencyGroup} will be captured and composited as a * single Form XObject with a `/Group` transparency dictionary. * * Transparency groups enable isolated and knockout compositing effects * that are not possible with simple opacity settings. * * Groups can be nested — each call must be paired with a matching * {@link endTransparencyGroup}. * * @param options Isolation, knockout, and color-space settings. * * @example * ```ts * page.beginTransparencyGroup({ isolated: true }); * page.drawRectangle({ x: 50, y: 50, width: 100, height: 100, opacity: 0.5 }); * page.drawCircle({ x: 100, y: 100, size: 60, opacity: 0.5 }); * page.endTransparencyGroup(); * ``` */ beginTransparencyGroup(options?: TransparencyGroupOptions): void; /** * End the current transparency group and composite it onto the page * as a Form XObject. * * @throws {Error} If there is no matching {@link beginTransparencyGroup}. */ endTransparencyGroup(): void; /** * Apply a soft mask (luminosity-based) for subsequent drawing operations. * * White regions in the mask are fully opaque; black regions are fully * transparent. The mask stays active until {@link clearSoftMask} is * called or the graphics state is restored. * * @param mask A soft mask reference created by * {@link PdfDocument.createSoftMask}. * * @example * ```ts * const mask = doc.createSoftMask(200, 200, (b) => { * b.drawRectangle(0, 0, 200, 200, 1); // white = opaque * b.drawCircle(100, 100, 80, 0); // black = transparent * }); * page.applySoftMask(mask); * page.drawImage(image, { x: 50, y: 50, width: 200, height: 200 }); * page.clearSoftMask(); * ``` */ applySoftMask(mask: SoftMaskRef): void; /** * Clear the current soft mask, resetting to no masking. * * This emits an ExtGState with `/SMask /None`, which removes any * previously applied soft mask for subsequent drawing operations. */ clearSoftMask(): void; /** * Mark a rectangular region on this page for redaction. * * The mark is stored but not applied until `doc.applyRedactions()` * is called. * * @param rect The region to redact: [x, y, width, height]. * @param options Additional redaction options (overlay text, colour). */ markForRedaction(rect: [number, number, number, number], options?: Partial): void; /** * Return this page's content stream as fully decoded bytes. * * For a page parsed from a loaded PDF, the original (possibly compressed) * content stream(s) are resolved and decompressed; any operators added * afterwards (via {@link drawText}, {@link drawImage}, …) are appended. * Multiple content streams are joined with newline separators. * * This is the public entry point for the text-extraction pipeline: * * ```ts * import { loadPdf, parseContentStream, extractTextWithPositions } from 'modern-pdf-lib'; * * const doc = await loadPdf(bytes); * const ops = parseContentStream(doc.getPage(0).getContentStream()); * const items = extractTextWithPositions(ops); * ``` * * @returns The decoded content-stream bytes (`Uint8Array`). */ getContentStream(): Uint8Array; /** @internal Return the accumulated operator string. */ getContentStreamData(): string; /** @internal Return the original content-stream refs from a loaded PDF. */ getOriginalContentRefs(): readonly PdfRef[]; /** @internal Return the original resources dict from a loaded PDF. */ getOriginalResources(): PdfDict | undefined; /** @internal Return the object registry for this page. */ getRegistry(): PdfObjectRegistry; /** * @internal Build the `/Resources` dictionary for this page. */ buildResources(): PdfDict; /** * @internal Merge original resources from a loaded PDF with any newly * added resources (fonts, images, graphics states). * * The original resources dict is used as the base. New entries are * added into the appropriate sub-dictionaries (e.g. /Font, /XObject). */ private _mergeResources; /** * @internal Finalize this page: create the content stream object and * register it in the object registry. Returns a {@link PageEntry} * compatible with {@link buildPageTree}. */ finalize(): { pageRef: PdfRef; mediaBox: readonly [number, number, number, number]; width: number; height: number; contentStreamRefs: PdfRef | readonly PdfRef[]; resources: PdfDict; rotation?: number | undefined; cropBox?: readonly [number, number, number, number] | undefined; bleedBox?: readonly [number, number, number, number] | undefined; artBox?: readonly [number, number, number, number] | undefined; trimBox?: readonly [number, number, number, number] | undefined; annotationRefs?: PdfRef[] | undefined; tabOrder?: "S" | "R" | "C" | undefined; }; } //#endregion //#region src/core/pdfCatalog.d.ts /** * Format a `Date` as a PDF date string. * * PDF dates follow the form: `D:YYYYMMDDHHmmSSOHH'mm` * * - `O` is the relationship to UT: `+`, `-`, or `Z`. * - The trailing `HH'mm` is the UT offset. * * @param date A JavaScript Date object. * @returns A PDF date string wrapped in parentheses. */ declare function formatPdfDate(date: Date): string; /** Metadata fields for the /Info dictionary. */ interface DocumentMetadata { title?: string | undefined; author?: string | undefined; subject?: string | undefined; keywords?: string | undefined; creator?: string | undefined; producer?: string | undefined; creationDate?: Date | undefined; modDate?: Date | undefined; } /** * Build the `/Info` dictionary from metadata. * * @param meta Document metadata. * @param registry Object registry — the info dict is registered as an * indirect object. * @returns The indirect reference to the `/Info` dict. */ declare function buildInfoDict(meta: DocumentMetadata, registry: PdfObjectRegistry): PdfRef; /** * Represents a single page's key refs for building the page tree. */ interface PageEntry { /** Indirect reference for this page object. */ readonly pageRef: PdfRef; /** Full media box `[llx, lly, urx, ury]`. */ readonly mediaBox?: readonly [number, number, number, number] | undefined; /** Width of the page (points). */ readonly width: number; /** Height of the page (points). */ readonly height: number; /** * Content stream reference(s). * * A single PdfRef for newly created pages, or an array for loaded pages * that may have multiple content streams (or original + appended). */ readonly contentStreamRefs: PdfRef | readonly PdfRef[]; /** Resources dictionary (fonts, images, etc.). */ readonly resources: PdfDict; /** Optional rotation in degrees (0, 90, 180, 270). */ readonly rotation?: number | undefined; /** Optional crop box `[llx, lly, urx, ury]`. */ readonly cropBox?: readonly [number, number, number, number] | undefined; /** Optional bleed box `[llx, lly, urx, ury]`. */ readonly bleedBox?: readonly [number, number, number, number] | undefined; /** Optional art box `[llx, lly, urx, ury]`. */ readonly artBox?: readonly [number, number, number, number] | undefined; /** Optional trim box `[llx, lly, urx, ury]`. */ readonly trimBox?: readonly [number, number, number, number] | undefined; /** Optional annotation indirect references. */ readonly annotationRefs?: readonly PdfRef[] | undefined; /** Optional tab order: 'S' (structure), 'R' (row), 'C' (column). */ readonly tabOrder?: "S" | "R" | "C" | undefined; } /** * Build the `/Pages` tree and individual `/Page` dictionaries. * * This implementation uses a flat page tree (a single `/Pages` node) * which is correct for documents with up to several thousand pages. * * @param pages Ordered list of page entries. * @param registry Object registry. * @returns The indirect reference to the root `/Pages` node. */ declare function buildPageTree(pages: readonly PageEntry[], registry: PdfObjectRegistry): PdfRef; /** Options for building the catalog. */ interface CatalogOptions { /** Page layout hint. */ pageLayout?: "SinglePage" | "OneColumn" | "TwoColumnLeft" | "TwoColumnRight" | "TwoPageLeft" | "TwoPageRight" | undefined; /** Page mode hint. */ pageMode?: "UseNone" | "UseOutlines" | "UseThumbs" | "FullScreen" | "UseOC" | "UseAttachments" | undefined; /** The natural language of the document content (e.g. `en-US`). */ lang?: string | undefined; } /** * Build the `/Catalog` dictionary. * * @param pagesRef Indirect reference to the root `/Pages` node. * @param registry Object registry. * @param options Optional catalog-level settings. * @returns The indirect reference to the `/Catalog` dict. */ declare function buildCatalog(pagesRef: PdfRef, registry: PdfObjectRegistry, options?: CatalogOptions): PdfRef; /** * High-level helper that wires together the catalog, page tree, and info * dict, returning all the references the writer needs. */ interface DocumentStructure { /** Reference to the /Catalog. */ catalogRef: PdfRef; /** Reference to the /Info dict. */ infoRef: PdfRef; /** Reference to the /Pages node. */ pagesRef: PdfRef; } /** * Build the complete document structure. * * @param pages Page entries (already have refs allocated). * @param meta Document metadata. * @param registry Object registry. * @param options Optional catalog settings. */ declare function buildDocumentStructure(pages: readonly PageEntry[], meta: DocumentMetadata, registry: PdfObjectRegistry, options?: CatalogOptions): DocumentStructure; //#endregion //#region src/crypto/permissions.d.ts /** * Human-friendly permission flags for a PDF document. * * Each flag controls a specific capability: * * - `printing`: `true` = full quality, `'lowResolution'` = low-res only, * `false` / `undefined` = no printing allowed. * - `modifying`: Allow content modifications. * - `copying`: Allow text/graphics extraction. * - `annotating`: Allow adding/modifying annotations. * - `fillingForms`: Allow filling interactive form fields. * - `contentAccessibility`: Allow text extraction for accessibility. * - `documentAssembly`: Allow inserting/deleting/rotating pages. */ interface PdfPermissionFlags { printing?: boolean | "lowResolution" | undefined; modifying?: boolean | undefined; copying?: boolean | undefined; annotating?: boolean | undefined; fillingForms?: boolean | undefined; contentAccessibility?: boolean | undefined; documentAssembly?: boolean | undefined; } /** * Encode human-friendly permission flags into the 32-bit /P integer * used in the PDF encryption dictionary. * * By default (when all flags are `undefined` or `false`), no * permissions are granted beyond the reserved bits. * * @param flags The permissions to encode. * @returns A 32-bit signed integer for the /P entry. */ declare function encodePermissions(flags: PdfPermissionFlags): number; /** * Decode the 32-bit /P integer from a PDF encryption dictionary into * human-friendly permission flags. * * @param value The /P integer from the encryption dictionary. * @returns The decoded permission flags. */ declare function decodePermissions(value: number): PdfPermissionFlags; //#endregion //#region src/crypto/encryptionHandler.d.ts /** * Algorithm selection for new encryption. */ type EncryptAlgorithm = "rc4-40" | "rc4-128" | "aes-128" | "aes-256"; /** * Options for encrypting a PDF document. */ interface EncryptOptions { /** The user password (may be empty string for open access). */ userPassword: string; /** The owner password (restricts editing). */ ownerPassword: string; /** Permission flags. */ permissions?: PdfPermissionFlags | undefined; /** Encryption algorithm. Default: `'aes-128'`. */ algorithm?: EncryptAlgorithm | undefined; } /** * Handles encryption and decryption of PDF objects according to the * standard security handler. * * Create via: * - `PdfEncryptionHandler.create(options)` for new encryption * - `PdfEncryptionHandler.fromEncryptDict(dict, fileId, password)` for existing */ declare class PdfEncryptionHandler { /** The file-level encryption key. */ private readonly fileKey; /** Algorithm version (/V). */ private readonly version; /** Security handler revision (/R). */ private readonly revision; /** Key length in bits. */ private readonly keyLengthBits; /** Whether to use AES (true) or RC4 (false). */ private readonly useAes; /** Whether to encrypt the /Metadata stream. */ private readonly encryptMetadata; /** Permission flags as a 32-bit integer. */ private readonly permissionsValue; /** Owner key (/O). */ private readonly ownerKey; /** User key (/U). */ private readonly userKey; /** Owner encryption key (/OE, V=5 only). */ private readonly ownerEncryptionKey?; /** User encryption key (/UE, V=5 only). */ private readonly userEncryptionKey?; /** Encrypted permissions (/Perms, V=5 only). */ private readonly perms?; /** The file ID (first element of /ID array). */ private readonly fileId; /** * Cache for per-object derived keys (V=1-4 only). * Key: `(objNum << 16) | genNum` — unique integer per object. * Value: the derived encryption key. * * Avoids recomputing MD5(fileKey + objNum + genNum [+ sAlT]) for * every string and stream in the same object. */ private readonly objectKeyCache; private constructor(); /** * Create a new encryption handler for encrypting a document. * * Generates all necessary keys and values for the /Encrypt dictionary. * * @param options Encryption options. * @param fileId Optional file ID. If omitted, a random one is generated. * @returns A configured PdfEncryptionHandler. */ static create(options: EncryptOptions, fileId?: Uint8Array): Promise; /** * Create an encryption handler from an existing /Encrypt dictionary. * * @param dict The /Encrypt dictionary from the PDF trailer. * @param fileId The first element of the /ID array. * @param password The password to try (user or owner). * @returns A configured PdfEncryptionHandler. * @throws If the password is incorrect or the dict is invalid. */ static fromEncryptDict(dict: PdfDict, fileId: Uint8Array, password: string): Promise; /** * Derive the per-object encryption key for V=1-4. * * Per the spec: MD5(fileKey + objNum(3LE) + genNum(2LE) [+ "sAlT" for AES]) * Truncated to min(keyLength/8 + 5, 16) bytes. * * @param objNum Object number. * @param genNum Generation number. * @returns The per-object key. */ private deriveObjectKey; /** * Encrypt raw data for a specific object. * * @param objNum Object number. * @param genNum Generation number. * @param data Plaintext data. * @returns Encrypted data. */ encryptObject(objNum: number, genNum: number, data: Uint8Array): Promise; /** * Decrypt raw data for a specific object. * * @param objNum Object number. * @param genNum Generation number. * @param data Encrypted data. * @returns Decrypted data. */ decryptObject(objNum: number, genNum: number, data: Uint8Array): Promise; /** * Encrypt a PdfString value. * * Converts the string value to bytes, encrypts, and returns a new * hex-encoded PdfString. * * @param objNum Object number. * @param genNum Generation number. * @param str The string to encrypt. * @returns An encrypted PdfString (hex-encoded). */ encryptString(objNum: number, genNum: number, str: PdfString): Promise; /** * Decrypt a stream's data. * * @param objNum Object number. * @param genNum Generation number. * @param streamData Encrypted stream bytes. * @returns Decrypted stream bytes. */ decryptStream(objNum: number, genNum: number, streamData: Uint8Array): Promise; /** * Build the /Encrypt dictionary for the PDF trailer. * * @returns A PdfDict suitable for use as the /Encrypt entry. */ buildEncryptDict(): PdfDict; /** Get the permission flags. */ getPermissions(): PdfPermissionFlags; /** Get the raw permissions value. */ getPermissionsValue(): number; /** Whether this handler uses AES (vs RC4). */ isAes(): boolean; /** The algorithm version (/V). */ getVersion(): number; /** The security handler revision (/R). */ getRevision(): number; /** The file encryption key (for testing/debugging). */ getFileKey(): Uint8Array; /** The file ID used for key derivation. */ getFileId(): Uint8Array; /** Whether metadata streams are encrypted. */ isMetadataEncrypted(): boolean; } //#endregion //#region src/core/pdfWriter.d.ts /** Options that control how the PDF is written. */ interface PdfSaveOptions { /** Apply FlateDecode compression to streams. Default: `true`. */ compress?: boolean | undefined; /** * Compression level for FlateDecode (1–9). Default: `6`. * Ignored when `compress` is `false`. */ compressionLevel?: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | undefined; /** * When `true`, attempt to use WASM-accelerated compression if the * WASM module has been initialized. Default: `false`. */ useWasm?: boolean | undefined; /** * Minimum number of non-stream indirect objects before object streams * are used. When the count exceeds this threshold, objects are packed * into compressed object streams and a cross-reference stream replaces * the traditional xref table. * * Set to `Infinity` to disable object streams (traditional xref). * A useful value for size reduction is `100`. * * Default: `Infinity` (disabled for backward compatibility). */ objectStreamThreshold?: number | undefined; /** Add a blank page if the document has no pages. Default: `true`. */ addDefaultPage?: boolean | undefined; /** Regenerate form field appearances before saving. Default: `true`. */ updateFieldAppearances?: boolean | undefined; } /** * Serialize a PDF document to a `Uint8Array`. * * ```ts * const writer = new PdfWriter(registry, structure, options); * const bytes = writer.write(); * ``` */ declare class PdfWriter { /** All indirect objects. */ private readonly registry; /** Document structure references. */ private readonly structure; private readonly buf; private readonly xrefOffsets; private readonly compress; private readonly compressionLevel; private readonly useWasm; private readonly objectStreamThreshold; private readonly encryptionHandler; /** * When encryption is active, the /Encrypt dict is registered as an * indirect object. Its reference is stored here for the trailer. */ private encryptDictRef; constructor(registry: PdfObjectRegistry, structure: DocumentStructure, options?: PdfSaveOptions, encryptionHandler?: PdfEncryptionHandler); /** * Produce the complete PDF file as a `Uint8Array`. * * When an encryption handler is present, all string and stream * objects are encrypted and the /Encrypt dictionary + /ID array * are added to the trailer. */ write(): Promise; private writeHeader; private writeBody; private writeIndirectObject; /** * Encrypt all encryptable data within an indirect object. * * Per the PDF spec: * - Strings inside the object are encrypted with the per-object key. * - Stream data is encrypted with the per-object key. * - The /Encrypt dictionary itself is never encrypted. * - String values in the trailer /ID array are never encrypted. */ private encryptEntry; /** * Recursively encrypt all PdfString values inside a PdfDict. */ private encryptDictStrings; /** * Recursively encrypt all PdfString values inside a PdfArray. */ private encryptArrayStrings; /** * Apply FlateDecode compression to a stream's data if it is not * already compressed. */ private compressStream; /** * Set of object numbers that must NOT be placed inside an object * stream. This includes the catalog, info dict, pages root, and * any stream objects (which by definition cannot nest in an ObjStm). */ private protectedObjectNumbers; /** * Write the document body using object streams when the number of * eligible non-stream objects exceeds `threshold`. * * @returns `true` if object streams (and a cross-reference stream) * were used and the PDF is complete. `false` if the * threshold was not met — in that case the body has been * written in traditional format and the caller must still * emit the classic xref table and trailer. */ writeBodyWithObjectStreams(threshold: number): Promise; /** * Serialize a group of non-stream objects into a single object stream * (`/Type /ObjStm`) and record xref entries for them. */ private writeObjectStream; /** * Write a cross-reference stream (PDF 1.5+) that replaces the * traditional xref table and trailer. */ private writeXrefStream; private writeXref; private writeTrailer; } /** * Serialize a complete PDF from a registry and structure refs. * * @param registry All registered indirect objects. * @param structure Catalog / Info / Pages references. * @param options Save options. * @param encryptionHandler Optional encryption handler for encrypting * all objects and adding /Encrypt + /ID to * the trailer. * @returns The raw PDF bytes. */ declare function serializePdf(registry: PdfObjectRegistry, structure: DocumentStructure, options?: PdfSaveOptions, encryptionHandler?: PdfEncryptionHandler): Promise; //#endregion //#region src/parser/documentParser.d.ts /** * Options for loading a PDF document from bytes. */ interface LoadPdfOptions { /** Password for encrypted PDFs (Phase 5). */ password?: string; /** When true, skip decryption even if the PDF is encrypted. */ ignoreEncryption?: boolean; /** * When true, update the /ModDate in the /Info dictionary to the * current time when saving. Defaults to true. */ updateMetadata?: boolean; /** * Number of objects to process per event-loop tick during parsing. * Lower values keep the main thread more responsive in browsers. * Defaults to `Infinity` (no throttling). */ objectsPerTick?: number; /** * When `true`, throw an error if a malformed or invalid PDF object * is encountered during parsing. When `false` (default), malformed * objects are silently skipped. */ throwOnInvalidObject?: boolean | undefined; /** * When `true`, clamp extreme floating-point values (very large or * very small numbers) to safe ranges during parsing. This prevents * numeric overflows from producing garbage output. * * Default: `false`. */ capNumbers?: boolean | undefined; } /** * Load a PDF document from raw bytes, an ArrayBuffer, or a Base64-encoded * string. * * This is the primary entry point for parsing existing PDFs. It creates * a `PdfDocumentParser`, runs the full parse pipeline, and returns * a populated {@link PdfDocument}. * * @param data The PDF data as a `Uint8Array`, `ArrayBuffer`, or a * Base64-encoded string. * @param options Optional loading options. * @returns A fully parsed PdfDocument. * * @example * ```ts * import { loadPdf } from 'modern-pdf-lib'; * * // From fetch (ArrayBuffer) * const pdfBytes = await fetch('document.pdf').then(r => r.arrayBuffer()); * const doc = await loadPdf(pdfBytes); * * // From a Base64 string * const doc2 = await loadPdf(base64String); * ``` */ declare function loadPdf(data: Uint8Array | ArrayBuffer | string, options?: LoadPdfOptions): Promise; //#endregion //#region src/outline/pdfOutline.d.ts /** * Describes where an outline item navigates to when clicked. * * - `type: 'page'` — navigate to a specific page by zero-based index. * - `type: 'named'` — use a named destination string. */ interface OutlineDestination { /** Whether to navigate by page index or named destination. */ type: "page" | "named"; /** Zero-based page index (used when `type` is `'page'`). */ pageIndex?: number | undefined; /** Named destination string (used when `type` is `'named'`). */ namedDestination?: string | undefined; /** Page fit mode — how the page should be displayed. */ fit?: "Fit" | "FitH" | "FitV" | "FitB" | "FitBH" | "FitBV" | "XYZ" | undefined; /** Top coordinate for FitH, FitBH, XYZ fit modes. */ top?: number | undefined; /** Left coordinate for FitV, FitBV, XYZ fit modes. */ left?: number | undefined; /** Zoom factor for XYZ fit mode (0 means keep current). */ zoom?: number | undefined; } /** Options for creating an outline item. */ interface OutlineItemOptions { /** Whether the item's children are initially visible. Default: `true`. */ isOpen?: boolean | undefined; /** Colour of the outline text as RGB in range 0-1. */ color?: { r: number; g: number; b: number; } | undefined; /** Whether the title text is bold. */ bold?: boolean | undefined; /** Whether the title text is italic. */ italic?: boolean | undefined; } /** * A single node in the outline tree. Each item has a title, a * destination, and zero or more child items. */ declare class PdfOutlineItem { /** The displayed bookmark title. */ title: string; /** Where clicking this bookmark navigates. */ destination: OutlineDestination; /** Child outline items. */ children: PdfOutlineItem[]; /** Whether children are initially expanded. */ isOpen: boolean; /** Optional colour for the outline text (RGB, 0-1 range). */ color?: { r: number; g: number; b: number; } | undefined; /** Whether the title is displayed in bold. */ bold?: boolean | undefined; /** Whether the title is displayed in italic. */ italic?: boolean | undefined; /** * Create a new outline item. * * @param title Display title for the bookmark. * @param destination Navigation target. * @param options Visual style options. */ constructor(title: string, destination: OutlineDestination, options?: OutlineItemOptions); /** * Add a child outline item. * * @param title Display title. * @param destination Navigation target. * @param options Visual style options. * @returns The newly created child item. */ addChild(title: string, destination: OutlineDestination, options?: OutlineItemOptions): PdfOutlineItem; /** * Remove a child outline item. * * @param item The child item to remove. * @throws If the item is not a direct child. */ removeChild(item: PdfOutlineItem): void; /** * Count all visible descendants (for the /Count entry). * * Per the PDF spec: * - If the item is open, /Count is the total number of visible * descendants (children + their visible descendants). * - If the item is closed, /Count is the negative of the total * number of descendants that *would* be visible if opened. * * @returns The count value for the /Count entry. */ getVisibleDescendantCount(): number; /** * Count the total number of descendants regardless of open/closed state. * @internal */ getTotalDescendantCount(): number; } /** * The root of the outline tree, containing top-level outline items. */ declare class PdfOutlineTree { /** Top-level outline items. */ items: PdfOutlineItem[]; constructor(); /** * Add a top-level outline item. * * @param title Display title. * @param destination Navigation target. * @param options Visual style options. * @returns The newly created item. */ addItem(title: string, destination: OutlineDestination, options?: OutlineItemOptions): PdfOutlineItem; /** * Remove a top-level outline item. * * @param item The item to remove. * @throws If the item is not in the tree. */ removeItem(item: PdfOutlineItem): void; /** * Serialize the outline tree to a PDF /Outlines dictionary. * * This creates the complete outline object graph: * - A root /Outlines dict with /Type, /First, /Last, /Count * - One dict per outline item with /Title, /Parent, /Prev, /Next, * /First, /Last, /Count, /Dest (or /A), /C, /F * * All dictionaries are registered in the provided registry and * cross-linked via indirect references. * * @param registry Object registry for allocating refs. * @param pageRefs Array of PdfRef for each page (indexed by page number). * @returns The indirect reference to the /Outlines root dict. */ toDict(registry: PdfObjectRegistry, pageRefs: readonly PdfRef[]): PdfRef; /** * Parse an outline tree from an existing /Outlines dictionary. * * @param dict The /Outlines dictionary. * @param resolver Function to resolve indirect references to objects. * @param pageRefToIndex Mapping from page ref object numbers to page indices. * @returns A fully populated PdfOutlineTree. */ static fromDict(dict: PdfDict, resolver: (ref: PdfRef) => PdfObject | undefined, pageRefToIndex: ReadonlyMap): PdfOutlineTree; /** * Serialize a list of sibling outline items, linking them with * /Prev and /Next references. * * @param items The sibling items to serialize. * @param parentRef The indirect reference to the parent node. * @param registry Object registry. * @param pageRefs Page references array. * @returns Array of refs for the serialized items. * * @internal */ private serializeItems; /** * Serialize a destination into a /Dest array on the item dict. * * Destination formats per PDF spec: * - [page /Fit] * - [page /FitH top] * - [page /FitV left] * - [page /FitB] * - [page /FitBH top] * - [page /FitBV left] * - [page /XYZ left top zoom] * * @internal */ private serializeDestination; } //#endregion //#region src/metadata/viewerPreferences.d.ts /** * Viewer preference settings for a PDF document. * * All properties are optional. Omitted properties use the viewer's * default behaviour. */ interface ViewerPreferences { /** Hide the viewer's toolbar when the document is active. */ hideToolbar?: boolean | undefined; /** Hide the viewer's menu bar when the document is active. */ hideMenubar?: boolean | undefined; /** Hide the viewer's window UI elements (scrollbars, etc.). */ hideWindowUI?: boolean | undefined; /** Resize the document's window to fit the first page. */ fitWindow?: boolean | undefined; /** Center the document's window on the screen. */ centerWindow?: boolean | undefined; /** Display the document title (from /Info /Title) in the title bar. */ displayDocTitle?: boolean | undefined; /** Page mode to use when exiting full-screen mode. */ nonFullScreenPageMode?: "UseNone" | "UseOutlines" | "UseThumbs" | "UseOC" | undefined; /** Predominant reading order for text. */ direction?: "L2R" | "R2L" | undefined; /** Page scaling preference for the print dialog. */ printScaling?: "None" | "AppDefault" | undefined; /** Paper handling option for duplex printing. */ duplex?: "Simplex" | "DuplexFlipShortEdge" | "DuplexFlipLongEdge" | undefined; /** Page ranges to print, as [start, end] pairs (1-based). */ printPageRange?: [number, number][] | undefined; /** Default number of copies to print. */ numCopies?: number | undefined; /** Whether to pick the paper tray based on the PDF page size. */ pickTrayByPDFSize?: boolean | undefined; } /** * Build a `/ViewerPreferences` dictionary from preferences. * * Only includes entries for properties that are explicitly set * (non-undefined). Boolean values of `false` are included to * explicitly override viewer defaults. * * @param prefs Viewer preferences to serialize. * @returns A PdfDict representing the `/ViewerPreferences` entry. */ declare function buildViewerPreferencesDict(prefs: ViewerPreferences): PdfDict; /** * Parse a `/ViewerPreferences` dictionary into a ViewerPreferences object. * * @param dict The PDF dictionary to parse. * @returns The parsed viewer preferences. */ declare function parseViewerPreferences(dict: PdfDict): ViewerPreferences; //#endregion //#region src/metadata/pdfViewerPreferences.d.ts /** * Class-based API for PDF viewer preferences with individual getter/setter pairs. * * Provides the same functionality as the plain `ViewerPreferences` interface * but with a more discoverable, pdf-lib-compatible API. * * ```ts * const prefs = doc.getViewerPreferences(); * prefs.setHideToolbar(true); * prefs.setDisplayDocTitle(true); * prefs.setPrintScaling('None'); * ``` */ declare class PdfViewerPreferences { private data; constructor(data?: ViewerPreferences); /** Whether the viewer's toolbar should be hidden. */ getHideToolbar(): boolean; /** Set whether the viewer's toolbar should be hidden. */ setHideToolbar(value: boolean): void; /** Whether the viewer's menu bar should be hidden. */ getHideMenubar(): boolean; /** Set whether the viewer's menu bar should be hidden. */ setHideMenubar(value: boolean): void; /** Whether the viewer's window UI elements should be hidden. */ getHideWindowUI(): boolean; /** Set whether the viewer's window UI elements should be hidden. */ setHideWindowUI(value: boolean): void; /** Whether the document window should be resized to fit the first page. */ getFitWindow(): boolean; /** Set whether the document window should be resized to fit the first page. */ setFitWindow(value: boolean): void; /** Whether the document window should be centered on the screen. */ getCenterWindow(): boolean; /** Set whether the document window should be centered on the screen. */ setCenterWindow(value: boolean): void; /** Whether the title bar should display the document title from metadata. */ getDisplayDocTitle(): boolean; /** Set whether the title bar should display the document title. */ setDisplayDocTitle(value: boolean): void; /** Whether the paper tray should be selected based on the PDF page size. */ getPickTrayByPDFSize(): boolean; /** Set whether the paper tray should be selected based on the PDF page size. */ setPickTrayByPDFSize(value: boolean): void; /** Page mode to use when exiting full-screen mode. */ getNonFullScreenPageMode(): "UseNone" | "UseOutlines" | "UseThumbs" | "UseOC"; /** Set the page mode to use when exiting full-screen mode. */ setNonFullScreenPageMode(value: "UseNone" | "UseOutlines" | "UseThumbs" | "UseOC"): void; /** Predominant reading order for text. */ getDirection(): "L2R" | "R2L"; /** Set the predominant reading order for text. */ setDirection(value: "L2R" | "R2L"): void; /** Page scaling preference for the print dialog. */ getPrintScaling(): "None" | "AppDefault"; /** Set the page scaling preference for the print dialog. */ setPrintScaling(value: "None" | "AppDefault"): void; /** Paper handling option for duplex printing, or undefined if not set. */ getDuplex(): "Simplex" | "DuplexFlipShortEdge" | "DuplexFlipLongEdge" | undefined; /** Set the paper handling option for duplex printing. */ setDuplex(value: "Simplex" | "DuplexFlipShortEdge" | "DuplexFlipLongEdge"): void; /** Default number of copies to print. */ getNumCopies(): number; /** Set the default number of copies to print. */ setNumCopies(value: number): void; /** Page ranges to print, as [start, end] pairs, or undefined if not set. */ getPrintPageRange(): [number, number][] | undefined; /** Set the page ranges to print, as [start, end] pairs. */ setPrintPageRange(value: [number, number][]): void; /** Convert to a PdfDict for embedding in the PDF catalog. */ toDict(): PdfDict; /** Convert to a plain ViewerPreferences object. */ toObject(): ViewerPreferences; } //#endregion //#region src/signature/signatureHandler.d.ts /** * Options for a visible signature appearance on the page. */ interface VisibleSignatureOptions { /** Zero-based page index where the signature should appear. Default: 0. */ pageIndex?: number | undefined; /** Rectangle [x, y, width, height] in PDF points from the bottom-left corner. */ rect: [number, number, number, number]; /** * Text lines to display in the signature box. * Each string becomes a separate line. If omitted, auto-generates * from the signer name, reason, location, and date. */ text?: string[] | undefined; /** Font size for the text. Default: 10. */ fontSize?: number | undefined; /** * Background color as [r, g, b] values (0–1). Default: transparent. */ backgroundColor?: [number, number, number] | undefined; /** * Border color as [r, g, b] values (0–1). Default: [0, 0, 0] (black). */ borderColor?: [number, number, number] | undefined; /** Border width in points. Default: 1. Set to 0 for no border. */ borderWidth?: number | undefined; } /** * Options for signing a PDF. */ interface SignOptions { /** DER-encoded X.509 certificate. */ certificate: Uint8Array; /** PKCS#8 DER-encoded private key. */ privateKey: Uint8Array; /** Hash algorithm. Default: 'SHA-256'. */ hashAlgorithm?: "SHA-256" | "SHA-384" | "SHA-512" | undefined; /** Reason for signing. */ reason?: string | undefined; /** Location of signing. */ location?: string | undefined; /** Contact information. */ contactInfo?: string | undefined; /** RFC 3161 TSA URL for timestamping (optional). */ timestampUrl?: string | undefined; /** * Visible signature appearance options. When provided, the signature * field is rendered visibly on the specified page with text and * optional styling. When omitted, the signature is invisible. */ appearance?: VisibleSignatureOptions | undefined; } /** * Information about an existing signature in a PDF. */ interface PdfSignatureInfo { /** The signature field name. */ fieldName: string; /** Subject CN from the certificate. */ signedBy: string; /** Reason for signing. */ reason?: string | undefined; /** Location of signing. */ location?: string | undefined; /** Contact information. */ contactInfo?: string | undefined; /** Signing date/time. */ signingDate?: Date | undefined; /** The ByteRange covering this signature. */ byteRange: [number, number, number, number]; /** Whether the signature is valid (set during verification). */ signatureValid?: boolean | undefined; } /** * Sign a PDF document. * * Returns the signed PDF bytes. Uses incremental save to preserve * existing content (including any previous signatures). * * @param pdfBytes The original PDF file bytes. * @param fieldName The name for the signature field. * @param options Signing options (certificate, key, etc.). * @returns The signed PDF bytes. * * @example * ```ts * const signedPdf = await signPdf(pdfBytes, 'Signature1', { * certificate: certDer, * privateKey: keyDer, * reason: 'Document approval', * location: 'New York, NY', * }); * ``` */ declare function signPdf(pdfBytes: Uint8Array, fieldName: string, options: SignOptions): Promise; /** * Extract signature information from a PDF. * * Scans the PDF for signature dictionaries and extracts metadata * from each one. * * @param pdfBytes The PDF file bytes. * @returns Array of signature info objects. */ declare function getSignatures(pdfBytes: Uint8Array): PdfSignatureInfo[]; //#endregion //#region src/core/embeddedFiles.d.ts /** Describes a file to attach to (or already attached to) a PDF. */ interface EmbeddedFile { /** Filename. */ name: string; /** File data. */ data: Uint8Array; /** MIME type (e.g. `"application/pdf"`, `"text/plain"`). */ mimeType: string; /** Optional description. */ description?: string | undefined; /** Optional creation date. */ creationDate?: Date | undefined; /** Optional modification date. */ modificationDate?: Date | undefined; /** * Optional PDF 2.0 `/AFRelationship` of this file to the document * (`Source`/`Data`/`Alternative`/…). Defaults to `Unspecified`. */ relationship?: string | undefined; } /** * Create an embedded file stream and filespec dictionary, registering * them in the object registry. * * @param registry The PDF object registry. * @param file The file to embed. * @returns The indirect reference to the filespec dictionary. */ declare function attachFile(registry: PdfObjectRegistry, file: EmbeddedFile): PdfRef; /** * Extract embedded file attachments from a catalog dictionary. * * @param catalogDict The catalog dictionary. * @param resolver A function to resolve indirect references. * @returns An array of embedded file descriptions. */ declare function getAttachments(catalogDict: PdfDict, resolver: (ref: PdfRef) => PdfObject): EmbeddedFile[]; /** * Build an `/EmbeddedFiles` name tree dictionary. * * @param files Array of indirect references to filespec dictionaries. * @param names Corresponding file names (same order as `files`). * @param registry The PDF object registry. * @returns The name tree dictionary. */ declare function buildEmbeddedFilesNameTree(files: PdfRef[], names: string[], _registry: PdfObjectRegistry): PdfDict; //#endregion //#region src/compliance/associatedFiles.d.ts /** Relationship type for associated files (PDF 2.0 / PDF/A-3). */ type AFRelationship = "Source" | "Data" | "Alternative" | "Supplement" | "EncryptedPayload" | "FormData" | "Schema" | "Unspecified"; /** Options for creating an associated file entry. */ interface AssociatedFileOptions { /** The file data bytes. */ readonly data: Uint8Array; /** The filename. */ readonly filename: string; /** MIME type of the file (e.g. `"text/xml"`, `"application/pdf"`). */ readonly mimeType: string; /** Relationship to the PDF document. */ readonly relationship: AFRelationship; /** Optional description of the file. */ readonly description?: string | undefined; /** Optional creation date (ISO 8601 string, stored as PDF date). */ readonly creationDate?: string | undefined; /** Optional modification date (ISO 8601 string, stored as PDF date). */ readonly modificationDate?: string | undefined; } /** Result of creating an associated file. */ interface AssociatedFileResult { /** Reference to the file specification dictionary. */ readonly fileSpecRef: PdfRef; /** Reference to the embedded file stream. */ readonly streamRef: PdfRef; } /** * Create a PDF/A-3 compliant associated file entry. * * Creates: * 1. An embedded file stream with the data * 2. A file specification dictionary with /AFRelationship * * The caller is responsible for adding the `fileSpecRef` to the * catalog's /AF array and /Names/EmbeddedFiles name tree. * * @param registry The PDF object registry. * @param options Associated file configuration. * @returns References to the created objects. */ declare function createAssociatedFile(registry: PdfObjectRegistry, options: AssociatedFileOptions): AssociatedFileResult; /** * Build an /AF array from multiple associated file specification references. * * The returned array should be set on the catalog dictionary: * ```ts * catalogDict.set('/AF', buildAfArray([ref1, ref2])); * ``` * * @param fileSpecRefs Indirect references to file specification dictionaries. * @returns A PdfArray containing the references. */ declare function buildAfArray(fileSpecRefs: PdfRef[]): PdfArray; //#endregion //#region src/core/watermark.d.ts /** Options for watermark rendering. */ interface WatermarkOptions { /** The watermark text. */ text: string; /** Font size in points (default: 60). */ fontSize?: number | undefined; /** Text colour as RGB (0-1 range, default: light gray). */ color?: { r: number; g: number; b: number; } | undefined; /** Opacity from 0 (invisible) to 1 (opaque), default: 0.3. */ opacity?: number | undefined; /** Rotation angle in degrees (default: 45). */ rotation?: number | undefined; /** Position: `'center'`, `'top'`, or `'bottom'` (default: `'center'`). */ position?: "center" | "top" | "bottom" | undefined; } /** * Add a watermark to a single page. * * The watermark is drawn using the Helvetica standard font (no * embedding required). The text is rendered with the specified * rotation, opacity, and colour. * * @param page The page to watermark. * @param options Watermark options. * @param registry The PDF object registry (for ExtGState). */ declare function addWatermarkToPage(page: PdfPage, options: WatermarkOptions, registry: PdfObjectRegistry): void; /** * Add a watermark to all pages in a document. * * @param doc The PDF document. * @param options Watermark options. */ declare function addWatermark(doc: PdfDocument, options: WatermarkOptions): void; //#endregion //#region src/signature/signatureVerifier.d.ts /** * Result of verifying a single signature. */ interface SignatureVerificationResult { /** The signature field name. */ fieldName: string; /** Subject CN from the certificate. */ signedBy: string; /** Overall validity (integrity AND signature). */ valid: boolean; /** Reason for signing (if present). */ reason?: string | undefined; /** Whether the ByteRange hash matches the signed hash. */ integrityValid: boolean; /** Whether the cryptographic signature is valid. */ certificateValid?: boolean | undefined; /** Signing date (if present in signed attributes). */ signingDate?: Date | undefined; /** * Whether the ESS `signing-certificate-v2` attribute (RFC 5035, * CAdES-BES / PAdES-B-B) is present in the signed attributes. */ cadesSigningCertPresent?: boolean | undefined; /** * When the ESS signing-certificate-v2 attribute is present, whether its * embedded `certHash` matches the digest of the signer certificate * (binding the signature to that exact certificate). `undefined` when * the attribute is absent. */ cadesSigningCertHashValid?: boolean | undefined; } /** * Verify all signatures in a PDF. * * For each signature found: * 1. Computes the hash of the ByteRange-covered bytes * 2. Extracts the PKCS#7 structure * 3. Verifies the message digest matches * 4. Verifies the cryptographic signature against the certificate * * @param pdfBytes The PDF file bytes. * @returns Array of verification results. */ declare function verifySignatures(pdfBytes: Uint8Array): Promise; /** * Verify a single signature. * * Extracts the signed attributes from the PKCS#7 structure and * verifies the signature using the certificate's public key. * * @param pdfBytes The PDF file bytes. * @param byteRange The ByteRange array. * @param signatureBytes The DER-encoded PKCS#7 signature. * @param certificateBytes The DER-encoded X.509 certificate. * @returns `true` if the signature is valid. */ declare function verifySignature(pdfBytes: Uint8Array, byteRange: [number, number, number, number], signatureBytes: Uint8Array, certificateBytes: Uint8Array): Promise; //#endregion //#region src/plugins/pluginSystem.d.ts /** Minimal document shape visible to plugins. */ interface PluginDocument { getPageCount(): number; getPages(): readonly PluginPage[]; setTitle(title: string): void; setAuthor(author: string): void; setSubject(subject: string): void; setKeywords(keywords: string | string[]): void; setProducer(producer: string): void; setCreator(creator: string): void; setCreationDate(date: Date): void; setModDate(date: Date): void; setLanguage(lang: string): void; } /** Minimal page shape visible to plugins. */ interface PluginPage { getWidth(): number; getHeight(): number; } /** * Plugin lifecycle hooks -- plugins can intercept and modify behavior * at various points in the PDF creation pipeline. */ interface PdfPlugin { /** Unique plugin name. */ readonly name: string; /** Plugin version string. */ readonly version?: string | undefined; /** Called when the plugin is registered on a document. */ onRegister?(doc: PluginDocument): void; /** Called before a page is added. Can modify page options. */ onBeforeAddPage?(size: PageSize): PageSize; /** Called after a page is added. Can add content to the page. */ onAfterAddPage?(page: PluginPage, doc: PluginDocument): void; /** * Called before font embedding. Can transform font data and options. * Return the (possibly modified) data and options. */ onBeforeEmbedFont?(data: Uint8Array, options: EmbedFontOptions): { data: Uint8Array; options: EmbedFontOptions; }; /** Called before image embedding. Can transform image data. */ onBeforeEmbedImage?(data: Uint8Array): Uint8Array; /** * Called before serialization. Can modify document structure. * May be async (e.g. for network-dependent plugins). */ onBeforeSave?(doc: PluginDocument): void | Promise; /** * Called after serialization. Can post-process the final PDF bytes. * May be async. */ onAfterSave?(bytes: Uint8Array): Uint8Array | Promise; /** Called to add custom entries to the document catalog dict. */ onBuildCatalog?(catalog: PdfDict): void; /** Called to add custom entries to page dictionaries. */ onBuildPageDict?(pageDict: PdfDict, pageIndex: number): void; } /** * Manages plugin registration, ordering, and hook execution. * * Plugins execute in registration order for every hook. */ declare class PdfPluginManager { private readonly plugins; /** * Register a plugin. Plugins execute in registration order. * * @throws {Error} If a plugin with the same name is already registered. */ register(plugin: PdfPlugin): void; /** * Unregister a plugin by name. * * @returns `true` if the plugin was found and removed, `false` otherwise. */ unregister(name: string): boolean; /** Get a registered plugin by name. */ get(name: string): PdfPlugin | undefined; /** List all registered plugins in registration order. */ list(): readonly PdfPlugin[]; /** Check whether any plugins are registered. */ get hasPlugins(): boolean; /** * Execute the `onRegister` hook on a single plugin. * Called internally when `.use()` is called on a document. */ executeOnRegister(plugin: PdfPlugin, doc: PluginDocument): void; /** * Execute `onBeforeAddPage` across all plugins in order. * Each plugin may modify the page size; the final result is returned. */ executeOnBeforeAddPage(size: PageSize): PageSize; /** * Execute `onAfterAddPage` across all plugins in order. */ executeOnAfterAddPage(page: PluginPage, doc: PluginDocument): void; /** * Execute `onBeforeEmbedFont` across all plugins in order. * Each plugin may modify the data/options; the final result is returned. */ executeOnBeforeEmbedFont(data: Uint8Array, options: EmbedFontOptions): { data: Uint8Array; options: EmbedFontOptions; }; /** * Execute `onBeforeEmbedImage` across all plugins in order. * Each plugin may transform the image data; the final result is returned. */ executeOnBeforeEmbedImage(data: Uint8Array): Uint8Array; /** * Execute `onBeforeSave` across all plugins in order. * Awaits each plugin sequentially to maintain ordering guarantees. */ executeOnBeforeSave(doc: PluginDocument): Promise; /** * Execute `onAfterSave` across all plugins in order. * Each plugin may transform the output bytes; the final result is returned. */ executeOnAfterSave(bytes: Uint8Array): Promise; /** * Execute `onBuildCatalog` across all plugins in order. */ executeOnBuildCatalog(catalog: PdfDict): void; /** * Execute `onBuildPageDict` across all plugins in order. */ executeOnBuildPageDict(pageDict: PdfDict, pageIndex: number): void; } //#endregion //#region src/core/pdfDocument.d.ts /** * The 14 standard PDF fonts guaranteed to be available in every PDF * viewer. These can be used without embedding font data. */ declare const StandardFonts: { readonly Courier: "Courier"; readonly CourierBold: "Courier-Bold"; readonly CourierOblique: "Courier-Oblique"; readonly CourierBoldOblique: "Courier-BoldOblique"; readonly Helvetica: "Helvetica"; readonly HelveticaBold: "Helvetica-Bold"; readonly HelveticaOblique: "Helvetica-Oblique"; readonly HelveticaBoldOblique: "Helvetica-BoldOblique"; readonly TimesRoman: "Times-Roman"; readonly TimesBold: "Times-Bold"; readonly TimesItalic: "Times-Italic"; readonly TimesBoldItalic: "Times-BoldItalic"; readonly Symbol: "Symbol"; readonly ZapfDingbats: "ZapfDingbats"; }; type StandardFontName = (typeof StandardFonts)[keyof typeof StandardFonts]; /** * Options for font embedding. */ interface EmbedFontOptions { /** Whether to subset the font to reduce file size. Default: true. */ subset?: boolean | undefined; /** OpenType feature flags. e.g., { kern: true, liga: true }. */ features?: Record | undefined; /** Custom name to use in the font dictionary's /BaseFont instead of the font's PostScript name. */ customName?: string | undefined; } /** * Options for {@link PdfDocument.setTitle}. */ interface SetTitleOptions { /** When `true`, tell PDF viewers to display the document title in the window title bar. */ showInWindowTitleBar?: boolean | undefined; } /** * The root document object. Create via {@link createPdf}. * * Manages: * - Page collection (ordered) * - Embedded resources (fonts, images) * - Document metadata (title, author, dates, …) * - Object-number allocation */ declare class PdfDocument { /** * Load an existing PDF document from raw bytes, an ArrayBuffer, or a * Base64-encoded string. * * This is the primary entry point for parsing existing PDFs. It * validates the file header, parses the cross-reference structure, * resolves the page tree and metadata, and returns a fully populated * {@link PdfDocument} that can be inspected or further modified. * * @param data The PDF data as a `Uint8Array`, `ArrayBuffer`, or a * Base64-encoded string. * @param options Optional loading options (e.g. password, encryption). * @returns A promise that resolves to the parsed PdfDocument. * * @example * ```ts * // From fetch (ArrayBuffer) * const pdfBytes = await fetch('document.pdf').then(r => r.arrayBuffer()); * const doc = await PdfDocument.load(pdfBytes); * * // From a Base64 string * const doc2 = await PdfDocument.load(base64String); * ``` */ static load(data: Uint8Array | ArrayBuffer | string, options?: LoadPdfOptions): Promise; /** * Create a new, empty PDF document. * * This is the static-method equivalent of {@link createPdf}. * * ```ts * const doc = PdfDocument.create(); * ``` */ static create(): PdfDocument; /** Object registry — allocates indirect references. */ private readonly registry; /** Pages in document order. */ private readonly pages; /** Metadata fields. */ private readonly meta; /** Counter for font resource names (F1, F2, …). */ private fontCounter; /** Counter for image resource names (Im1, Im2, …). */ private imageCounter; /** Counter for form XObject resource names (XF1, XF2, …). */ private formXObjectCounter; /** Plugin manager — handles plugin registration and lifecycle hooks. */ private readonly pluginManager; /** * @param registry Optional pre-populated object registry (used when * loading an existing PDF so parsed objects are preserved). */ constructor(registry?: PdfObjectRegistry); /** Embedded fonts — maps base font name → FontRef. */ private readonly embeddedFonts; /** Embedded images — maps an internal key → ImageRef. */ private readonly embeddedImages; /** * Register a plugin on this document. * * Plugins execute their lifecycle hooks in registration order. * The plugin's `onRegister` hook (if defined) is called immediately. * * @param plugin The plugin to register. * @returns This document (for chaining). * * @example * ```ts * import { createPdf } from 'modern-pdf-lib'; * import { timestampPlugin } from 'modern-pdf-lib/plugins'; * * const doc = createPdf() * .use(timestampPlugin()) * .use(myCustomPlugin); * ``` */ use(plugin: PdfPlugin): this; /** * Get the plugin manager for advanced plugin operations. * * Most users should prefer `doc.use(plugin)` for registration. * The manager is exposed for cases where you need to unregister, * list, or introspect registered plugins. */ getPluginManager(): PdfPluginManager; /** * Add a page to the document. * * When called with a {@link PageSize} (or no argument), a new blank page * is created. When called with an existing {@link PdfPage} instance * (e.g. one returned by {@link copyPages}), that page is inserted * directly. * * @param sizeOrPage A page size as `[width, height]` tuple, * `{ width, height }` object, one of the * {@link PageSizes} constants, or an existing * {@link PdfPage} instance. Defaults to A4. * @returns The {@link PdfPage} that was added. */ addPage(sizeOrPage?: PageSize | PdfPage): PdfPage; /** * Return a specific page by zero-based index. * * @param index Zero-based page index. * @returns The {@link PdfPage} at the given index. * @throws If the index is out of range. */ getPage(index: number): PdfPage; /** * Return all pages. */ getPages(): readonly PdfPage[]; /** * Return the page count. */ getPageCount(): number; /** The number of pages in this document. */ get pageCount(): number; /** * @internal Return the mutable internal pages array. * Used by `pageManipulation.ts` and `documentMerge.ts`. */ getInternalPages(): PdfPage[]; /** * @internal Return the object registry for external modules. */ getRegistry(): PdfObjectRegistry; /** * @internal Register all currently embedded fonts and CID encoders * on the given page. Used when inserting or copying pages. */ registerFontsOnPage(page: PdfPage): void; /** * @internal Return the embedded fonts map for cross-document operations. */ getEmbeddedFonts(): ReadonlyMap; /** * @internal Add a pre-built page (from loading a parsed PDF). * Unlike `addPage()`, this does NOT create a new blank page — * it inserts a PdfPage that already carries original content. */ _addLoadedPage(page: PdfPage): void; /** * @internal Advance font/image counters past names already used * by loaded pages so new resources don't collide. */ _advanceCounters(maxFont: number, maxImage: number, _maxGState: number): void; /** * @internal Get the next font counter value and increment it. */ allocateFontName(): string; /** * @internal Get the next image counter value and increment it. */ allocateImageName(): string; /** * Insert a new blank page at the specified position. * * @param index Zero-based position (0 to pageCount inclusive). * @param size Optional page size. Defaults to A4. * @returns The newly created PdfPage. */ insertPage(index: number, size?: PageSize): PdfPage; /** * Remove a page by its zero-based index. * * @param index Zero-based page index to remove. * @throws RangeError if the index is out of bounds. */ removePage(index: number): void; /** * Move a page from one position to another. * * @param fromIndex Current zero-based index of the page. * @param toIndex Target zero-based index (after removal). */ movePage(fromIndex: number, toIndex: number): void; /** * Copy pages from another document into this one. * * The copied pages are appended to the end of this document. * Resources (fonts, images) are deeply cloned and re-registered * in the target document's registry. * * @param sourceDoc The source document to copy pages from. * @param indices Zero-based indices of pages to copy. * @returns The newly created pages in this document. */ copyPages(sourceDoc: PdfDocument, indices: number[]): Promise; /** Counter for unique TTF font keys (to distinguish multiple TTF embeds). */ private ttfCounter; /** * Maps TTF font resource name → EmbeddedFont and mutable PDF objects * that need to be updated at save time with subsetted data. */ private readonly ttfFonts; /** * Embed a font in the document. * * Accepts either: * - A **standard font name** string (e.g. `"Helvetica"`) — embeds a * Type 1 font reference (no font data needed). * - A **Uint8Array** of TrueType font bytes — embeds a CIDFont Type 2 * composite font with /Identity-H encoding, /FontDescriptor, /ToUnicode * CMap, and /FontFile2 stream. * * The returned {@link FontRef} includes `widthOfTextAtSize()` and * `heightAtSize()` methods for text measurement. * * @param fontNameOrData Base font name string or raw TTF/OTF bytes. * @param options Optional embedding options (subset, OpenType features). * @returns A {@link FontRef} to pass to drawing methods. */ embedFont(fontNameOrData: string | Uint8Array, options?: EmbedFontOptions): Promise; /** * Embed a standard (Type 1) font. * @internal */ private embedStandardFont; /** * Embed a TrueType font from raw bytes as a CIDFont Type 2. * @internal */ private embedTrueTypeFont; /** * Embed a CFF-based OpenType font from raw bytes as a CIDFont Type 0. * * CFF fonts use /CIDFontType0 (instead of /CIDFontType2 for TrueType), * /FontFile3 with /Subtype /CIDFontType0C (instead of /FontFile2), * and embed only the raw CFF table data (not the full OTF wrapper). * No /CIDToGIDMap is needed since CFF fonts map CIDs directly. * * @internal */ private embedCffFont; /** * Embed a PNG image. * * Fully decodes the PNG (including filter reconstruction and alpha * channel separation) and creates a correct PDF image XObject. * For images with transparency, a separate SMask XObject is created * and referenced from the main image. * * @param pngData Raw PNG file bytes as a `Uint8Array` or `ArrayBuffer`. * @returns A promise resolving to an {@link ImageRef} to pass to `page.drawImage()`. */ embedPng(pngData: Uint8Array | ArrayBuffer): Promise; /** * Embed a PNG image synchronously. * * @deprecated Use {@link embedPng} (now async) for API consistency. * Will be removed in v2.0. * @param pngData Raw PNG file bytes as a `Uint8Array` or `ArrayBuffer`. * @returns An {@link ImageRef} to pass to `page.drawImage()`. */ embedPngSync(pngData: Uint8Array | ArrayBuffer): ImageRef; /** * Embed a JPEG image. * * JPEG data can be embedded directly as a PDF stream with * `DCTDecode` filter — no re-encoding is needed. * * @param jpegData Raw JPEG file bytes as a `Uint8Array` or `ArrayBuffer`. * @returns An {@link ImageRef}. */ embedJpeg(jpegData: Uint8Array | ArrayBuffer): Promise; /** * Embed a WebP image. * * WebP cannot be directly embedded in PDF. This method decodes the * WebP image to raw pixels (VP8/lossy, VP8L/lossless, or VP8+ALPH), * then embeds as a FlateDecode image XObject. If the WebP has * transparency, the alpha channel is embedded as a soft mask. * * @param webpData Raw WebP file bytes as a `Uint8Array` or `ArrayBuffer`. * @returns An {@link ImageRef}. */ embedWebP(webpData: Uint8Array | ArrayBuffer): ImageRef; /** * Embed a TIFF image. * * Decodes the TIFF image and creates a PDF image XObject with * FlateDecode compression. For multi-page TIFFs, a specific page * can be selected via options. * * @param tiffData Raw TIFF file bytes as a `Uint8Array` or `ArrayBuffer`. * @param options Options (e.g., `{ page: 0 }` for multi-page TIFFs). * @returns An {@link ImageRef}. */ embedTiff(tiffData: Uint8Array | ArrayBuffer, options?: { page?: number | undefined; }): ImageRef; /** * Embed an image, auto-detecting the format from file headers. * * Inspects the first bytes to determine the image format (PNG, JPEG, * WebP, or TIFF), then delegates to the appropriate embedding method. * * Supported formats: * - **PNG**: `89 50 4E 47` — embedded via {@link embedPng} * - **JPEG**: `FF D8 FF` — embedded via {@link embedJpeg} * - **WebP**: `52 49 46 46` + `57 45 42 50` — embedded via {@link embedWebP} * - **TIFF LE**: `49 49 2A 00` — embedded via {@link embedTiff} * - **TIFF BE**: `4D 4D 00 2A` — embedded via {@link embedTiff} * * @param imageData Raw image file bytes (PNG, JPEG, WebP, or TIFF). * @returns An {@link ImageRef} to pass to `page.drawImage()`. * @throws If the image format cannot be detected. * * @example * ```ts * const bytes = new Uint8Array(await readFile('photo.jpg')); * const image = await pdf.embedImage(bytes); * page.drawImage(image, { x: 50, y: 400, width: 200, height: 150 }); * ``` */ embedImage(imageData: Uint8Array | ArrayBuffer): Promise; /** * Embed multiple images in parallel. * * Auto-detects each image's format (PNG, JPEG, WebP, TIFF) and embeds * them concurrently using `Promise.all`. Returns an array of * {@link ImageRef} in the same order as the input. * * @param items Array of image descriptors with raw bytes and optional name. * @returns Array of {@link ImageRef} in the same order as `items`. * * @example * ```ts * const [logo, photo] = await doc.embedImages([ * { data: logoPngBytes }, * { data: photoJpegBytes }, * ]); * ``` */ embedImages(items: Array<{ data: Uint8Array | ArrayBuffer; name?: string; }>): Promise; /** * Embed multiple fonts in parallel. * * Accepts an array of font descriptors — each containing either a * standard font name string or raw TTF/OTF bytes — and embeds them * concurrently using `Promise.all`. Returns an array of * {@link FontRef} in the same order as the input. * * @param items Array of font descriptors with font name/data and options. * @returns Array of {@link FontRef} in the same order as `items`. * * @example * ```ts * const [serif, mono] = await doc.embedFonts([ * { data: serifTtfBytes }, * { data: 'Courier' }, * ]); * ``` */ embedFonts(items: Array<{ data: string | Uint8Array; options?: EmbedFontOptions; }>): Promise; /** * Embed pages from another PDF as Form XObjects. * * Each embedded page is turned into a self-contained Form XObject that * can be painted onto any page via `page.drawPage()`. The source PDF's * content streams are decoded and concatenated, and all referenced * resources (fonts, images, etc.) are deep-cloned into this document's * registry. * * @param data Raw PDF bytes (Uint8Array or ArrayBuffer). * @param pageIndices Zero-based page indices to embed. Defaults to * `[0]` (first page only). * @returns Array of {@link EmbeddedPdfPage} handles. * * @example * ```ts * const [embeddedPage] = await doc.embedPdf(existingPdfBytes, [0]); * page.drawPage(embeddedPage, { x: 50, y: 50, width: 300, height: 400 }); * ``` */ embedPdf(data: Uint8Array | ArrayBuffer, pageIndices?: number[], options?: EmbedPageOptions): Promise; /** * Embed a single page (from this or another document) as a Form XObject. * * This is useful when you have an already-parsed PdfPage and want to * stamp it onto other pages as a form XObject. * * @param page The PdfPage to embed. * @param options Optional bounding box / transformation matrix. * @returns An {@link EmbeddedPdfPage} handle. */ embedPage(page: PdfPage, options?: EmbedPageOptions): EmbeddedPdfPage; /** * Embed multiple pages as Form XObjects in batch. * Convenience wrapper around {@link embedPage}. * * @param pages Array of PdfPage instances to embed. * @returns Array of {@link EmbeddedPdfPage} handles, one per input page. */ embedPages(pages: PdfPage[]): EmbeddedPdfPage[]; /** Set the document title. */ setTitle(title: string, options?: SetTitleOptions): void; /** Set the document author. */ setAuthor(author: string): void; /** Set the document subject. */ setSubject(subject: string): void; /** Set the document keywords. */ setKeywords(keywords: string | string[]): void; /** Set the creator application name. */ setCreator(creator: string): void; /** Set the producer string (defaults to `"modern-pdf"`). */ setProducer(producer: string): void; /** Set the document creation date. */ setCreationDate(date: Date): void; /** Set the document modification date. */ setModDate(date: Date): void; /** Get the document title, or `undefined` if not set. */ getTitle(): string | undefined; /** Get the document author, or `undefined` if not set. */ getAuthor(): string | undefined; /** Get the document subject, or `undefined` if not set. */ getSubject(): string | undefined; /** Get the document keywords, or `undefined` if not set. */ getKeywords(): string | undefined; /** Get the creator application name, or `undefined` if not set. */ getCreator(): string | undefined; /** Get the producer string. */ getProducer(): string | undefined; /** Get the document creation date. */ getCreationDate(): Date | undefined; /** Get the document modification date, or `undefined` if not set. */ getModDate(): Date | undefined; /** The encryption handler, set when `encrypt()` is called. */ private encryptionHandler; /** * Configure encryption for this document. * * When encryption is set, the document will be encrypted on the next * call to `save()`. The /Encrypt dictionary and file ID are * generated automatically. * * @param options Encryption options (passwords, permissions, algorithm). * * @example * ```ts * const doc = createPdf(); * doc.addPage(); * doc.encrypt({ * userPassword: 'user123', * ownerPassword: 'owner456', * permissions: { printing: true, copying: false }, * algorithm: 'aes-256', * }); * const bytes = await doc.save(); * ``` */ encrypt(options: EncryptOptions): Promise; /** * Check whether this document has encryption configured. * * Returns `true` if `encrypt()` has been called on this document, * or if the document was loaded from an encrypted PDF. */ isEncrypted(): boolean; /** * Get the permission flags for this document, if encrypted. * * @returns The decoded permission flags, or `undefined` if the * document is not encrypted. */ getPermissions(): PdfPermissionFlags | undefined; /** * Get the encryption handler (for advanced use / testing). * @internal */ getEncryptionHandler(): PdfEncryptionHandler | undefined; /** Original PDF bytes (set when loaded from an existing file). */ private originalBytes; /** * @internal Set the original bytes (called by the parser on load). */ setOriginalBytes(bytes: Uint8Array): void; /** * @internal Get the original bytes. */ getOriginalBytes(): Uint8Array | undefined; /** * Add a signature field to a page. * * This is a placeholder method that records the intent to sign. * The actual signature creation happens in `sign()`. * * @param pageIndex Zero-based page index. * @param rect Rectangle [x1, y1, x2, y2] for the visual appearance. * @param name The signature field name (must be unique). */ addSignatureField(pageIndex: number, rect: [number, number, number, number], name: string): void; /** Pending signature field definitions. */ private readonly signatureFields; /** * Sign the PDF document. * * Returns the signed PDF bytes. Uses incremental save to preserve * existing content and any previous signatures. * * @param fieldName The signature field name. * @param options Signing options (certificate, private key, etc.). * @returns The signed PDF bytes. * * @example * ```ts * const doc = await PdfDocument.load(pdfBytes); * const signedBytes = await doc.sign('Signature1', { * certificate: certDer, * privateKey: keyDer, * reason: 'Document approval', * }); * ``` */ sign(fieldName: string, options: SignOptions): Promise; /** * Get information about all signatures in this document. * * @returns Array of signature info objects. */ getSignatures(): PdfSignatureInfo[]; /** * Verify all signatures in this document. * * @returns Array of verification results. */ verifySignatures(): Promise; /** The outline tree, lazily created. */ private outlineTree; /** * Get the outline (bookmark) tree for this document. * * If no outlines have been added, returns an empty tree. * * @returns The {@link PdfOutlineTree} for this document. */ getOutlines(): PdfOutlineTree; /** * Add a top-level outline (bookmark) entry. * * Convenience method that creates or retrieves the outline tree and * adds a new item pointing to the specified page. * * @param title The display title for the bookmark. * @param pageIndex Zero-based page index to navigate to. * @param options Optional visual style and behaviour settings. * @returns The newly created {@link PdfOutlineItem}. */ addOutline(title: string, pageIndex: number, options?: OutlineItemOptions & { fit?: OutlineDestination["fit"]; top?: number; left?: number; zoom?: number; }): PdfOutlineItem; /** * Replace the outline tree for this document. * * @param outlines The new outline tree. */ setOutlines(outlines: PdfOutlineTree): void; /** Raw XMP metadata string, if set. */ private xmpMetadataString; /** * Get the raw XMP metadata string, or `undefined` if not set. */ getXmpMetadata(): string | undefined; /** * Set raw XMP metadata as an XML string. * * The string should be a valid XMP packet. Use * {@link buildXmpMetadata} from `modern-pdf` to generate one * from standard metadata fields. * * @param xmp The XMP XML string. */ setXmpMetadata(xmp: string): void; /** The document's structure tree (for tagged PDF), if created. */ private structureTree; /** The document's natural language (BCP 47 tag, e.g. "en-US"). */ private documentLanguage; /** * Get the structure tree for this document, or `undefined` if * no structure tree has been created. * * A structure tree is required for tagged PDF / PDF/UA compliance. * * @returns The {@link PdfStructureTree}, or `undefined`. */ getStructureTree(): PdfStructureTree | undefined; /** * Create a new structure tree for this document. * * If a structure tree already exists, it is returned as-is. * Call this to begin making the document accessible (tagged PDF). * * @returns The {@link PdfStructureTree} for this document. */ createStructureTree(): PdfStructureTree; /** * Set the document's natural language. * * This is required by PDF/UA and should be a BCP 47 language tag * (e.g. `"en"`, `"en-US"`, `"de-DE"`, `"ja"`). * * @param lang The BCP 47 language tag. */ setLanguage(lang: string): void; /** * Get the document's natural language, or `undefined` if not set. * * @returns The BCP 47 language tag, or `undefined`. */ getLanguage(): string | undefined; /** * Run accessibility checks on this document. * * Validates the document against PDF/UA requirements and general * accessibility best practices. * * @returns An array of {@link AccessibilityIssue} objects. */ checkAccessibility(): AccessibilityIssue[]; /** Viewer preferences, if set. */ private viewerPrefs; /** Cached PdfViewerPreferences instance. */ private _viewerPrefsInstance?; /** * Get the viewer preferences for this document as a * {@link PdfViewerPreferences} instance with getter/setter pairs. * * If no preferences have been set, a default (empty) instance is * returned. The instance is cached so that repeated calls return * the same object and mutations are preserved. */ getViewerPreferences(): PdfViewerPreferences; /** * Set viewer preferences for this document. * * Controls how the document is displayed when opened in a PDF viewer * (toolbar visibility, window sizing, print options, etc.). * * Accepts either a plain {@link ViewerPreferences} object or a * {@link PdfViewerPreferences} class instance. * * @param prefs The viewer preferences to set. */ setViewerPreferences(prefs: ViewerPreferences | PdfViewerPreferences): void; /** The form instance, lazily created. */ private form; /** * Check whether this document has an AcroForm (interactive form). * * Returns `true` if a form has been created or if the document * was loaded from a PDF that contains an /AcroForm dictionary. */ hasForm(): boolean; /** * Get the interactive form (AcroForm) for this document. * * If the document does not yet have a form, an empty one is created. * The form provides access to all form fields and supports fill, * flatten, and field creation operations. * * @returns The {@link PdfForm} for this document. */ getForm(): PdfForm; /** * Set the form for this document (used when loading parsed PDFs). * @internal */ setForm(form: PdfForm): void; /** * Draw an SVG image onto a page. * * @param pageIndex Zero-based page index. * @param svgString The SVG markup string. * @param options Rendering options (position, size). */ drawSvg(pageIndex: number, svgString: string, options?: SvgRenderOptions): void; /** The layer manager, lazily created. */ private layerManager; /** * Add a new optional content layer. * * @param name The display name for the layer. * @param visible Whether the layer is visible by default. * @returns The newly created {@link PdfLayer}. */ addLayer(name: string, visible?: boolean): PdfLayer; /** * Get all layers in this document. * * @returns An array of {@link PdfLayer} objects. */ getLayers(): PdfLayer[]; /** Attached file references. */ private readonly attachedFiles; /** Filespec refs that must also appear in the catalog `/AF` array (PDF 2.0). */ private readonly associatedAfRefs; /** Document-level JavaScript actions — maps name → script source. */ private readonly javaScripts; /** * Attach a file to this PDF document. * * @param name File name. * @param data File data. * @param mimeType MIME type string. * @param options Optional description. */ attachFile(name: string, data: Uint8Array, mimeType: string, options?: { description?: string | undefined; }): void; /** * Attach a PDF 2.0 **associated file** to this document — an embedded file * with a typed `/AFRelationship` that is referenced from the catalog's `/AF` * array, so the companion data is recognized as associated with the document * (required for PDF/A-3, Factur-X/ZUGFeRD, etc.) rather than merely embedded. * * @param name File name. * @param data File bytes. * @param mimeType MIME type (e.g. `'text/xml'`). * @param relationship The `/AFRelationship` (`Source`/`Data`/`Alternative`/…). * @param options Optional description. * * @example * ```ts * doc.addAssociatedFile('factur-x.xml', xmlBytes, 'text/xml', 'Alternative'); * ``` */ addAssociatedFile(name: string, data: Uint8Array, mimeType: string, relationship: AFRelationship, options?: { description?: string | undefined; }): void; /** * Get all file attachments in this document. * * Note: Currently returns information about files attached via * this API. For parsing attachments from loaded PDFs, use the * lower-level `getAttachments()` function. * * @returns An array of embedded file metadata. */ getAttachments(): EmbeddedFile[]; /** * Add a document-level JavaScript action. * * The script is registered in the catalog's `/Names` dictionary under * the `/JavaScript` name tree. When a conforming viewer opens the * document, scripts listed here are executed automatically (in name * order). * * @param name A unique name for this JavaScript entry. * @param script The JavaScript source code. * * @example * ```ts * doc.addJavaScript('init', 'app.alert("Hello from PDF JavaScript!");'); * ``` */ addJavaScript(name: string, script: string): void; /** * Add a text watermark to all pages in the document. * * @param options Watermark appearance options. */ addWatermark(options: WatermarkOptions): void; /** * Create a soft mask Form XObject that can be used with * {@link PdfPage.applySoftMask}. * * The builder callback receives a {@link SoftMaskBuilder} with methods * for generating grayscale content where white (`1`) represents fully * opaque regions and black (`0`) represents fully transparent regions. * * The returned {@link SoftMaskRef} is passed to * {@link PdfPage.applySoftMask} to activate the mask for subsequent * drawing operations on that page. * * @param width Width of the mask in points. * @param height Height of the mask in points. * @param builder Callback that draws the mask content. * @returns A reference to the soft mask Form XObject. * * @example * ```ts * const mask = doc.createSoftMask(200, 200, (b) => { * // White background = fully opaque * b.drawRectangle(0, 0, 200, 200, 1); * // Black circle = fully transparent hole * b.drawCircle(100, 100, 80, 0); * }); * page.applySoftMask(mask); * page.drawRectangle({ x: 50, y: 50, width: 200, height: 200, color: rgb(1, 0, 0) }); * page.clearSoftMask(); * ``` */ createSoftMask(width: number, height: number, builder: (ops: SoftMaskBuilder) => void): SoftMaskRef; /** * Apply all pending redactions across all pages. * * Redaction marks are added to individual pages using * `page.markForRedaction()`. This method draws the redaction * rectangles on all pages that have pending marks. */ applyRedactions(): void; /** * Create an independent deep copy of this document. * * The copy is produced by serializing the document to bytes and then * re-parsing those bytes. This guarantees that the returned * `PdfDocument` is completely independent — mutations to the copy * do not affect the original, and vice versa. * * @returns A new `PdfDocument` that is a deep copy of this one. * * @example * ```ts * const doc = createPdf(); * doc.addPage(PageSizes.A4); * const clone = await doc.copy(); * clone.addPage(PageSizes.Letter); // does not affect `doc` * ``` */ copy(): Promise; /** * Serialize the document to a `Uint8Array`. * * @param options Compression and serialization options. * @returns The complete PDF file as bytes. */ save(options?: PdfSaveOptions): Promise; /** * Serialize the document as a `ReadableStream`. * * Ideal for streaming responses in edge/serverless environments. * * @param options Compression and serialization options. */ saveAsStream(options?: PdfSaveOptions): ReadableStream; /** * Serialize the document to a `Blob`. * * Convenient for client-side download links. * * @param options Compression and serialization options. */ saveAsBlob(options?: PdfSaveOptions): Promise; /** * Serialize the document to a Base64-encoded string. * * Useful for embedding PDFs in JSON payloads, data URIs, or * transferring over text-only channels. * * @param options Standard save options plus an optional `dataUri` * flag. When `dataUri` is `true`, the returned * string is prefixed with * `data:application/pdf;base64,`. * @returns A Base64-encoded string of the PDF bytes. * * @example * ```ts * const b64 = await doc.saveAsBase64(); * const dataUri = await doc.saveAsBase64({ dataUri: true }); * // dataUri === "data:application/pdf;base64,JVBERi0..." * ``` */ saveAsBase64(options?: PdfSaveOptions & { dataUri?: boolean; }): Promise; /** * Finalize all pages and build the catalog / page tree / info dict. */ private buildStructure; /** * Subset all embedded TrueType fonts. * * Called at save time, after all text has been drawn. For each TTF * font, this: * 1. Calls {@link subsetFont} with the used glyph set * 2. Updates the `/FontFile2` stream data with the (possibly subsetted) font bytes * 3. Updates the `/Length1` in the font file dict * 4. Rebuilds the `/W` (widths) array for the CIDFont dict * 5. Rebuilds the `/ToUnicode` CMap stream * * Since WASM subsetting is not yet available, the fallback returns * the full font unchanged. But the /W array and /ToUnicode CMap * are rebuilt to only include used glyphs, reducing PDF overhead. * * @internal */ private subsetTtfFonts; } /** * Create a new, empty PDF document. * * ```ts * const doc = createPdf(); * ``` */ declare function createPdf(): PdfDocument; //#endregion export { PageEntry as $, rotationMatrix as $n, EmbedPageOptions as $t, signPdf as A, createAnnotation as An, setStrokeColor as Ar, TableRow as At, loadPdf as B, ParseSpeeds as Bn, GradientFill as Bt, attachFile as C, parseSvgTransform as Cn, rgbToCmyk as Cr, DrawTableOptions as Ct, SignOptions as D, PdfAnnotation as Dn, setFillColorGray as Dr, TableCell as Dt, PdfSignatureInfo as E, AnnotationType as En, setFillColorCmyk as Er, PageContent as Et, OutlineDestination as F, StructureType as Fn, setStrokingColor as Fr, QrCodeMatrix as Ft, EncryptOptions as G, Radians as Gn, RadialGradientOptions as Gt, PdfWriter as H, TextRenderingMode as Hn, NormalizedStop as Ht, OutlineItemOptions as I, BlendMode as In, spotColor as Ir, QrCodeOptions as It, decodePermissions as J, degreesToRadians as Jn, buildPatternObjects as Jt, PdfEncryptionHandler as K, concatMatrix as Kn, TilingPatternOptions as Kt, PdfOutlineItem as L, ImageAlignment as Ln, spotResourceName as Lr, encodeQrCode as Lt, ViewerPreferences as M, PdfStructureElement as Mn, setStrokeColorGray as Mr, renderMultiPageTable as Mt, buildViewerPreferencesDict as N, PdfStructureTree as Nn, setStrokeColorRgb as Nr, renderTable as Nt, VisibleSignatureOptions as O, annotationFromDict as On, setFillColorRgb as Or, TableColumn as Ot, parseViewerPreferences as P, StructureElementOptions as Pn, setStrokeColorSpace as Pr, ErrorCorrectionLevel as Pt, DocumentStructure as Q, rotate as Qn, DrawPageOptions as Qt, PdfOutlineTree as R, LineCapStyle as Rn, qrCodeToOperators as Rt, EmbeddedFile as S, parseSvgPath as Sn, rgb as Sr, CellContent as St, getAttachments as T, AnnotationOptions as Tn, setFillColor as Tr, NestedTableContent as Tt, serializePdf as U, Angle as Un, PatternFill as Ut, PdfSaveOptions as V, TextAlignment as Vn, LinearGradientOptions as Vt, EncryptAlgorithm as W, Degrees as Wn, RadialGradientFill as Wt, CatalogOptions as X, radiansToDegrees as Xn, radialGradient as Xt, encodePermissions as Y, radians as Yn, linearGradient as Yt, DocumentMetadata as Z, restoreState as Zn, tilingPattern as Zt, AFRelationship as _, SvgGradientStop as _n, componentsToColor as _r, PageSizes as _t, StandardFonts as a, getRedactionMarks as an, CmykColor as ar, DrawCircleOptions as at, buildAfArray as b, parseSvg as bn, grayscale as br, SoftMaskRef as bt, PdfPluginManager as c, PdfLayerManager as cn, GrayscaleColor as cr, DrawLineOptions as ct, SignatureVerificationResult as d, SvgRenderOptions as dn, applyFillColor as dr, DrawSquareOptions as dt, EmbeddedPdfPage as en, saveState as er, buildCatalog as et, verifySignature as f, drawSvgOnPage as fn, applyStrokeColor as fr, DrawSvgPathOptions as ft, addWatermarkToPage as g, SvgGradient as gn, colorToHex as gr, PageSize as gt, addWatermark as h, SvgElement as hn, colorToComponents as hr, ImageRef as ht, StandardFontName as i, applyRedactions as in, translate as ir, formatPdfDate as it, PdfViewerPreferences as j, AccessibilityIssue as jn, setStrokeColorCmyk as jr, TextRun as jt, getSignatures as k, buildAnnotationDict as kn, setFillingColor as kr, TableRenderResult as kt, PluginDocument as l, beginLayerContent as ln, RgbColor as lr, DrawQrCodeOptions as lt, WatermarkOptions as m, SvgDrawCommand as mn, cmykToRgb as mr, FontRef as mt, PdfDocument as n, RedactionMark as nn, setGraphicsState as nr, buildInfoDict as nt, createPdf as o, markForRedaction as on, Color as or, DrawEllipseOptions as ot, verifySignatures as p, svgToPdfOperators as pn, cmyk as pr, DrawTextOptions as pt, PdfPermissionFlags as q, degrees as qn, buildGradientObjects as qt, SetTitleOptions as r, RedactionOptions as rn, skew as rr, buildPageTree as rt, PdfPlugin as s, PdfLayer as sn, DeviceNColor as sr, DrawImageOptions as st, EmbedFontOptions as t, embedPageAsFormXObject as tn, scale as tr, buildDocumentStructure as tt, PluginPage as u, endLayerContent as un, SpotColor as ur, DrawRectangleOptions as ut, AssociatedFileOptions as v, applySpreadMethod as vn, deviceNColor as vr, PdfPage as vt, buildEmbeddedFilesNameTree as w, AnnotationFlags as wn, setColorSpace as wr, MultiPageTableResult as wt, createAssociatedFile as x, parseSvgColor as xn, hexToColor as xr, TransparencyGroupOptions as xt, AssociatedFileResult as y, interpolateLinearRgb as yn, deviceNResourceName as yr, SoftMaskBuilder as yt, LoadPdfOptions as z, LineJoinStyle as zn, ColorStop as zt }; //# sourceMappingURL=pdfDocument-C7TItmPQ.d.mts.map