import { $ as DrawLineOptions, $n as colorToComponents, $t as PdfLayerManager, A as LoadPdfOptions, An as Angle, At as ColorStop, B as encodePermissions, Bn as rotationMatrix, Bt as linearGradient, C as ViewerPreferences, Cn as BlendMode, Ct as renderMultiPageTable, D as OutlineItemOptions, Dn as ParseSpeeds, Dt as QrCodeOptions, E as OutlineDestination, En as LineJoinStyle, Et as QrCodeMatrix, F as EncryptAlgorithm, Fn as degreesToRadians, Ft as RadialGradientFill, G as buildCatalog, Gn as translate, Gt as EmbeddedPdfPage, H as DocumentMetadata, Hn as scale, Ht as tilingPattern, I as EncryptOptions, In as radians, It as RadialGradientOptions, J as buildPageTree, Jn as GrayscaleColor, Jt as RedactionOptions, K as buildDocumentStructure, Kn as CmykColor, Kt as embedPageAsFormXObject, L as PdfEncryptionHandler, Ln as radiansToDegrees, Lt as TilingPatternOptions, M as PdfSaveOptions, Mn as Radians, Mt as LinearGradientOptions, N as PdfWriter, Nn as concatMatrix, Nt as NormalizedStop, O as PdfOutlineItem, On as TextAlignment, Ot as encodeQrCode, P as serializePdf, Pn as degrees, Pt as PatternFill, Q as DrawImageOptions, Qn as cmyk, Qt as PdfLayer, R as PdfPermissionFlags, Rn as restoreState, Rt as buildGradientObjects, S as PdfViewerPreferences, Sn as StructureType, St as TextRun, T as parseViewerPreferences, Tn as LineCapStyle, Tt as ErrorCorrectionLevel, U as DocumentStructure, Un as setGraphicsState, Ut as DrawPageOptions, V as CatalogOptions, Vn as saveState, Vt as radialGradient, W as PageEntry, Wn as skew, Wt as EmbedPageOptions, X as DrawCircleOptions, Xn as applyFillColor, Xt as getRedactionMarks, Y as formatPdfDate, Yn as RgbColor, Yt as applyRedactions, Z as DrawEllipseOptions, Zn as applyStrokeColor, Zt as markForRedaction, _ as PdfSignatureInfo, _n as createAnnotation, _t as PageContent, a as StandardFonts, an as SvgDrawCommand, ar as setFillColorCmyk, at as FontRef, b as getSignatures, bn as PdfStructureTree, bt as TableRenderResult, c as verifySignature, cn as parseSvgColor, cr as setFillingColor, ct as PageSizes, d as addWatermark, dn as AnnotationFlags, dr as setStrokeColorGray, dt as SoftMaskRef, en as beginLayerContent, er as componentsToColor, et as DrawQrCodeOptions, f as addWatermarkToPage, fn as AnnotationOptions, fr as setStrokeColorRgb, ft as TransparencyGroupOptions, g as getAttachments, gn as buildAnnotationDict, gt as NestedTableContent, h as buildEmbeddedFilesNameTree, hn as annotationFromDict, ht as MultiPageTableResult, i as StandardFontName, in as svgToPdfOperators, ir as setFillColor, it as DrawTextOptions, j as loadPdf, jn as Degrees, jt as GradientFill, k as PdfOutlineTree, kn as TextRenderingMode, kt as qrCodeToOperators, l as verifySignatures, ln as parseSvgPath, lr as setStrokeColor, lt as PdfPage, m as attachFile, mn as PdfAnnotation, mr as setStrokingColor, mt as DrawTableOptions, n as PdfDocument, nn as SvgRenderOptions, nr as rgb, nt as DrawSquareOptions, o as createPdf, on as SvgElement, or as setFillColorGray, ot as ImageRef, p as EmbeddedFile, pn as AnnotationType, pr as setStrokeColorSpace, pt as CellContent, q as buildInfoDict, qn as Color, qt as RedactionMark, r as SetTitleOptions, rn as drawSvgOnPage, rr as setColorSpace, rt as DrawSvgPathOptions, s as SignatureVerificationResult, sn as parseSvg, sr as setFillColorRgb, st as PageSize, t as EmbedFontOptions, tn as endLayerContent, tr as grayscale, tt as DrawRectangleOptions, u as WatermarkOptions, un as parseSvgTransform, ur as setStrokeColorCmyk, ut as SoftMaskBuilder, v as SignOptions, vn as AccessibilityIssue, vt as TableCell, w as buildViewerPreferencesDict, wn as ImageAlignment, wt as renderTable, x as signPdf, xn as StructureElementOptions, xt as TableRow, y as VisibleSignatureOptions, yn as PdfStructureElement, yt as TableColumn, z as decodePermissions, zn as rotate, zt as buildPatternObjects } from "./pdfDocument-Bi-NoyXv.mjs"; import { C as PdfRef, E as RegistryEntry, S as PdfObjectRegistry, T as PdfString, _ as PdfDict, a as PdfListboxField, b as PdfNumber, c as PdfCheckboxField, d as FieldType, f as PdfField, g as PdfBool, h as PdfArray, i as PdfButtonField, l as PdfTextField, m as ByteWriter, n as RefResolver, o as PdfDropdownField, p as WidgetAnnotationHost, r as PdfSignatureField, s as PdfRadioGroup, t as PdfForm, u as FieldFlags, v as PdfName, w as PdfStream, x as PdfObject, y as PdfNull } from "./pdfForm-BiyNtYem.mjs"; import { A as movePage, C as copyPages, D as cropPage, E as CropBox, F as rotateAllPages, I as rotatePage, L as asNumber, M as removePages, N as resizePage, O as getPageSize, P as reversePages, R as asPDFName, S as PageRange, T as splitPdf, _ as LayoutSinglelineResult, a as FontEmbeddingResult, b as layoutMultilineText, c as SubsetCmap, d as extractMetrics, f as ComputeFontSizeOptions, g as LayoutSinglelineOptions, h as LayoutMultilineResult, i as FontDescriptorData, j as removePage, k as insertPage, l as SubsetResult, m as LayoutMultilineOptions, n as CIDSystemInfoData, o as Type0FontData, p as LayoutCombedOptions, r as EmbeddedFont, s as WidthEntry, t as CIDFontData, u as FontMetrics, v as computeFontSize, w as mergePdfs, x as layoutSinglelineText, y as layoutCombedText, z as asPDFNumber } from "./fontEmbed-DlVnVCZU.mjs"; import { a as ListboxAppearanceOptions, c as TextAppearanceOptions, d as generateDropdownAppearance, f as generateListboxAppearance, h as generateTextAppearance, i as DropdownAppearanceOptions, l as generateButtonAppearance, m as generateSignatureAppearance, n as ButtonAppearanceOptions, o as RadioAppearanceOptions, p as generateRadioAppearance, r as CheckboxAppearanceOptions, s as SignatureAppearanceOptions, t as AppearanceProviderFor, u as generateCheckboxAppearance } from "./fieldAppearance-C8PoLFSc.mjs"; import { _ as parseContentStream, a as ImageInfo, c as PdfParseError, d as TextExtractionOptions, f as TextItem, g as Operand, h as ContentStreamOperator, i as analyzeImages, l as formatHexContext, m as extractTextWithPositions, n as AnalyzeImagesOptions, o as decodeImageStream, p as extractText, r as ImageAnalysis, s as extractImages, t as AnalysisReport, u as decodeStream } from "./compressionAnalysis-Ch7t-HXn.mjs"; //#region \0rolldown/runtime.js //#endregion //#region src/core/incrementalWriter.d.ts /** * Result of an incremental save operation. */ interface IncrementalSaveResult { /** The complete PDF file bytes (original + appended data). */ readonly bytes: Uint8Array; /** Byte offset of the new xref section in the output. */ readonly newXrefOffset: number; } /** * Tracks which objects have been added or modified since the document * was loaded. Only these objects are written during an incremental save. */ declare class ChangeTracker { /** Set of object numbers that are new (not in the original file). */ private readonly newObjects; /** Set of object numbers that existed but have been modified. */ private readonly modifiedObjects; /** The highest object number from the original file. */ private readonly originalMaxObjNum; constructor(originalMaxObjNum: number); /** * Mark an object as new (did not exist in the original file). */ markNew(objectNumber: number): void; /** * Mark an object as modified (existed in the original file). */ markModified(objectNumber: number): void; /** * Check if an object is new or modified. */ isChanged(objectNumber: number): boolean; /** * Get all changed object numbers (new + modified). */ getChangedObjects(): Set; /** * Get the count of changed objects. */ get changedCount(): number; } /** * Perform an incremental save of a PDF document. * * Takes the original file bytes and a registry of objects (some new, * some modified), and appends only the changed objects plus a new xref * section and trailer. * * The resulting bytes form a valid PDF file that preserves the original * content byte-for-byte and appends the modifications. * * @param originalBytes The original PDF file bytes (unmodified). * @param registry The object registry containing all objects * (original + new/modified). * @param structure Document structure references (catalog, info, pages). * @param changedObjects Set of object numbers that are new or modified. * @param options Optional save options (compression, etc.). * @returns The complete incremental save result. * * @example * ```ts * const result = saveIncremental(originalBytes, registry, structure, changedObjects); * await writeFile('output.pdf', result.bytes); * ``` */ declare function saveIncremental(originalBytes: Uint8Array, registry: PdfObjectRegistry, structure: DocumentStructure, changedObjects: Set, options?: PdfSaveOptions): IncrementalSaveResult; /** * Perform an incremental save given the original bytes and a PdfDocument. * * This is a convenience wrapper that builds the document structure, * determines which objects have changed, and calls `saveIncremental`. * * @param originalBytes The original PDF file bytes. * @param doc The modified PdfDocument. * @param options Optional save options. * @returns The incremental save result. */ declare function saveDocumentIncremental(originalBytes: Uint8Array, doc: PdfDocument, options?: PdfSaveOptions): Promise; //#endregion //#region src/assets/font/otfDetect.d.ts /** * @module assets/font/otfDetect * * Detection helpers for distinguishing CFF-based OpenType fonts from * TrueType-based fonts based on their magic bytes. * * CFF-based OpenType fonts (OTF) start with the ASCII bytes "OTTO". * TrueType fonts start with 0x00010000 or the ASCII bytes "true". */ /** * Detect whether font data is an OpenType font with CFF outlines. * CFF-based OpenType fonts start with the ASCII bytes "OTTO". * TrueType-based OpenType fonts start with 0x00010000 or "true". * * @param data - Raw font file bytes. * @returns `true` if the font is a CFF-based OpenType font. */ declare function isOpenTypeCFF(data: Uint8Array): boolean; /** * Detect whether font data is a TrueType font. * * @param data - Raw font file bytes. * @returns `true` if the font is a TrueType font. */ declare function isTrueType(data: Uint8Array): boolean; //#endregion //#region src/core/operators/graphics.d.ts /** * @module core/operators/graphics * * PDF path-construction and painting operators — produces the raw operator * strings that appear inside a page content stream. * * Reference: PDF 1.7 spec, §8.5 (Path Construction & Painting). */ /** * Append a rectangle to the current path (`re`). * * @param x Lower-left x coordinate. * @param y Lower-left y coordinate. * @param width Width of the rectangle. * @param height Height of the rectangle. */ declare function rectangle(x: number, y: number, width: number, height: number): string; /** * Begin a new sub-path by moving the current point (`m`). * * @param x Target x coordinate. * @param y Target y coordinate. */ declare function moveTo(x: number, y: number): string; /** * Append a straight line segment from the current point to `(x, y)` (`l`). * * @param x Target x coordinate. * @param y Target y coordinate. */ declare function lineTo(x: number, y: number): string; /** * Append a cubic Bezier curve to the current path (`c`). * * The curve extends from the current point to `(x3, y3)`, using * `(x1, y1)` and `(x2, y2)` as control points. */ declare function curveTo(x1: number, y1: number, x2: number, y2: number, x3: number, y3: number): string; /** * Append a cubic Bezier curve where the first control point coincides * with the current point (`v`). */ declare function curveToInitial(x2: number, y2: number, x3: number, y3: number): string; /** * Append a cubic Bezier curve where the second control point coincides * with the final point (`y`). */ declare function curveToFinal(x1: number, y1: number, x3: number, y3: number): string; /** * Close the current sub-path by appending a straight line from the * current point to the starting point (`h`). */ declare function closePath(): string; /** * Stroke the path (`S`). */ declare function stroke(): string; /** * Close and stroke the path — equivalent to `h S` (`s`). */ declare function closeAndStroke(): string; /** * Fill the path using the non-zero winding rule (`f`). */ declare function fill(): string; /** * Fill the path using the even-odd rule (`f*`). */ declare function fillEvenOdd(): string; /** * Fill and then stroke the path (non-zero winding) (`B`). */ declare function fillAndStroke(): string; /** * Fill (even-odd) and then stroke the path (`B*`). */ declare function fillEvenOddAndStroke(): string; /** * Close, fill, and stroke the path (`b`). */ declare function closeFillAndStroke(): string; /** * Close, fill (even-odd), and stroke the path (`b*`). */ declare function closeFillEvenOddAndStroke(): string; /** * End the path without filling or stroking — a no-op painting operator * typically used with clipping (`n`). */ declare function endPath(): string; /** * Intersect the clipping path with the current path using the non-zero * winding rule (`W`). Must be followed by a painting operator. */ declare function clip(): string; /** * Intersect the clipping path with the current path using the even-odd * rule (`W*`). */ declare function clipEvenOdd(): string; /** * Set the line width (`w`). * * @param width Line width in user-space units. */ declare function setLineWidth(width: number): string; /** * Set the line cap style (`J`). * * | Value | Style | * |-------|-------------| * | 0 | Butt cap | * | 1 | Round cap | * | 2 | Square cap | */ declare function setLineCap(style: 0 | 1 | 2): string; /** * Set the line join style (`j`). * * | Value | Style | * |-------|--------------| * | 0 | Miter join | * | 1 | Round join | * | 2 | Bevel join | */ declare function setLineJoin(style: 0 | 1 | 2): string; /** * Set the miter limit (`M`). * * @param limit Maximum ratio of miter length to line width. */ declare function setMiterLimit(limit: number): string; /** * Set the line dash pattern (`d`). * * @param dashArray Array of dash and gap lengths. * @param dashPhase Offset into the dash pattern. */ declare function setDashPattern(dashArray: readonly number[], dashPhase: number): string; /** * Set the flatness tolerance (`i`). * * @param flatness Maximum distance in device pixels between the * mathematical path and the rendered approximation. */ declare function setFlatness(flatness: number): string; /** * Produce the path operators for an approximate circle (4 cubic Bezier * curves). Does NOT include the painting operator — call {@link stroke}, * {@link fill}, or {@link fillAndStroke} afterwards. * * @param cx Centre x. * @param cy Centre y. * @param radius Radius. */ declare function circlePath(cx: number, cy: number, radius: number): string; /** * Produce the path operators for an approximate ellipse. * * @param cx Centre x. * @param cy Centre y. * @param rx Horizontal radius. * @param ry Vertical radius. */ declare function ellipsePath(cx: number, cy: number, rx: number, ry: number): string; //#endregion //#region src/core/operators/text.d.ts /** * @module core/operators/text * * PDF text operators — generates the raw operator strings that appear * inside a page content stream. Every function returns a plain string * (one or more PDF operators terminated by '\n'). * * Reference: PDF 1.7 spec, §9.4 (Text Objects) & §9.3 (Text State). */ /** * Begin a text object (`BT`). * * All text-showing operators must appear between a `BT` / `ET` pair. */ declare function beginText(): string; /** * End the current text object (`ET`). */ declare function endText(): string; /** * Select font and size (`Tf`). * * @param fontName Resource name of the font (e.g. `/F1`). The leading * slash is added automatically if absent. * @param size Font size in user-space units. */ declare function setFont(fontName: string, size: number): string; /** * Set the font size only — alias for `setFont` when the font has already * been selected. * * @param fontName Resource name of the font. * @param size Font size in user-space units. */ declare function setFontSize(fontName: string, size: number): string; /** * Set the text leading — the vertical distance between baselines of * consecutive lines (`TL`). * * @param leading Leading value in user-space units. */ declare function setLeading(leading: number): string; /** * Set the character spacing (`Tc`). * * @param spacing Extra space (in unscaled text-space units) to add * between each pair of characters. */ declare function setCharacterSpacing(spacing: number): string; /** * Set the word spacing (`Tw`). * * @param spacing Extra space (in unscaled text-space units) to add * when a space character (0x20) is encountered. */ declare function setWordSpacing(spacing: number): string; /** * Set the text rise (super / subscript offset) (`Ts`). * * @param rise Distance, in unscaled text-space units, to move the * baseline up (positive) or down (negative). */ declare function setTextRise(rise: number): string; /** * Set the text rendering mode (`Tr`). * * | Value | Meaning | * |-------|--------------------| * | 0 | Fill | * | 1 | Stroke | * | 2 | Fill then stroke | * | 3 | Invisible | * | 4 | Fill and clip | * | 5 | Stroke and clip | * | 6 | Fill, stroke, clip | * | 7 | Clip | */ declare function setTextRenderingMode(mode: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7): string; /** * Set the text matrix and text line matrix (`Tm`). * * The six operands form a standard 3 × 3 transformation matrix: * * ``` * [ a b 0 ] * [ c d 0 ] * [ tx ty 1 ] * ``` * * @param a Horizontal scaling. * @param b Rotation component (sin). * @param c Rotation component (−sin). * @param d Vertical scaling. * @param tx Horizontal translation. * @param ty Vertical translation. */ declare function setTextMatrix(a: number, b: number, c: number, d: number, tx: number, ty: number): string; /** * Move to the start of the next line, offset by `(tx, ty)` (`Td`). * * @param tx Horizontal offset from the start of the current line. * @param ty Vertical offset from the start of the current line. */ declare function moveText(tx: number, ty: number): string; /** * Move to the start of the next line, offset by `(tx, ty)`, and set the * leading to `-ty` (`TD`). * * Equivalent to: `-ty TL` followed by `tx ty Td`. */ declare function moveTextSetLeading(tx: number, ty: number): string; /** * Move to the start of the next line (`T*`). * * Equivalent to `0 -TL Td` where TL is the current leading. */ declare function nextLine(): string; /** * Show a text string (`Tj`). * * @param text The text to display. Special characters are escaped. */ declare function showText(text: string): string; /** * Show a text string using a hex-encoded string (`<…> Tj`). * * Used for CIDFont Type 2 (TrueType) fonts where each character is * encoded as a 2-byte glyph ID in hexadecimal. * * @param hex The hex-encoded glyph IDs (e.g. `"00480065006C006C006F"`). */ declare function showTextHex(hex: string): string; /** * Show one or more text strings with individual glyph positioning (`TJ`). * * Each element of `items` is either: * - a `string` — literal text to show, or * - a `number` — a horizontal adjustment in thousandths of a unit of text * space (negative = move right, positive = move left). * * @param items Array of strings and numeric adjustments. */ declare function showTextArray(items: ReadonlyArray): string; /** * Show a text string and move to the next line (`'`). * * Equivalent to `T*` followed by `string Tj`. */ declare function showTextNextLine(text: string): string; /** * Show a text string, set word and character spacing, and move to the * next line (`"`). * * @param wordSpacing Word spacing. * @param charSpacing Character spacing. * @param text Text to show. */ declare function showTextWithSpacing(wordSpacing: number, charSpacing: number, text: string): string; //#endregion //#region src/core/operators/image.d.ts /** * @module core/operators/image * * PDF XObject invocation operators — places an image (or form) XObject * on the page. * * Reference: PDF 1.7 spec, §8.8 (External Objects). */ /** * Invoke a named XObject (`Do`). * * The XObject must be listed in the page's `/Resources /XObject` dictionary * under `name`. The leading slash is added automatically if absent. * * This is the fundamental operator for placing images on a page. Callers * should first set up the transformation matrix (via `cm`) so that the * unit square `[0,0]–[1,1]` maps to the desired page rectangle. * * @param name Resource name (e.g. `Im1` or `/Im1`). */ declare function drawXObject(name: string): string; /** * Produce the full operator sequence to draw an image XObject at the * given position and dimensions. * * This emits: * 1. `q` — save graphics state * 2. `cm` — transformation matrix that maps the image's unit square * to the rectangle `(x, y, width, height)` * 3. `Do` — paint the XObject * 4. `Q` — restore graphics state * * @param name Resource name of the XObject (e.g. `Im1`). * @param x Lower-left x coordinate of the image on the page. * @param y Lower-left y coordinate of the image on the page. * @param width Rendered width of the image. * @param height Rendered height of the image. */ declare function drawImageXObject(name: string, x: number, y: number, width: number, height: number): string; /** * Produce the full operator sequence to draw an image XObject with an * arbitrary 6-component transformation matrix. * * The matrix maps the unit square to the target parallelogram: * * ``` * [ a b 0 ] * [ c d 0 ] * [ tx ty 1 ] * ``` * * @param name Resource name of the XObject. * @param a Horizontal scaling / rotation. * @param b Rotation / skew component. * @param c Rotation / skew component. * @param d Vertical scaling / rotation. * @param tx Horizontal translation. * @param ty Vertical translation. */ declare function drawImageWithMatrix(name: string, a: number, b: number, c: number, d: number, tx: number, ty: number): string; //#endregion //#region src/accessibility/markedContent.d.ts /** * Represents a marked-content scope — provides the operator strings * needed to open and close the scope in a content stream. */ interface MarkedContentScope { /** The marked-content ID linking to the structure tree. */ readonly mcid: number; /** The structure type tag. */ readonly tag: string; /** * Return the PDF operator string that begins this marked-content * sequence. For tagged content with an MCID, this produces a * `BDC` (begin marked-content with properties) operator. */ begin(): string; /** * Return the PDF operator string that ends this marked-content * sequence (`EMC`). */ end(): string; } /** * Generate a `BMC` (begin marked content) operator with just a tag. * * This is the simplest form of marked content — no properties dict. * Produces: `/ BMC\n` * * @param tag The marked-content tag (e.g. `"Span"`, `"Artifact"`). * @returns The PDF operator string. */ declare function beginMarkedContent(tag: string): string; /** * Generate a `BDC` (begin marked-content with properties) operator. * * The properties dictionary is serialized inline. This is used when * you need to associate additional data (like MCID) with the marked * content. * * Produces: `/ <> BDC\n` * * @param tag The marked-content tag. * @param properties Key-value pairs for the properties dictionary. * @returns The PDF operator string. */ declare function beginMarkedContentWithProperties(tag: string, properties: Record): string; /** * Generate an `EMC` (end marked content) operator. * * @returns The PDF operator string. */ declare function endMarkedContent(): string; /** * Generate a `BDC` operator for a structure-tagged marked-content * sequence with an MCID. * * This is the most common form used in tagged PDF: it begins a * content region associated with a specific structure element via * the MCID. * * Produces: `/ <> BDC\n` * * @param tag The structure type (e.g. `"P"`, `"H1"`, `"Span"`). * @param mcid The marked-content identifier. * @returns The PDF operator string. */ declare function beginMarkedContentSequence(tag: StructureType, mcid: number): string; /** * Wrap existing content-stream operators in a marked-content sequence. * * This is a convenience function that prepends a `BDC` operator and * appends an `EMC` operator around the given operator string. * * @param operators The existing PDF operator string(s) to wrap. * @param tag The structure type tag. * @param mcid The marked-content identifier. * @returns The wrapped operator string. */ declare function wrapInMarkedContent(operators: string, tag: StructureType, mcid: number): string; /** * Create a {@link MarkedContentScope} object for a given tag and MCID. * * The scope provides `begin()` and `end()` methods to generate the * matching operator strings. This is useful when you want to * incrementally build content between the markers. * * @param tag The structure type tag. * @param mcid The marked-content identifier. * @returns A {@link MarkedContentScope} object. */ declare function createMarkedContentScope(tag: StructureType, mcid: number): MarkedContentScope; /** * Generate an `Artifact` marked-content operator for content that is * not part of the document's logical structure (e.g. page numbers, * headers, footers, decorative borders). * * Produces: `/Artifact BMC\n` * * @returns The PDF operator string. */ declare function beginArtifact(): string; /** * Generate an `Artifact` BDC operator with properties specifying the * artifact type and other attributes. * * @param artifactType The type of artifact: `"Pagination"`, * `"Layout"`, or `"Background"`. * @param subtype Optional subtype (e.g. `"Header"`, `"Footer"`, * `"Watermark"`). * @returns The PDF operator string. */ declare function beginArtifactWithType(artifactType: 'Pagination' | 'Layout' | 'Background', subtype?: string): string; /** * End an artifact (alias for {@link endMarkedContent}). * * @returns The PDF operator string (`EMC\n`). */ declare function endArtifact(): string; //#endregion //#region src/core/operators/index.d.ts /** * A first-class representation of a single PDF content-stream operator. * * In pdf-lib, operators are typed objects rather than raw strings. This * class provides the same capability while remaining interoperable with * the string-based operator functions above. * * ```ts * const op = PDFOperator.of('m', 100, 200); // moveTo(100, 200) * page.pushOperators(op.toString()); * ``` */ declare class PDFOperator { /** The PDF operator name. */ readonly name: string; /** The operands for this operator. */ readonly operands: readonly (number | string)[]; /** * Create a new operator. * * @param name The PDF operator name (e.g. `'m'`, `'l'`, `'re'`, `'Tj'`). * @param operands Numeric, string, or name operands. */ static of(name: string, ...operands: (number | string)[]): PDFOperator; private constructor(); /** * Serialize this operator to its PDF content-stream representation. * * @returns A string like `"100 200 m\n"`. */ toString(): string; } //#endregion //#region src/core/pdfStream.d.ts /** * A PDF writer that produces a `ReadableStream`. * * Usage: * ```ts * const streamWriter = new PdfStreamWriter(registry, structure, options); * const readable = streamWriter.toReadableStream(); * // Pipe or consume the readable stream * ``` * * The stream handles back-pressure automatically via the underlying * `TransformStream`. */ declare class PdfStreamWriter { /** All indirect objects. */ private readonly registry; /** Document structure references. */ private readonly structure; private readonly compress; private readonly compressionLevel; private readonly useWasm; constructor(/** All indirect objects. */ registry: PdfObjectRegistry, /** Document structure references. */ structure: DocumentStructure, options?: PdfSaveOptions); /** * Create a `ReadableStream` that emits the complete PDF. * * The stream respects back-pressure: it will not produce data faster * than the consumer can handle. */ toReadableStream(): ReadableStream; private pumpInto; private writeHeader; private writeBody; private compressStream; private writeXref; private writeTrailer; } //#endregion //#region src/metadata/xmpMetadata.d.ts /** * Build an XMP metadata XML string from document metadata. * * The output is a complete XMP packet including: * - `` header * - `` root element * - RDF description with Dublin Core, XMP, and PDF properties * - `` trailer * * @param meta Document metadata fields. * @returns The complete XMP XML string. */ declare function buildXmpMetadata(meta: DocumentMetadata): string; /** * Parse XMP metadata XML string into document metadata fields. * * This is a lightweight regex-based parser that handles the standard * XMP properties used in PDF files. It does not require a full XML * parser, keeping the library dependency-free. * * @param xmpString The raw XMP XML string. * @returns Partial document metadata extracted from the XMP. */ declare function parseXmpMetadata$1(xmpString: string): Partial; /** * Create an XMP metadata stream suitable for embedding in a PDF * catalog's `/Metadata` entry. * * The stream is created with: * - `/Type /Metadata` * - `/Subtype /XML` * - The XMP XML as uncompressed stream data * * @param meta Document metadata. * @param registry Object registry for allocating a reference. * @returns The indirect reference to the metadata stream. */ declare function createXmpStream(meta: DocumentMetadata, registry: PdfObjectRegistry): PdfRef; //#endregion //#region src/accessibility/accessibilityChecker.d.ts /** * Check a PDF document for accessibility issues. * * This function examines the document's structure tree, metadata, and * page content to identify potential accessibility problems. It returns * an array of {@link AccessibilityIssue} objects, each describing a * specific issue with its severity, code, and human-readable message. * * @param doc The PDF document to check. * @returns An array of accessibility issues (empty if no issues found). * * @example * ```ts * import { createPdf } from 'modern-pdf-lib'; * import { checkAccessibility } from 'modern-pdf-lib/accessibility'; * * const doc = createPdf(); * const issues = checkAccessibility(doc); * for (const issue of issues) { * console.log(`[${issue.severity}] ${issue.code}: ${issue.message}`); * } * ``` */ declare function checkAccessibility(doc: PdfDocument): AccessibilityIssue[]; /** * Generate a summary of accessibility issues by severity. * * @param issues The issues to summarize. * @returns An object with counts per severity level. */ declare function summarizeIssues(issues: readonly AccessibilityIssue[]): { errors: number; warnings: number; infos: number; total: number; }; /** * Check whether a set of issues contains any errors (severity = "error"). * * @param issues The issues to check. * @returns `true` if there are no errors. */ declare function isAccessible(issues: readonly AccessibilityIssue[]): boolean; //#endregion //#region src/accessibility/pdfUaValidator.d.ts /** * PDF/UA conformance level. * * Currently only PDF/UA-1 is supported. PDF/UA-2 (ISO 14289-2) * may be added in a future release. */ type PdfUaLevel = 'UA1'; /** * A single PDF/UA validation error — a must-fix violation. */ interface PdfUaError { /** Machine-readable error code (e.g. `"UA-STRUCT-001"`). */ readonly code: string; /** Human-readable description of the violation. */ readonly message: string; /** The ISO 14289-1 clause reference, if applicable. */ readonly clause?: string | undefined; /** The structure element related to the error, if any. */ readonly element?: PdfStructureElement | undefined; /** Zero-based page index, if the issue is page-specific. */ readonly pageIndex?: number | undefined; } /** * A single PDF/UA validation warning — a best-practice recommendation. */ interface PdfUaWarning { /** Machine-readable warning code (e.g. `"UA-WARN-001"`). */ readonly code: string; /** Human-readable recommendation. */ readonly message: string; /** The structure element related to the warning, if any. */ readonly element?: PdfStructureElement | undefined; /** Zero-based page index, if the warning is page-specific. */ readonly pageIndex?: number | undefined; } /** * Result of a PDF/UA validation check. */ interface PdfUaValidationResult { /** Whether the document passes all PDF/UA requirements (no errors). */ readonly valid: boolean; /** The PDF/UA conformance level checked against. */ readonly level: PdfUaLevel; /** Must-fix violations that prevent compliance. */ readonly errors: PdfUaError[]; /** Best-practice recommendations. */ readonly warnings: PdfUaWarning[]; } /** * Result of the {@link enforcePdfUa} auto-fix pass. */ interface PdfUaEnforcementResult { /** Actions that were successfully applied. */ readonly fixed: string[]; /** Issues that could not be auto-fixed and require manual attention. */ readonly unfixable: PdfUaError[]; } /** * Validate a PDF document against PDF/UA-1 (ISO 14289-1) requirements. * * Performs the following checks: * 1. Structure tree presence (/StructTreeRoot, /MarkInfo) * 2. Document language (/Lang) * 3. Document title and /DisplayDocTitle * 4. Heading hierarchy (sequential, no skips) * 5. Alt text on all illustration elements (Figure, Formula, Form) * 6. Table header cells (TH) with scope * 7. List structure (L/LI/Lbl/LBody) * 8. Reading order via structure tree * 9. Font embedding (no unembedded standard 14 fonts) * 10. Color contrast (AA: 4.5:1, AAA: 7:1) * 11. Bookmarks for navigation * 12. Tab order (/Tabs /S) on pages * * @param doc The PDF document to validate. * @param level The PDF/UA conformance level (default: `'UA1'`). * @returns A {@link PdfUaValidationResult} with errors and warnings. * * @example * ```ts * import { createPdf } from 'modern-pdf-lib'; * import { validatePdfUa } from 'modern-pdf-lib/accessibility'; * * const doc = createPdf(); * const result = validatePdfUa(doc); * if (!result.valid) { * for (const err of result.errors) { * console.error(`[${err.code}] ${err.message}`); * } * } * ``` */ declare function validatePdfUa(doc: PdfDocument, level?: PdfUaLevel): PdfUaValidationResult; /** * Auto-fix PDF/UA issues that can be corrected programmatically. * * Applies the following corrections when the relevant requirement is * not already satisfied: * - Sets `/Lang` to `'en'` if the document has no language. * - Sets the document title to `'Untitled'` if missing, and enables * `/DisplayDocTitle` in viewer preferences. * - Adds `/MarkInfo` by creating a structure tree if none exists. * - Sets `/Tabs /S` (structure order) on every page. * * Returns a result listing what was fixed and what remains unfixable * (e.g. missing alt text, heading skips — those require manual * content changes). * * @param doc The PDF document to fix in-place. * @returns A {@link PdfUaEnforcementResult} describing what was done. * * @example * ```ts * import { createPdf } from 'modern-pdf-lib'; * import { enforcePdfUa, validatePdfUa } from 'modern-pdf-lib/accessibility'; * * const doc = createPdf(); * doc.addPage(); * const result = enforcePdfUa(doc); * console.log('Fixed:', result.fixed); * console.log('Unfixable:', result.unfixable.length); * ``` */ declare function enforcePdfUa(doc: PdfDocument): PdfUaEnforcementResult; //#endregion //#region src/crypto/keyDerivation.d.ts /** * The subset of encryption dictionary values needed by key derivation. */ interface EncryptDictValues { /** /V value: algorithm version (1, 2, 4, or 5). */ version: number; /** /R value: revision number (2, 3, 4, 5, or 6). */ revision: number; /** /Length value in bits (40-256, default 40). */ keyLength: number; /** /O value: owner key (32 bytes for R<=4, 48 bytes for R>=5). */ ownerKey: Uint8Array; /** /U value: user key (32 bytes for R<=4, 48 bytes for R>=5). */ userKey: Uint8Array; /** /P value: permissions integer. */ permissions: number; /** /OE value: owner encryption key (32 bytes, R>=5 only). */ ownerEncryptionKey?: Uint8Array | undefined; /** /UE value: user encryption key (32 bytes, R>=5 only). */ userEncryptionKey?: Uint8Array | undefined; /** /Perms value: encrypted permissions (16 bytes, R>=5 only). */ perms?: Uint8Array | undefined; /** /EncryptMetadata: whether to encrypt the /Metadata stream. */ encryptMetadata: boolean; } /** * Compute the file encryption key from a password and encryption dict. * * Tries the password as both user and owner password. Returns the key * on the first successful match, or throws if neither works. * * Results are cached so that re-opening the same PDF with the same * password skips the expensive key derivation. * * @param password The password to try. * @param dict Encryption dictionary values. * @param fileId The first element of the /ID array (unused for R>=5). * @returns The file encryption key. * @throws If the password is incorrect. */ declare function computeFileEncryptionKey(password: string, dict: EncryptDictValues, fileId: Uint8Array): Promise; /** * Verify a user password against the /U value in the encryption dict. * * For R=2: Compare the entire 32 bytes. * For R=3/4: Compare only the first 16 bytes (the rest is arbitrary). * * @param password The password to verify. * @param dict Encryption dictionary values. * @param fileId The first element of the /ID array. * @returns True if the password is correct. */ declare function verifyUserPassword(password: string, dict: EncryptDictValues, fileId: Uint8Array): Promise; /** * Verify an owner password against the /O value in the encryption dict. * * For R=2-4: Recover the user password from /O using the owner password, * then verify it can produce the correct /U. * * @param password The owner password to verify. * @param dict Encryption dictionary values. * @param fileId The first element of the /ID array. * @returns True if the password is the correct owner password. */ declare function verifyOwnerPassword(password: string, dict: EncryptDictValues, fileId: Uint8Array): Promise; //#endregion //#region src/crypto/md5.d.ts /** * @module crypto/md5 * * Pure-JavaScript MD5 hash implementation. * * Produces a 16-byte (128-bit) digest from arbitrary binary input. * Used in PDF encryption key derivation (Algorithm 2, per-object keys) * where MD5 is required by the spec. * * Operates exclusively on `Uint8Array` -- no Node.js `Buffer` or * `crypto` module dependency, so it runs in every JavaScript runtime. * * Reference: RFC 1321 (The MD5 Message-Digest Algorithm). */ /** * Compute the MD5 hash of the given data. * * @param data Input bytes. * @returns A 16-byte Uint8Array containing the MD5 digest. */ declare function md5(data: Uint8Array): Uint8Array; //#endregion //#region src/crypto/rc4.d.ts /** * @module crypto/rc4 * * Pure-JavaScript RC4 (Rivest Cipher 4) implementation. * * RC4 is a symmetric stream cipher: the same function encrypts and * decrypts. It is required for legacy PDF encryption (V=1 R=2 with * 40-bit keys, V=2 R=3 with 128-bit keys). * * Operates exclusively on `Uint8Array` -- no Node.js dependencies. * * Note: RC4 is considered cryptographically weak. It is implemented * here solely for backward compatibility with older PDF files. */ /** * Encrypt or decrypt data using the RC4 stream cipher. * * RC4 is symmetric: `rc4(key, rc4(key, data))` returns the original data. * * @param key The encryption key (1-256 bytes). * @param data The data to encrypt or decrypt. * @returns The transformed data (same length as input). */ declare function rc4(key: Uint8Array, data: Uint8Array): Uint8Array; //#endregion //#region src/crypto/aes.d.ts /** * @module crypto/aes * * AES-CBC encryption and decryption using the Web Crypto API. * * Supports AES-128 (16-byte key) and AES-256 (32-byte key) in CBC mode * with PKCS#7 padding. The IV is handled as follows: * * - **Encryption**: If no IV is provided, a random 16-byte IV is * generated. The IV is prepended to the ciphertext output. * - **Decryption**: The first 16 bytes of the input are treated as the * IV; the remainder is the ciphertext. * * Uses `globalThis.crypto.subtle` which is available in: * - Node.js 18+ (via the built-in Web Crypto API) * - All modern browsers * - Deno, Bun, Cloudflare Workers * * No pure-JS fallback is provided since Web Crypto is universal in all * supported runtimes. * * Reference: PDF spec SS7.6 (Encryption), AES-CBC mode per NIST SP 800-38A. */ /** * Encrypt data using AES-CBC with PKCS#7 padding. * * The returned ciphertext has the 16-byte IV prepended: * `[IV (16 bytes)] [ciphertext (N bytes)]` * * Web Crypto's AES-CBC implementation automatically applies PKCS#7 * padding during encryption and removes it during decryption. * * @param key AES key: 16 bytes (AES-128) or 32 bytes (AES-256). * @param data Plaintext data to encrypt. * @param iv Optional 16-byte initialization vector. If omitted, a * random IV is generated. * @returns IV + ciphertext as a single Uint8Array. */ declare function aesEncryptCBC(key: Uint8Array, data: Uint8Array, iv?: Uint8Array | undefined): Promise; /** * Decrypt data using AES-CBC with PKCS#7 padding. * * Expects the first 16 bytes to be the IV, followed by the ciphertext. * * @param key AES key: 16 bytes (AES-128) or 32 bytes (AES-256). * @param data IV (16 bytes) + ciphertext. * @returns The decrypted plaintext. */ declare function aesDecryptCBC(key: Uint8Array, data: Uint8Array): Promise; //#endregion //#region src/crypto/sha256.d.ts /** * @module crypto/sha256 * * SHA-256/384/512 hashing via the Web Crypto API. * * Uses `globalThis.crypto.subtle.digest(...)` which is available in * Node.js 18+, all modern browsers, Deno, Bun, and Cloudflare Workers. * * Reference: FIPS 180-4 (Secure Hash Standard). */ /** * Compute the SHA-256 hash of the given data. * * @param data Input bytes. * @returns A 32-byte Uint8Array containing the SHA-256 digest. */ declare function sha256(data: Uint8Array): Promise; /** * Compute the SHA-384 hash of the given data. * * @param data Input bytes. * @returns A 48-byte Uint8Array containing the SHA-384 digest. */ declare function sha384(data: Uint8Array): Promise; /** * Compute the SHA-512 hash of the given data. * * @param data Input bytes. * @returns A 64-byte Uint8Array containing the SHA-512 digest. */ declare function sha512(data: Uint8Array): Promise; //#endregion //#region src/annotation/types/textAnnotation.d.ts /** Standard icon names for text annotations. */ type TextAnnotationIcon = 'Comment' | 'Key' | 'Note' | 'Help' | 'NewParagraph' | 'Paragraph' | 'Insert'; /** * A sticky note annotation (subtype /Text). * * Displays a small icon on the page; clicking the icon opens a popup * containing the annotation's text. */ declare class PdfTextAnnotation extends PdfAnnotation { constructor(dict: PdfDict); /** * Create a new text (sticky note) annotation. */ static create(options: AnnotationOptions & { icon?: TextAnnotationIcon | undefined; open?: boolean | undefined; }): PdfTextAnnotation; /** * Create a PdfTextAnnotation from an existing dictionary. */ static fromDict(dict: PdfDict, resolver?: (ref: PdfRef) => PdfObject | undefined): PdfTextAnnotation; /** Get the icon name. Defaults to 'Note'. */ getIcon(): string; /** Set the icon name. */ setIcon(icon: string): void; /** Whether the popup is initially open. */ isOpen(): boolean; /** Set the initial open state. */ setOpen(open: boolean): void; } //#endregion //#region src/annotation/types/linkAnnotation.d.ts /** Visual effect when clicking the link. */ type LinkHighlightMode = 'None' | 'Invert' | 'Outline' | 'Push'; /** * A link annotation (subtype /Link). * * Provides navigation to a destination within the document or to an * external URI. */ declare class PdfLinkAnnotation extends PdfAnnotation { constructor(dict: PdfDict); /** * Create a new link annotation. */ static create(options: AnnotationOptions & { url?: string | undefined; pageIndex?: number | undefined; fit?: string | undefined; highlightMode?: LinkHighlightMode | undefined; }): PdfLinkAnnotation; /** * Create from an existing dictionary. */ static fromDict(dict: PdfDict, resolver?: (ref: PdfRef) => PdfObject | undefined): PdfLinkAnnotation; /** * Get the destination (named dest string or explicit dest array). * * Returns: * - A string for named destinations. * - An array `[pageIndex, fitMode, ...params]` for explicit destinations. * - `undefined` if no destination is set. */ getDestination(): string | [number, string, ...number[]] | undefined; /** * Set an explicit destination (page index + fit mode). * * @param pageIndex Zero-based page index. * @param fit Fit mode (defaults to 'Fit'). */ setDestination(pageIndex: number, fit?: string | undefined): void; /** Get the URL if this is a URI link. */ getUrl(): string | undefined; /** Set the URL (creates a /URI action). */ setUrl(url: string): void; /** Get the highlight mode. Defaults to 'Invert'. */ getHighlightMode(): LinkHighlightMode; /** Set the highlight mode. */ setHighlightMode(mode: LinkHighlightMode): void; } //#endregion //#region src/annotation/types/freeTextAnnotation.d.ts /** Text alignment for free text annotations. */ type FreeTextAlignment = 'left' | 'center' | 'right'; /** * A free text annotation (subtype /FreeText). * * Displays text directly on the page as if it were part of the page * content. Does not require opening a popup. */ declare class PdfFreeTextAnnotation extends PdfAnnotation { constructor(dict: PdfDict); /** * Create a new free text annotation. */ static create(options: AnnotationOptions & { text?: string | undefined; fontSize?: number | undefined; alignment?: FreeTextAlignment | undefined; defaultAppearance?: string | undefined; }): PdfFreeTextAnnotation; /** * Create from an existing dictionary. */ static fromDict(dict: PdfDict, resolver?: (ref: PdfRef) => PdfObject | undefined): PdfFreeTextAnnotation; /** Get the displayed text. */ getText(): string; /** Set the displayed text. */ setText(text: string): void; /** Get the font size from the default appearance string. */ getFontSize(): number; /** Set the font size (rebuilds the default appearance string). */ setFontSize(size: number): void; /** Get the text alignment. Defaults to 'left'. */ getAlignment(): FreeTextAlignment; /** Set the text alignment. */ setAlignment(align: FreeTextAlignment): void; /** Get the default appearance string (/DA). */ getDefaultAppearance(): string; /** Set the default appearance string. */ setDefaultAppearance(da: string): void; /** Generate the appearance stream for this free text annotation. */ generateAppearance(): PdfStream; } //#endregion //#region src/annotation/types/markupAnnotations.d.ts /** * Highlight annotation (subtype /Highlight). * * Highlights text with a translucent colour overlay. */ declare class PdfHighlightAnnotation extends PdfAnnotation { constructor(dict: PdfDict); /** Create a new highlight annotation. */ static create(options: AnnotationOptions & { quadPoints?: number[] | undefined; }): PdfHighlightAnnotation; /** * Convenience: create a highlight for a rectangle region. */ static createForRect(rect: [number, number, number, number], color?: { r: number; g: number; b: number; } | undefined): PdfHighlightAnnotation; static fromDict(dict: PdfDict, resolver?: (ref: PdfRef) => PdfObject | undefined): PdfHighlightAnnotation; /** Get the quad points array. */ getQuadPoints(): number[]; /** Set the quad points array. */ setQuadPoints(points: number[]): void; generateAppearance(): PdfStream; } /** * Underline annotation (subtype /Underline). */ declare class PdfUnderlineAnnotation extends PdfAnnotation { constructor(dict: PdfDict); static create(options: AnnotationOptions & { quadPoints?: number[] | undefined; }): PdfUnderlineAnnotation; static fromDict(dict: PdfDict, resolver?: (ref: PdfRef) => PdfObject | undefined): PdfUnderlineAnnotation; /** Get the quad points array. */ getQuadPoints(): number[]; /** Set the quad points array. */ setQuadPoints(points: number[]): void; generateAppearance(): PdfStream; } /** * Squiggly underline annotation (subtype /Squiggly). */ declare class PdfSquigglyAnnotation extends PdfAnnotation { constructor(dict: PdfDict); static create(options: AnnotationOptions & { quadPoints?: number[] | undefined; }): PdfSquigglyAnnotation; static fromDict(dict: PdfDict, resolver?: (ref: PdfRef) => PdfObject | undefined): PdfSquigglyAnnotation; /** Get the quad points array. */ getQuadPoints(): number[]; /** Set the quad points array. */ setQuadPoints(points: number[]): void; generateAppearance(): PdfStream; } /** * Strike-out annotation (subtype /StrikeOut). */ declare class PdfStrikeOutAnnotation extends PdfAnnotation { constructor(dict: PdfDict); static create(options: AnnotationOptions & { quadPoints?: number[] | undefined; }): PdfStrikeOutAnnotation; static fromDict(dict: PdfDict, resolver?: (ref: PdfRef) => PdfObject | undefined): PdfStrikeOutAnnotation; /** Get the quad points array. */ getQuadPoints(): number[]; /** Set the quad points array. */ setQuadPoints(points: number[]): void; generateAppearance(): PdfStream; } //#endregion //#region src/annotation/types/shapeAnnotations.d.ts /** Line ending style names. */ type LineEndingStyle = 'None' | 'Square' | 'Circle' | 'Diamond' | 'OpenArrow' | 'ClosedArrow' | 'Butt' | 'ROpenArrow' | 'RClosedArrow' | 'Slash'; /** * Line annotation (subtype /Line). * * Draws a straight line between two points on the page. */ declare class PdfLineAnnotation extends PdfAnnotation { constructor(dict: PdfDict); /** * Create a new line annotation. */ static create(options: AnnotationOptions & { linePoints?: [number, number, number, number] | undefined; lineEndingStart?: LineEndingStyle | undefined; lineEndingEnd?: LineEndingStyle | undefined; }): PdfLineAnnotation; static fromDict(dict: PdfDict, resolver?: (ref: PdfRef) => PdfObject | undefined): PdfLineAnnotation; /** Get the line endpoints [x1, y1, x2, y2]. */ getLinePoints(): [number, number, number, number]; /** Set the line endpoints. */ setLinePoints(points: [number, number, number, number]): void; /** Get the line ending styles [start, end]. */ getLineEndingStyles(): [string, string]; /** Set the line ending styles. */ setLineEndingStyles(start: string, end: string): void; generateAppearance(): PdfStream; } /** * Square annotation (subtype /Square). * * Draws a rectangle on the page. */ declare class PdfSquareAnnotation extends PdfAnnotation { constructor(dict: PdfDict); static create(options: AnnotationOptions & { interiorColor?: { r: number; g: number; b: number; } | undefined; }): PdfSquareAnnotation; static fromDict(dict: PdfDict, resolver?: (ref: PdfRef) => PdfObject | undefined): PdfSquareAnnotation; /** Get the interior (fill) color. */ getInteriorColor(): { r: number; g: number; b: number; } | undefined; /** Set the interior (fill) color. */ setInteriorColor(color: { r: number; g: number; b: number; }): void; generateAppearance(): PdfStream; } /** * Circle annotation (subtype /Circle). * * Draws an ellipse inscribed within the annotation rectangle. */ declare class PdfCircleAnnotation extends PdfAnnotation { constructor(dict: PdfDict); static create(options: AnnotationOptions & { interiorColor?: { r: number; g: number; b: number; } | undefined; }): PdfCircleAnnotation; static fromDict(dict: PdfDict, resolver?: (ref: PdfRef) => PdfObject | undefined): PdfCircleAnnotation; /** Get the interior (fill) color. */ getInteriorColor(): { r: number; g: number; b: number; } | undefined; /** Set the interior (fill) color. */ setInteriorColor(color: { r: number; g: number; b: number; }): void; generateAppearance(): PdfStream; } /** * Polygon annotation (subtype /Polygon). * * Draws a closed polygon on the page. */ declare class PdfPolygonAnnotation extends PdfAnnotation { constructor(dict: PdfDict); static create(options: AnnotationOptions & { vertices?: number[] | undefined; interiorColor?: { r: number; g: number; b: number; } | undefined; }): PdfPolygonAnnotation; static fromDict(dict: PdfDict, resolver?: (ref: PdfRef) => PdfObject | undefined): PdfPolygonAnnotation; /** Get the polygon vertices as a flat array [x1,y1,x2,y2,...]. */ getVertices(): number[]; /** Set the polygon vertices. */ setVertices(vertices: number[]): void; /** Get the interior (fill) color. */ getInteriorColor(): { r: number; g: number; b: number; } | undefined; /** Set the interior (fill) color. */ setInteriorColor(color: { r: number; g: number; b: number; }): void; } /** * PolyLine annotation (subtype /PolyLine). * * Draws an open polyline (series of connected line segments). */ declare class PdfPolyLineAnnotation extends PdfAnnotation { constructor(dict: PdfDict); static create(options: AnnotationOptions & { vertices?: number[] | undefined; }): PdfPolyLineAnnotation; static fromDict(dict: PdfDict, resolver?: (ref: PdfRef) => PdfObject | undefined): PdfPolyLineAnnotation; /** Get the polyline vertices as a flat array [x1,y1,x2,y2,...]. */ getVertices(): number[]; /** Set the polyline vertices. */ setVertices(vertices: number[]): void; } //#endregion //#region src/annotation/types/stampAnnotation.d.ts /** Standard stamp names defined in the PDF specification. */ type StandardStampName = 'Approved' | 'Experimental' | 'NotApproved' | 'AsIs' | 'Expired' | 'NotForPublicRelease' | 'Confidential' | 'Final' | 'Sold' | 'Departmental' | 'ForComment' | 'TopSecret' | 'Draft' | 'ForPublicRelease'; /** * A stamp annotation (subtype /Stamp). * * Displays a graphical stamp on the page, similar to a rubber stamp * applied to a physical document. */ declare class PdfStampAnnotation extends PdfAnnotation { constructor(dict: PdfDict); /** * Create a new stamp annotation. */ static create(options: AnnotationOptions & { stampName?: string | undefined; }): PdfStampAnnotation; static fromDict(dict: PdfDict, resolver?: (ref: PdfRef) => PdfObject | undefined): PdfStampAnnotation; /** Get the stamp name (e.g. 'Approved', 'Draft'). */ getStampName(): string; /** Set the stamp name. */ setStampName(name: string): void; } //#endregion //#region src/annotation/types/inkAnnotation.d.ts /** * An ink annotation (subtype /Ink). * * Contains one or more ink paths, each being an array of coordinate * pairs [x1,y1,x2,y2,...] representing a freehand stroke. */ declare class PdfInkAnnotation extends PdfAnnotation { constructor(dict: PdfDict); /** * Create a new ink annotation. */ static create(options: AnnotationOptions & { inkLists?: number[][] | undefined; }): PdfInkAnnotation; static fromDict(dict: PdfDict, resolver?: (ref: PdfRef) => PdfObject | undefined): PdfInkAnnotation; /** * Get all ink lists. * * Each ink list is an array of numbers [x1,y1,x2,y2,...] representing * a single stroke path. */ getInkLists(): number[][]; /** * Add a new ink stroke path. * * @param points Array of coordinate pairs [x1,y1,x2,y2,...]. */ addInkList(points: number[]): void; /** Remove all ink stroke paths. */ clearInkLists(): void; generateAppearance(): PdfStream; } //#endregion //#region src/annotation/types/redactAnnotation.d.ts /** * A redaction annotation (subtype /Redact). * * Marks content for redaction. The annotation itself is a marker; * the actual redaction (content removal) must be applied separately. */ declare class PdfRedactAnnotation extends PdfAnnotation { constructor(dict: PdfDict); /** * Create a new redact annotation. */ static create(options: AnnotationOptions & { overlayText?: string | undefined; interiorColor?: { r: number; g: number; b: number; } | undefined; quadPoints?: number[] | undefined; }): PdfRedactAnnotation; static fromDict(dict: PdfDict, resolver?: (ref: PdfRef) => PdfObject | undefined): PdfRedactAnnotation; /** Get the overlay text displayed after redaction is applied. */ getOverlayText(): string | undefined; /** Set the overlay text. */ setOverlayText(text: string): void; /** Get the interior (fill) color used after redaction. */ getInteriorColor(): { r: number; g: number; b: number; } | undefined; /** Set the interior color. */ setInteriorColor(color: { r: number; g: number; b: number; }): void; /** Get the quad points (regions to redact). */ getQuadPoints(): number[] | undefined; /** Set the quad points. */ setQuadPoints(points: number[]): void; } //#endregion //#region src/annotation/types/popupAnnotation.d.ts /** * A popup annotation (subtype /Popup). * * Displays a floating window containing the text of its parent * annotation. The parent annotation references this popup via its * `/Popup` entry, and this popup references its parent via `/Parent`. */ declare class PdfPopupAnnotation extends PdfAnnotation { constructor(dict: PdfDict); /** * Create a new popup annotation. * * @param options.open Whether the popup is initially open. Default: false. */ static create(options: AnnotationOptions & { open?: boolean | undefined; }): PdfPopupAnnotation; /** * Create a PdfPopupAnnotation from an existing dictionary. */ static fromDict(dict: PdfDict, _resolver?: (ref: PdfRef) => PdfObject | undefined): PdfPopupAnnotation; /** Whether the popup is initially open. */ isOpen(): boolean; /** Set the initial open state. */ setOpen(open: boolean): void; /** * Set the parent annotation reference. * The parent is the annotation whose text this popup displays. */ setParent(parentRef: PdfRef): void; /** Get the parent annotation reference, if set. */ getParent(): PdfRef | undefined; } //#endregion //#region src/annotation/types/caretAnnotation.d.ts /** * Symbol displayed by the caret annotation. * * - `'None'` — No symbol (just the caret marker). * - `'P'` — A paragraph symbol, indicating a new paragraph should * be inserted at this location. */ type CaretSymbol = 'None' | 'P'; /** * A caret annotation (subtype /Caret). * * Marks an insertion point in the text. Used in review workflows * to indicate where new content should be added. */ declare class PdfCaretAnnotation extends PdfAnnotation { constructor(dict: PdfDict); /** * Create a new caret annotation. * * @param options.symbol The caret symbol. Default: 'None'. * @param options.caretRect The inner rectangle (RD) that describes * the difference between the annotation rect and the actual caret * position. Format: [left, bottom, right, top] insets. */ static create(options: AnnotationOptions & { symbol?: CaretSymbol | undefined; caretRect?: [number, number, number, number] | undefined; }): PdfCaretAnnotation; /** * Create a PdfCaretAnnotation from an existing dictionary. */ static fromDict(dict: PdfDict, _resolver?: (ref: PdfRef) => PdfObject | undefined): PdfCaretAnnotation; /** Get the caret symbol. Defaults to 'None'. */ getSymbol(): CaretSymbol; /** Set the caret symbol. */ setSymbol(symbol: CaretSymbol): void; /** * Get the inner rectangle differences (RD entry). * Returns [left, bottom, right, top] insets from the annotation rect. */ getCaretRect(): [number, number, number, number] | undefined; /** Set the inner rectangle differences (RD entry). */ setCaretRect(rd: [number, number, number, number]): void; } //#endregion //#region src/annotation/types/fileAttachmentAnnotation.d.ts /** * Standard icon names for file attachment annotations. * * - `'GraphPushPin'` — A push pin on a graph (default). * - `'PaperclipTag'` — A paper clip with a tag. * - `'Paperclip'` — A paper clip. * - `'Tag'` — A tag label. */ type FileAttachmentIcon = 'GraphPushPin' | 'PaperclipTag' | 'Paperclip' | 'Tag'; /** * A file attachment annotation (subtype /FileAttachment). * * Embeds a file directly in the annotation, rendered as a clickable * icon on the page. When the user clicks the icon, the PDF viewer * allows them to open or save the embedded file. */ declare class PdfFileAttachmentAnnotation extends PdfAnnotation { /** The raw file data to embed. */ private fileData; /** The filename to display. */ private fileName; /** Optional MIME type. */ private mimeType; /** Optional file description. */ private fileDescription; constructor(dict: PdfDict); /** * Create a new file attachment annotation. * * @param options.file The file data to embed. * @param options.fileName The filename (e.g., 'invoice.xml'). * @param options.mimeType Optional MIME type (e.g., 'application/xml'). * @param options.description Optional description of the file. * @param options.icon Icon to display. Default: 'GraphPushPin'. */ static create(options: AnnotationOptions & { file: Uint8Array; fileName: string; mimeType?: string | undefined; description?: string | undefined; icon?: FileAttachmentIcon | undefined; }): PdfFileAttachmentAnnotation; /** * Create a PdfFileAttachmentAnnotation from an existing dictionary. */ static fromDict(dict: PdfDict, _resolver?: (ref: PdfRef) => PdfObject | undefined): PdfFileAttachmentAnnotation; /** Get the icon name. Defaults to 'GraphPushPin'. */ getIcon(): FileAttachmentIcon; /** Set the icon name. */ setIcon(icon: FileAttachmentIcon): void; /** Get the filename, if set. */ getFileName(): string | undefined; /** * Build the file specification dictionary and register the embedded * file stream. Call this before serializing the annotation. * * @param registry The document's object registry. * @returns The annotation dict with `/FS` referencing the file. */ buildFileSpec(registry: PdfObjectRegistry): PdfDict; } //#endregion //#region src/annotation/appearanceGenerator.d.ts /** * Generate appearance stream for a Square annotation. */ declare function generateSquareAppearance(annot: PdfAnnotation): PdfStream; /** * Generate appearance stream for a Circle annotation. */ declare function generateCircleAppearance(annot: PdfAnnotation): PdfStream; /** * Generate appearance stream for a Line annotation. */ declare function generateLineAppearance(annot: PdfAnnotation): PdfStream; /** * Generate appearance stream for a Highlight annotation. */ declare function generateHighlightAppearance(annot: PdfAnnotation): PdfStream; /** * Generate appearance stream for an Underline annotation. */ declare function generateUnderlineAppearance(annot: PdfAnnotation): PdfStream; /** * Generate appearance stream for a Squiggly annotation. */ declare function generateSquigglyAppearance(annot: PdfAnnotation): PdfStream; /** * Generate appearance stream for a StrikeOut annotation. */ declare function generateStrikeOutAppearance(annot: PdfAnnotation): PdfStream; /** * Generate appearance stream for an Ink annotation. */ declare function generateInkAppearance(annot: PdfAnnotation): PdfStream; /** * Generate appearance stream for a FreeText annotation. * * This requires access to the annotation's text, default appearance * string, and alignment. We accept the annotation object directly * to access these properties. */ declare function generateFreeTextAppearance(annot: PdfAnnotation): PdfStream; //#endregion //#region src/signature/byteRange.d.ts /** * @module signature/byteRange * * ByteRange calculation for PDF digital signatures. * * A PDF signature works by: * 1. Inserting a signature dictionary with a `/Contents` placeholder * (a hex string of zeroes) and a `/ByteRange` array. * 2. Computing a hash of the PDF bytes *excluding* the `/Contents` * hex string value. * 3. Signing the hash with the signer's private key. * 4. Embedding the signature (DER-encoded PKCS#7) into the placeholder. * * The `/ByteRange` is an array of four integers: * [offsetBefore, lengthBefore, offsetAfter, lengthAfter] * * Where: * - `[offsetBefore .. offsetBefore+lengthBefore)` = bytes before the * `<…>` hex string * - `[offsetAfter .. offsetAfter+lengthAfter)` = bytes after the * `<…>` hex string * * Reference: PDF 1.7 spec, SS12.8.1 (Signature Filtering). * * @packageDocumentation */ /** * Result of ByteRange computation for a prepared PDF. */ interface ByteRangeResult { /** The byte range array [offset1, length1, offset2, length2]. */ byteRange: [number, number, number, number]; /** Start offset of the /Contents hex string placeholder (the `<`). */ contentsOffset: number; /** Length of the placeholder in bytes (including angle brackets `<…>`). */ contentsLength: number; } /** * Prepare a PDF for signing by appending a signature dictionary * via incremental update. * * This function: * 1. Appends a new signature field and value to the PDF * 2. Inserts an empty `/Contents` placeholder of the specified size * 3. Computes the `/ByteRange` that excludes the `/Contents` value * * The resulting PDF bytes can be hashed (excluding the placeholder gap) * and the hash can be signed. * * @param pdfBytes The original PDF file bytes. * @param signatureFieldName The name for the signature field. * @param placeholderSize Size in bytes for the signature. Default 8192. * @returns The prepared PDF and ByteRange info. */ /** * Options for visible signature appearance within the byte-range preparation. * @internal */ interface PrepareAppearanceOptions { /** Page rectangle [x, y, width, height]. */ rect: [number, number, number, number]; /** Lines of text to render inside the signature box. */ textLines: string[]; /** Font size. Default: 10. */ fontSize?: number | undefined; /** Background [r,g,b]. Default: none. */ backgroundColor?: [number, number, number] | undefined; /** Border [r,g,b]. Default: [0,0,0]. */ borderColor?: [number, number, number] | undefined; /** Border width. Default: 1. */ borderWidth?: number | undefined; } declare function prepareForSigning(pdfBytes: Uint8Array, signatureFieldName: string, placeholderSize?: number, appearance?: PrepareAppearanceOptions | undefined, mdpPermission?: number | undefined, fieldLock?: { action: 'All' | 'Include' | 'Exclude'; fields?: string[] | undefined; } | undefined): { preparedPdf: Uint8Array; byteRange: ByteRangeResult; }; /** * Compute the hash of PDF bytes excluding the signature placeholder. * * Hashes the bytes covered by the ByteRange (everything except * the `/Contents` hex string). * * @param pdfBytes The prepared PDF bytes. * @param byteRange The [offset1, length1, offset2, length2] array. * @param algorithm Hash algorithm. Default 'SHA-256'. * @returns The hash digest. */ declare function computeSignatureHash(pdfBytes: Uint8Array, byteRange: [number, number, number, number], algorithm?: 'SHA-256' | 'SHA-384' | 'SHA-512'): Promise; /** * Embed a signature into the prepared PDF at the placeholder position. * * Writes the hex-encoded signature bytes into the `/Contents <…>` * placeholder, replacing the zero bytes. * * @param preparedPdf The prepared PDF bytes (from prepareForSigning). * @param signatureBytes The DER-encoded signature (PKCS#7/CMS). * @param byteRange The ByteRange result from prepareForSigning. * @returns The signed PDF bytes. */ declare function embedSignature(preparedPdf: Uint8Array, signatureBytes: Uint8Array, byteRange: ByteRangeResult): Uint8Array; /** * Find all signature fields in a PDF and extract their ByteRange * and Contents information. * * @param pdfBytes The PDF bytes to scan. * @returns Array of signature info objects. */ declare function findSignatures(pdfBytes: Uint8Array): Array<{ byteRange: [number, number, number, number]; contentsHex: string; contentsOffset: number; contentsLength: number; }>; //#endregion //#region src/signature/pkcs7.d.ts /** * @module signature/pkcs7 * * PKCS#7 / CMS SignedData structure builder for PDF digital signatures. * * Builds a minimal but valid PKCS#7 SignedData structure using pure * TypeScript ASN.1 DER encoding. Uses the Web Crypto API for * RSASSA-PKCS1-v1_5 or ECDSA signing. * * Structure overview: * ``` * ContentInfo { * contentType: signedData (1.2.840.113549.1.7.2) * content: SignedData { * version: 1 * digestAlgorithms: { SHA-256 } * encapContentInfo: { data (1.2.840.113549.1.7.1) } * certificates: [0] IMPLICIT { certificate } * signerInfos: { * SignerInfo { * version: 1 * issuerAndSerialNumber * digestAlgorithm: SHA-256 * signedAttrs: { contentType, signingTime, messageDigest } * signatureAlgorithm * signature * } * } * } * } * ``` * * References: * - RFC 5652 (Cryptographic Message Syntax) * - RFC 3161 (Internet X.509 PKI Time-Stamp Protocol) * - PKCS#7 / CMS SignedData * * @packageDocumentation */ /** * Information needed to sign a hash. */ interface SignerInfo { /** DER-encoded X.509 certificate. */ certificate: Uint8Array; /** PKCS#8 DER-encoded private key. */ privateKey: Uint8Array; /** Hash algorithm. */ hashAlgorithm: 'SHA-256' | 'SHA-384' | 'SHA-512'; } /** * Options for building a signature. */ interface SignatureOptions { signerInfo: SignerInfo; reason?: string | undefined; location?: string | undefined; contactInfo?: string | undefined; signingDate?: Date | undefined; } /** * Encode the length field of a DER TLV (Tag-Length-Value). * * - Lengths 0–127 are encoded as a single byte. * - Lengths >= 128 use the long form: first byte has bit 7 set and * the lower 7 bits give the number of length bytes that follow. */ declare function encodeLength(length: number): Uint8Array; /** * Encode a SEQUENCE containing the given DER-encoded contents. */ declare function encodeSequence(contents: Uint8Array[]): Uint8Array; /** * Encode a SET containing the given DER-encoded contents. */ declare function encodeSet(contents: Uint8Array[]): Uint8Array; /** * Encode an OID from dotted-decimal string (e.g. "1.2.840.113549.1.7.2"). */ declare function encodeOID(oid: string): Uint8Array; /** * Encode an OCTET STRING. */ declare function encodeOctetString(data: Uint8Array): Uint8Array; /** * Encode an INTEGER. * * DER integers are signed; a leading 0x00 byte is added if the * high bit of the first byte is set (to indicate a positive value). */ declare function encodeInteger(data: Uint8Array): Uint8Array; /** * Encode a UTF8String. */ declare function encodeUtf8String(str: string): Uint8Array; /** * Encode a PrintableString. */ declare function encodePrintableString(str: string): Uint8Array; /** * Encode a UTCTime from a Date. * * Format: YYMMDDHHmmSSZ */ declare function encodeUTCTime(date: Date): Uint8Array; /** * Encode a context-specific tagged value (implicit or explicit). * * For PKCS#7: * - [0] is used for content in ContentInfo (explicit, constructed) * - [0] IMPLICIT is used for certificates in SignedData * - [0] IMPLICIT is used for signed attributes in SignerInfo */ declare function encodeContextTag(tag: number, contents: Uint8Array): Uint8Array; /** * Build a PKCS#7 (CMS) SignedData structure for a PDF signature. * * Takes a pre-computed hash of the PDF content (excluding the * /Contents placeholder) and produces a DER-encoded PKCS#7 blob * that can be embedded in the PDF's /Contents field. * * @param dataHash The hash of the PDF bytes covered by ByteRange. * @param options Signing options (certificate, key, etc.). * @returns DER-encoded PKCS#7 SignedData. */ declare function buildPkcs7Signature(dataHash: Uint8Array, options: SignatureOptions): Promise; //#endregion //#region src/signature/timestamp.d.ts /** * @module signature/timestamp * * RFC 3161 Timestamp Authority (TSA) client for timestamped signatures. * * Timestamps provide proof that a document was signed at a specific time, * independent of the signer's system clock. A TSA is a trusted third * party that cryptographically binds a hash to a specific moment in time. * * This module builds TimeStampReq messages, sends them to a TSA via * HTTP POST (using `fetch()`), and parses TimeStampResp messages. * * References: * - RFC 3161 (Internet X.509 PKI Time-Stamp Protocol) * - RFC 5816 (ESSCertIDv2 Update for RFC 3161) * * @packageDocumentation */ /** * Result from a timestamp request. */ interface TimestampResult { /** The DER-encoded TimeStampToken (a CMS SignedData). */ timestampToken: Uint8Array; /** The signing time reported by the TSA. */ signingTime: Date; } /** * Build a DER-encoded TimeStampReq (RFC 3161 SS2.4.1). * * ``` * TimeStampReq ::= SEQUENCE { * version INTEGER { v1(1) }, * messageImprint MessageImprint, * reqPolicy TSAPolicyId OPTIONAL, * nonce INTEGER OPTIONAL, * certReq BOOLEAN DEFAULT FALSE, * extensions [0] IMPLICIT Extensions OPTIONAL * } * * MessageImprint ::= SEQUENCE { * hashAlgorithm AlgorithmIdentifier, * hashedMessage OCTET STRING * } * ``` * * @param dataHash The hash of the data to timestamp. * @param hashAlgorithm The hash algorithm used. * @returns DER-encoded TimeStampReq. */ declare function buildTimestampRequest(dataHash: Uint8Array, hashAlgorithm: string): Uint8Array; /** * Parse a DER-encoded TimeStampResp (RFC 3161 SS2.4.2). * * ``` * TimeStampResp ::= SEQUENCE { * status PKIStatusInfo, * timeStampToken ContentInfo OPTIONAL * } * * PKIStatusInfo ::= SEQUENCE { * status PKIStatus (INTEGER), * statusString PKIFreeText OPTIONAL, * failInfo PKIFailureInfo OPTIONAL * } * ``` * * @param response DER-encoded TimeStampResp. * @returns The parsed timestamp result. * @throws Error if the TSA reported an error status. */ declare function parseTimestampResponse(response: Uint8Array): TimestampResult; /** * Request a timestamp from an RFC 3161 TSA. * * Sends a TimeStampReq via HTTP POST and parses the TimeStampResp. * Uses `fetch()` for universal runtime compatibility (Node.js 18+, * browsers, Deno, Bun, Cloudflare Workers). * * @param dataHash The hash of the data to timestamp. * @param tsaUrl The URL of the TSA service. * @param hashAlgorithm The hash algorithm. Default 'SHA-256'. * @returns The timestamp result. * @throws Error if the request fails or the TSA returns * an error status. * * @example * ```ts * const hash = await computeSignatureHash(pdfBytes, byteRange); * const timestamp = await requestTimestamp( * hash, * 'http://timestamp.digicert.com', * ); * ``` */ declare function requestTimestamp(dataHash: Uint8Array, tsaUrl: string, hashAlgorithm?: 'SHA-256' | 'SHA-384' | 'SHA-512'): Promise; //#endregion //#region src/signature/incrementalSave.d.ts /** * @module signature/incrementalSave * * Incremental save with signature preservation. * * Provides the ability to perform append-only incremental updates * to a PDF while preserving all existing digital signatures. * This is essential for multi-signature workflows where each signer * adds their signature without invalidating previous signatures. * * Key guarantees: * - Original bytes are never modified (pure append) * - All existing signature byte ranges remain intact * - Each update appends objects + xref + trailer with /Prev pointer * * Reference: PDF 1.7 spec, SS7.5.6 (Incremental Updates), * SS12.8 (Digital Signatures). * * @packageDocumentation */ /** * Byte range for an existing signature. */ interface SignatureByteRange { /** The four-element byte range array [offset1, length1, offset2, length2]. */ byteRange: [number, number, number, number]; /** Offset of the /Contents hex string placeholder. */ contentsOffset: number; /** Length of the /Contents hex string (including angle brackets). */ contentsLength: number; } /** * Options for incremental save with signature preservation. */ interface IncrementalSaveOptions { /** Apply FlateDecode compression to new stream objects. Default: true. */ compress?: boolean | undefined; /** Preserve existing signatures by verifying byte ranges. Default: true. */ preserveSignatures?: boolean | undefined; } /** * Options for pure append-only incremental updates. */ interface AppendOptions { /** Apply FlateDecode compression. Default: false. */ compress?: boolean | undefined; } /** * An object to be appended in an incremental update. */ interface IncrementalObject { /** The PDF object number. */ objectNumber: number; /** The generation number (usually 0). */ generationNumber: number; /** The serialized object data (everything between `N G obj\n` and `\nendobj`). */ data: Uint8Array; } /** * Information extracted from an existing PDF trailer. */ interface TrailerInfo { /** The /Size value (total number of objects). */ size: number; /** The /Root reference string (e.g., "1 0 R"). */ rootRef: string; /** The /Info reference string (e.g., "4 0 R"), if present. */ infoRef?: string | undefined; /** The byte offset of the previous cross-reference section. */ prevXrefOffset: number; } /** * Scan a PDF for all /Type /Sig dictionaries and extract their byte ranges. * * @param pdf The PDF bytes to scan. * @returns Array of signature byte range descriptors. */ declare function findExistingSignatures(pdf: Uint8Array): SignatureByteRange[]; /** * Verify that no existing signature's covered bytes would overlap * with content appended after the current end of file. * * For a valid incremental update, all existing signature byte ranges * must reference bytes within the original file. Any overlap with * new content appended after the last %%EOF would break signatures. * * @param pdf The current PDF bytes. * @param signatures The signature byte ranges to validate. * @returns `true` if all byte ranges are valid and non-overlapping with appended content. */ declare function validateByteRangeIntegrity(pdf: Uint8Array, signatures: SignatureByteRange[]): boolean; /** * Parse the existing trailer from a PDF to extract /Size, /Root, /Info, * and the previous xref offset. * * Scans backward from the end of the file for `startxref` and the * trailer dictionary. * * @param pdf The PDF bytes. * @returns Parsed trailer information. */ declare function parseExistingTrailer(pdf: Uint8Array): TrailerInfo; /** * Perform an incremental save that preserves ALL existing signatures. * * Takes the original PDF bytes and a modified version, detects which * objects changed by comparing object hashes, and appends only the * changed/new objects after the original %%EOF. This ensures all * existing signature byte ranges remain intact. * * @param originalPdf The original (possibly signed) PDF bytes. * @param modifiedPdf The modified PDF bytes with changes. * @param options Options for the incremental save. * @returns The incrementally saved PDF bytes. */ declare function saveIncrementalWithSignaturePreservation(originalPdf: Uint8Array, modifiedPdf: Uint8Array, options?: IncrementalSaveOptions): Uint8Array; /** * Append a pure incremental update to a PDF. * * This function NEVER modifies bytes before the last %%EOF. * It appends new/modified objects, a new xref subsection, and a * new trailer with a /Prev pointer to the previous xref. * * @param originalPdf The original PDF bytes. * @param newObjects Objects to append (new or modified). * @param options Options for the append operation. * @returns The updated PDF bytes. */ declare function appendIncrementalUpdate(originalPdf: Uint8Array, newObjects: IncrementalObject[], options?: AppendOptions): Uint8Array; //#endregion //#region src/signature/multiSignatureValidator.d.ts /** * @module signature/multiSignatureValidator * * Multi-signature chain validation for PDFs with multiple signatures. * * In a multi-signature workflow, each subsequent signer adds their * signature via an incremental update. This module validates that: * * 1. Each signature covers the correct byte range * 2. Each subsequent signature covers all content including previous signatures * 3. No signature's covered bytes have been tampered with * 4. The chain is ordered correctly (chronological signing order) * * Reference: PDF 1.7 spec, SS12.8.1 (Signature Filtering). * * @packageDocumentation */ /** * Validation status for a single signature in the chain. */ interface SignatureChainEntry { /** The signature field name (extracted from /T). */ fieldName: string; /** The signer name (extracted from /Contents PKCS#7 or dictionary). */ signerName: string; /** The signing date (extracted from /M), if present. */ signedAt?: Date | undefined; /** The byte range covering this signature. */ byteRange: [number, number, number, number]; /** Whether this signature covers the entire document up to its point. */ coversEntireDocument: boolean; /** Validation status for this entry in the chain. */ status: 'valid' | 'invalid' | 'broken_chain'; } /** * Result of validating the entire signature chain. */ interface SignatureChainResult { /** Ordered array of signature chain entries. */ signatures: SignatureChainEntry[]; /** Whether the entire chain is valid (all entries valid, no breaks). */ isChainValid: boolean; /** Descriptive error messages, if any. */ errors: string[]; } /** * Validate the entire signature chain in a PDF. * * Finds all signatures, validates each one covers the correct byte range, * and verifies each subsequent signature covers all content including * previous signatures. Returns an ordered chain with status for each entry. * * @param pdf The PDF bytes to validate. * @returns The signature chain validation result. */ declare function validateSignatureChain(pdf: Uint8Array): Promise; //#endregion //#region src/signature/mdpPolicy.d.ts /** * MDP permission levels for certification signatures. * * These correspond to the /P value in the /TransformParams dictionary * of a /DocMDP transform method. */ declare enum MdpPermission { /** No changes to the document are permitted. */ NoChanges = 1, /** Only form filling and signing are permitted. */ FormFillAndSign = 2, /** Form filling, signing, and annotation changes are permitted. */ FormFillSignAnnotate = 3 } /** * Set the certification level (MDP permission) on sign options. * * When applied, the resulting signature will include a /DocMDP * transform method in its /TransformParams, which certifies the * document and restricts future modifications to the specified level. * * This should only be used for the FIRST (certification) signature * in a document. Subsequent approval signatures should not set MDP. * * @param options The sign options to modify (mutated in place). * @param level The MDP permission level to set. * * @example * ```ts * const options: SignOptions = { * certificate: certDer, * privateKey: keyDer, * }; * setCertificationLevel(options, MdpPermission.FormFillAndSign); * const signedPdf = await signPdf(pdfBytes, 'CertSig', options); * ``` */ declare function setCertificationLevel(options: SignOptions, level: MdpPermission): void; /** * Read the certification level (MDP permission) from a PDF. * * Scans the PDF for the first /DocMDP transform method and extracts * the /P value from its /TransformParams. Returns `undefined` if no * certification signature is found. * * @param pdf The PDF bytes to scan. * @returns The MDP permission level, or `undefined` if not certified. */ declare function getCertificationLevel(pdf: Uint8Array): MdpPermission | undefined; /** * Build a /DocMDP reference dictionary string for inclusion in * the signature dictionary. * * @param sigValueObjNum The object number of the signature value. * @param level The MDP permission level. * @returns The /Reference array string to include in the sig dict. * * @internal */ declare function buildDocMdpReference(sigValueObjNum: number, level: MdpPermission): string; //#endregion //#region src/signature/modificationDetector.d.ts /** * Types of modifications that can be detected. */ type ModificationViolationType = 'content_changed' | 'annotation_added' | 'form_filled' | 'page_added'; /** * A single modification violation detected in the document. */ interface ModificationViolation { /** The type of modification detected. */ type: ModificationViolationType; /** Human-readable description of the violation. */ description: string; /** Index of the signature whose coverage was violated. */ affectedSignatureIndex: number; } /** * Report of modifications detected in a certified document. */ interface ModificationReport { /** The certification level, if any. */ certificationLevel?: MdpPermission | undefined; /** Whether the modifications comply with the certification level. */ isCompliant: boolean; /** List of detected violations. */ violations: ModificationViolation[]; } /** * Detect modifications in a certified PDF document. * * Compares content at each signature's byte range against the current * PDF state. If an MDP (DocMDP) certification level is set, checks * whether the modifications comply with the permitted level. * * Modification levels: * - MDP 1 (NoChanges): Any change is a violation * - MDP 2 (FormFillAndSign): Only form fills and new signatures allowed * - MDP 3 (FormFillSignAnnotate): Form fills, signatures, and annotations allowed * * @param pdf The PDF bytes to analyze. * @returns A detailed modification report. */ declare function detectModifications(pdf: Uint8Array): Promise; //#endregion //#region src/signature/fieldLock.d.ts /** * Options for locking fields when a signature is applied. */ interface FieldLockOptions { /** Lock action: 'All', 'Include', or 'Exclude'. */ action: 'All' | 'Include' | 'Exclude'; /** Field names to include or exclude (required for 'Include' and 'Exclude'). */ fields?: string[] | undefined; } /** * Information about a field lock on a signature field. */ interface FieldLockInfo { /** The name of the signature field that has the lock. */ signatureFieldName: string; /** The lock action: 'All', 'Include', or 'Exclude'. */ action: 'All' | 'Include' | 'Exclude'; /** The list of locked fields (empty for 'All' action). */ lockedFields: string[]; } /** * Add a field lock dictionary to sign options. * * When applied, the resulting signature field will include a /Lock * dictionary that specifies which form fields should be locked after * this signature is applied. * * @param options The sign options to modify (mutated in place). * @param lock The field lock configuration. * * @example * ```ts * const options: SignOptions = { * certificate: certDer, * privateKey: keyDer, * }; * addFieldLock(options, { * action: 'Include', * fields: ['Name', 'Address', 'Amount'], * }); * const signedPdf = await signPdf(pdfBytes, 'ApprovalSig', options); * ``` */ declare function addFieldLock(options: SignOptions, lock: FieldLockOptions): void; /** * Read all field lock dictionaries from signature fields in a PDF. * * Scans the PDF for signature field dictionaries that contain a /Lock * entry and extracts the lock action and field names. * * @param pdf The PDF bytes to scan. * @returns Array of field lock information objects. */ declare function getFieldLocks(pdf: Uint8Array): FieldLockInfo[]; /** * Build a /Lock dictionary string for inclusion in a signature field. * * @param lock The field lock options. * @returns The /Lock dictionary string. * * @internal */ declare function buildFieldLockDict(lock: FieldLockOptions): string; //#endregion //#region src/signature/documentDiff.d.ts /** * @module signature/documentDiff * * Document modification detection — compares the signed version of a PDF * against the current version to identify what changed after signing. * * Uses the ByteRange to extract the signed content (the bytes that were * hashed when the signature was created), parses both versions, and * compares page counts, page content hashes, form field values, * annotation counts, and metadata. * * @packageDocumentation */ /** * A single difference found between signed and current content. */ interface DiffEntry { /** The category of change detected. */ type: 'page_added' | 'page_removed' | 'page_modified' | 'form_field_changed' | 'annotation_changed' | 'metadata_changed'; /** Zero-based page index (for page-related changes). */ pageIndex?: number | undefined; /** Form field name (for form field changes). */ fieldName?: string | undefined; /** Human-readable description of the change. */ description: string; } /** * Result of comparing signed content against the current PDF. */ interface DocumentDiff { /** Which signature was used as the baseline (zero-based). */ signatureIndex: number; /** The signing date from the signature dictionary, if available. */ signedAt?: Date | undefined; /** All detected changes between the signed and current version. */ changes: DiffEntry[]; /** Whether any changes were detected at all. */ hasChanges: boolean; } /** * Diff the signed content of a PDF against its current state. * * Extracts the signed bytes using the ByteRange of a specific signature * (or the latest signature by default), parses both versions, and * compares page count, page content hashes, form field values, * annotation counts, and metadata. * * @param pdf The current PDF bytes. * @param signatureIndex Zero-based index of the signature to diff against. * If not provided, uses the last (most recent) signature. * @returns A DocumentDiff describing all detected changes. * * @example * ```ts * import { diffSignedContent } from 'modern-pdf-lib/signature'; * * const diff = await diffSignedContent(pdfBytes); * if (diff.hasChanges) { * for (const entry of diff.changes) { * console.log(`${entry.type}: ${entry.description}`); * } * } * ``` */ declare function diffSignedContent(pdf: Uint8Array, signatureIndex?: number | undefined): Promise; //#endregion //#region src/signature/counterSignature.d.ts /** * @module signature/counterSignature * * Counter-signature support — allows signing an existing signature to * attest that a specific signature existed at a certain time (e.g., * notarization or witness signing). * * A counter-signature is a PKCS#7 unsigned attribute (OID 1.2.840.113549.1.9.6) * that contains a SignerInfo whose signature is computed over the existing * signature value. It is appended via incremental update. * * References: * - RFC 5652 SS 11.4 (Countersignature) * - PDF 2.0 spec SS 12.8 (Digital Signatures) * * @packageDocumentation */ /** * Information about a counter-signature found on a PDF signature. */ interface CounterSignatureInfo { /** The index of the primary signature that was counter-signed. */ targetSignatureIndex: number; /** The Common Name of the counter-signer. */ signerName: string; /** When the counter-signature was applied. */ signedAt?: Date | undefined; /** Whether the counter-signature is structurally valid. */ isValid: boolean; } /** * Add a counter-signature to an existing PDF signature. * * Finds the target signature's /Contents, computes a hash of the * existing signature value, creates a PKCS#7 counter-signature * attribute, and appends the result via incremental update. * * @param pdf The PDF bytes containing the target signature. * @param targetSignatureIndex Zero-based index of the signature to counter-sign. * @param signerInfo The counter-signer's certificate, private key, and hash algorithm. * @returns The PDF with the counter-signature appended. * * @example * ```ts * const counterSigned = await addCounterSignature( * signedPdf, * 0, * { certificate: certDer, privateKey: keyDer }, * ); * ``` */ declare function addCounterSignature(pdf: Uint8Array, targetSignatureIndex: number, signerInfo: { certificate: Uint8Array; privateKey: Uint8Array; hashAlgorithm?: string | undefined; }): Promise; /** * Extract counter-signatures from all signatures in a PDF. * * Scans each signature's PKCS#7 structure for the counter-signature * unsigned attribute (OID 1.2.840.113549.1.9.6). * * @param pdf The PDF bytes. * @returns Array of counter-signature info objects. * * @example * ```ts * const counterSigs = getCounterSignatures(pdfBytes); * for (const cs of counterSigs) { * console.log(`Signature ${cs.targetSignatureIndex} counter-signed by ${cs.signerName}`); * } * ``` */ declare function getCounterSignatures(pdf: Uint8Array): CounterSignatureInfo[]; //#endregion //#region src/signature/ltvEmbed.d.ts /** * @module signature/ltvEmbed * * LTV (Long-Term Validation) embedding for PDF digital signatures. * * Adds a Document Security Store (/DSS) dictionary to the PDF catalog * containing the validation data (certificates, CRLs, OCSP responses) * required to verify signatures decades after signing. * * The DSS is appended via incremental update to preserve existing * signatures (per ISO 32000-2 SS 12.8.4.3). * * References: * - ISO 32000-2:2020 SS 12.8.4.3 (Document Security Store) * - ETSI TS 102 778-4 (PAdES Long Term Validation) * - RFC 6960 (OCSP) * - RFC 5280 (CRL) * * @packageDocumentation */ /** * Options for LTV data embedding. */ interface LtvOptions { /** Include OCSP responses in the DSS. Default: true. */ includeOcsp?: boolean | undefined; /** Include CRL data in the DSS. Default: true. */ includeCrl?: boolean | undefined; /** Include certificate chains in the DSS. Default: true. */ includeCerts?: boolean | undefined; /** Pre-loaded OCSP responses (DER-encoded). */ ocspResponses?: Uint8Array[] | undefined; /** Pre-loaded CRLs (DER-encoded). */ crls?: Uint8Array[] | undefined; /** Additional certificates (DER-encoded) for the chain. */ extraCertificates?: Uint8Array[] | undefined; } /** * Data for the Document Security Store dictionary. */ interface DssData { /** DER-encoded certificates for the chain. */ certs: Uint8Array[]; /** DER-encoded OCSP responses. */ ocsps: Uint8Array[]; /** DER-encoded CRLs. */ crls: Uint8Array[]; } /** * Build a DSS (Document Security Store) dictionary string for * incremental append to a PDF. * * The DSS dictionary contains: * - /Certs: array of stream references for certificates * - /OCSPs: array of stream references for OCSP responses * - /CRLs: array of stream references for CRLs * * @param data The DSS data containing certs, OCSPs, and CRLs. * @returns A string representation of the DSS dictionary content. * * @example * ```ts * const dssStr = buildDssDictionary({ * certs: [certDer1, certDer2], * ocsps: [ocspResponse], * crls: [crlDer], * }); * ``` */ declare function buildDssDictionary(data: DssData): string; /** * Check whether a PDF already contains a Document Security Store (DSS). * * @param pdf The PDF bytes. * @returns `true` if the PDF contains a /DSS dictionary. */ declare function hasLtvData(pdf: Uint8Array): boolean; /** * Embed LTV (Long-Term Validation) data into a PDF. * * Extracts certificates from existing signatures, then appends a * Document Security Store (/DSS) dictionary to the PDF catalog via * incremental update. The DSS contains the certificate chains, * OCSP responses, and CRLs needed for future verification. * * @param pdf The PDF bytes. * @param options LTV embedding options. * @returns The PDF with embedded LTV data. * * @example * ```ts * import { embedLtvData } from 'modern-pdf-lib/signature'; * * const ltvPdf = await embedLtvData(signedPdf, { * includeOcsp: true, * includeCrl: true, * includeCerts: true, * }); * ``` */ declare function embedLtvData(pdf: Uint8Array, options?: LtvOptions | undefined): Promise; //#endregion //#region src/signature/incrementalOptimizer.d.ts /** * @module signature/incrementalOptimizer * * Incremental save size optimization. * * When performing incremental updates on a PDF, naive implementations * re-emit every modified object even if the content is identical to * the original. This module provides object-level diffing using FNV-1a * hashing to detect truly-changed objects and deduplicates identical * updates, producing minimal incremental appendices. * * @packageDocumentation */ /** * A single object change for an incremental update. */ interface IncrementalChange { /** The PDF object number. */ objectNumber: number; /** The generation number. */ generationNumber: number; /** The new content for this object (raw bytes). */ newContent: Uint8Array; } /** * FNV-1a 32-bit hash. * * A fast, non-cryptographic hash with good distribution properties. * Used for content comparison and deduplication. * * @param data The bytes to hash. * @returns A 32-bit unsigned hash as a hex string. */ declare function computeObjectHash(data: Uint8Array): string; /** * Find the list of object numbers whose content actually changed * between two versions of a PDF. * * Extracts all objects from both versions, hashes their content * using FNV-1a, and returns the object numbers where the hashes * differ. * * @param original The original PDF bytes. * @param modified The modified PDF bytes. * @returns Array of object numbers that have different content. * * @example * ```ts * const changed = findChangedObjects(originalPdf, modifiedPdf); * console.log(`${changed.length} objects actually changed`); * ``` */ declare function findChangedObjects(original: Uint8Array, modified: Uint8Array): number[]; /** * Optimize an incremental save by removing unchanged objects and * deduplicating identical updates. * * This function: * 1. Computes FNV-1a hashes of each change's content * 2. Compares against the original PDF objects to skip unchanged ones * 3. Deduplicates identical change entries (same content for same object) * 4. Builds a minimal incremental update containing only truly changed objects * * @param originalPdf The original PDF bytes. * @param changes The list of proposed changes. * @returns The optimized PDF bytes with minimal incremental update. * * @example * ```ts * import { optimizeIncrementalSave } from 'modern-pdf-lib/signature'; * * const optimizedPdf = optimizeIncrementalSave(originalPdf, [ * { objectNumber: 5, generationNumber: 0, newContent: newObj5 }, * { objectNumber: 7, generationNumber: 0, newContent: newObj7 }, * ]); * ``` */ declare function optimizeIncrementalSave(originalPdf: Uint8Array, changes: IncrementalChange[]): Uint8Array; //#endregion //#region src/core/linearization.d.ts /** * @module core/linearization * * Linearization support for PDF documents (PDF spec Appendix F). * * A linearized PDF is organized so that the first page can be displayed * before the entire file is downloaded. This is sometimes called * "fast web view" or "optimized for the web". * * **Structure of a linearized PDF (per §F.2):** * * 1. Header (%PDF-1.x + binary comment) * 2. Linearization parameter dictionary (first indirect object) * 3. First-page cross-reference table and trailer * 4. Document catalog, first-page objects * 5. Primary hint stream * 6. Remaining pages' objects (part 6..11 per spec) * 7. Main (overflow) cross-reference table and trailer * 8. %%EOF * * This implementation provides: * - Detection of linearized PDFs (`isLinearized`) * - Extraction of linearization info (`getLinearizationInfo`) * - Full linearization pass (`linearizePdf`) that reorganizes objects * so the first page's objects come first, with a linearization * parameter dict, page-offset hint table, shared object hint table, * and cross-reference streams. * - Delinearization (`delinearizePdf`) that strips linearization * artifacts and produces a normal (non-linearized) PDF. * * Reference: PDF 1.7 spec, Appendix F (Linearized PDF). */ /** Options for the linearization process. */ interface LinearizationOptions { /** First page to optimize for (default: 0). */ firstPage?: number | undefined; } /** * Information extracted from a linearization parameter dictionary. * Maps to the entries defined in PDF spec §F.2. */ interface LinearizationInfo { /** Linearization version (e.g. 1.0). */ version: number; /** File length (/L). */ length: number; /** Object number of the first page's page object (/O). */ primaryPage: number; /** Total page count (/N). */ pageCount: number; /** Byte offset of the end of the first page section (/E). */ firstPageOffset: number; } /** * Check if a PDF is linearized. * * A linearized PDF has a linearization parameter dictionary as the * very first indirect object after the header. This dictionary * contains `/Linearized` as a key. * * @param pdfBytes The raw PDF bytes. * @returns `true` if the PDF appears to be linearized. */ declare function isLinearized(pdfBytes: Uint8Array): boolean; /** * Extract linearization information from a linearized PDF. * * @param pdfBytes The raw PDF bytes. * @returns The linearization info, or `null` if not linearized. */ declare function getLinearizationInfo(pdfBytes: Uint8Array): LinearizationInfo | null; /** * Linearize a PDF document for fast web viewing. * * This reorganizes the PDF so that: * 1. A linearization parameter dictionary appears first (§F.2) * 2. Objects needed for the first page appear early in the file * 3. A primary hint stream describes page offsets and shared objects (§F.4) * 4. Cross-reference streams are used for all xref data (§7.5.8) * * @param pdfBytes The raw PDF bytes. * @param options Linearization options. * @returns The linearized PDF bytes. */ declare function linearizePdf(pdfBytes: Uint8Array, options?: LinearizationOptions): Promise; /** * Remove linearization artifacts from a PDF, producing a normal * (non-linearized) PDF. * * This: * 1. Strips the linearization parameter dictionary * 2. Removes hint streams * 3. Rebuilds the xref table without linearization ordering constraints * 4. Removes any /Linearized key from the output * * If the input PDF is not linearized, it is returned unchanged. * * @param pdfBytes The raw PDF bytes. * @returns A non-linearized PDF. */ declare function delinearizePdf(pdfBytes: Uint8Array): Promise; //#endregion //#region src/compliance/pdfA.d.ts /** * @module compliance/pdfA * * PDF/A compliance validation and enforcement. * * PDF/A is an ISO standard for long-term archival of electronic documents. * It restricts certain PDF features (e.g. encryption, JavaScript, * transparency) and mandates others (e.g. embedded fonts, XMP metadata). * * Supported conformance levels: * - **1b**: PDF/A-1b (based on PDF 1.4) — basic visual preservation * - **1a**: PDF/A-1a — adds logical structure and tagged PDF * - **2b**: PDF/A-2b (based on PDF 1.7) — allows JPEG2000, transparency * - **2a**: PDF/A-2a — adds logical structure * - **2u**: PDF/A-2u — adds Unicode mapping * - **3b**: PDF/A-3b — allows embedded files of any type * - **3a**: PDF/A-3a — adds logical structure * - **3u**: PDF/A-3u — adds Unicode mapping * * Reference: ISO 19005-1:2005, ISO 19005-2:2011, ISO 19005-3:2012. */ /** PDF/A conformance level. */ type PdfALevel = '1b' | '2b' | '3b' | '1a' | '2a' | '3a' | '2u' | '3u'; /** Result of a PDF/A validation check. */ interface PdfAValidationResult { valid: boolean; level: PdfALevel; issues: PdfAIssue[]; } /** A single PDF/A compliance issue. */ interface PdfAIssue { code: string; message: string; severity: 'error' | 'warning'; } /** * Validate a PDF against a specific PDF/A conformance level. * * This performs structural checks on the raw PDF bytes. It does NOT * fully render or deeply parse the PDF — it checks for the presence * or absence of features that PDF/A requires or forbids. * * @param pdfBytes The raw PDF bytes. * @param level The target PDF/A conformance level. * @returns A validation result with any issues found. */ declare function validatePdfA(pdfBytes: Uint8Array, level: PdfALevel): PdfAValidationResult; /** * Attempt to make a PDF conform to PDF/A. * * This adds or corrects: * - XMP metadata with PDF/A identification * - File identifier (/ID) in the trailer * - Document language (if missing, defaults to "en") * * **Limitations:** * - Cannot embed fonts that are not already embedded * - Cannot remove encryption or JavaScript (throws an error) * - Cannot add structure tree for 'a' conformance * - For full PDF/A conversion, use a dedicated tool * * @param pdfBytes The raw PDF bytes. * @param level The target PDF/A conformance level. * @returns The modified PDF bytes. */ declare function enforcePdfA(pdfBytes: Uint8Array, level: PdfALevel): Promise; //#endregion //#region src/compliance/transparencyFlattener.d.ts /** * Transparency flattener for PDF/A-1 compliance. * * PDF/A-1 (ISO 19005-1:2005) prohibits transparency features: * - ExtGState with /CA (stroke opacity) < 1.0 * - ExtGState with /ca (fill opacity) < 1.0 * - /SMask references (soft masks) * - /BM (blend mode) other than /Normal * * This module detects transparency usage and can modify the PDF * to remove or flatten it for PDF/A-1 compliance. */ /** Detected transparency usage in a PDF. */ interface TransparencyInfo { /** Whether any transparency was found. */ readonly hasTransparency: boolean; /** Number of ExtGState objects with non-1.0 CA. */ readonly strokeOpacityCount: number; /** Number of ExtGState objects with non-1.0 ca. */ readonly fillOpacityCount: number; /** Number of SMask references found. */ readonly softMaskCount: number; /** Number of non-Normal blend mode references. */ readonly blendModeCount: number; /** Detailed findings. */ readonly findings: TransparencyFinding[]; } /** A single transparency finding with type, value, and byte position. */ interface TransparencyFinding { readonly type: 'stroke-opacity' | 'fill-opacity' | 'soft-mask' | 'blend-mode'; readonly value: string; readonly position: number; } /** * Analyze PDF bytes for transparency usage. * * Scans the raw PDF text for ExtGState entries that use: * - `/CA ` where value < 1.0 (stroke opacity) * - `/ca ` where value < 1.0 (fill opacity) * - `/SMask ` where ref is not `/None` * - `/BM /` where mode is not `Normal` * * @param pdfBytes The raw PDF bytes. * @returns A {@link TransparencyInfo} describing any transparency found. */ declare function detectTransparency(pdfBytes: Uint8Array): TransparencyInfo; /** * Flatten transparency by modifying PDF bytes. * * This replaces: * - `/CA ` with `/CA 1` (where value < 1) * - `/ca ` with `/ca 1` (where value < 1) * - `/SMask ` with `/SMask /None` * - `/BM /` with `/BM /Normal` * * **Note:** This is a "lossy" operation — semi-transparent elements * will become fully opaque. For print-quality output, manual review * is recommended. * * @param pdfBytes The raw PDF bytes. * @returns Modified PDF bytes with transparency removed. */ declare function flattenTransparency(pdfBytes: Uint8Array): Uint8Array; //#endregion //#region src/compliance/srgbIccProfile.d.ts /** * @module compliance/srgbIccProfile * * Minimal sRGB ICC profile for PDF/A output intents. * * This generates a valid ICC v2 profile (~3KB) that satisfies * PDF/A validators. It uses the standard sRGB primaries and * the sRGB tone response curve (gamma ~ 2.2). * * The sRGB color space is defined by IEC 61966-2.1 and its ICC * profile encodes the D65 white point, the three primary * colorants (red, green, blue), and the tone response curve * (TRC) for each channel. * * Reference: ICC.1:2001-04 (ICC Profile Format Specification). */ /** * Generate a minimal sRGB ICC v2 profile. * * The resulting profile is a valid ICC v2.1.0 profile containing the * minimum set of tags required for a Display profile with 'RGB ' color * space and 'XYZ ' PCS: * * - `desc` — profile description ("sRGB IEC61966-2.1") * - `cprt` — copyright notice * - `wtpt` — media white point (D50) * - `rXYZ`, `gXYZ`, `bXYZ` — red/green/blue colorant XYZ values * - `rTRC`, `gTRC`, `bTRC` — red/green/blue tone response curves (gamma 2.2) * * @returns Raw ICC profile bytes (Uint8Array). */ declare function generateSrgbIccProfile(): Uint8Array; /** * Pre-generated sRGB ICC profile (cached). * * This is computed once at module load time. The profile is a minimal * valid ICC v2.1.0 sRGB profile suitable for embedding in PDF/A * OutputIntent dictionaries. */ declare const SRGB_ICC_PROFILE: Uint8Array; //#endregion //#region src/compliance/outputIntent.d.ts /** * Options for building a PDF/A output intent. */ interface OutputIntentOptions { /** * Output intent subtype. * * Common values: * - `/GTS_PDFA1` — PDF/A-1 (default) * - `/GTS_PDFX` — PDF/X * - `/ISO_PDFE1` — PDF/E * * @default '/GTS_PDFA1' */ subtype?: string; /** * Human-readable output condition description. * * @default 'sRGB' */ outputCondition?: string; /** * Formal registry identifier for the output condition. * * This should match a well-known profile identifier from the * ICC profile registry or a vendor-specific identifier. * * @default 'sRGB IEC61966-2.1' */ outputConditionIdentifier?: string; /** * URL of the ICC profile registry. * * @default 'http://www.color.org' */ registryName?: string; /** * Custom ICC profile bytes to embed instead of the built-in sRGB profile. * * When provided, the caller is responsible for ensuring the profile * is valid and matches the declared output condition. * * @default Built-in minimal sRGB ICC v2 profile. */ iccProfile?: Uint8Array; /** * Number of color components in the ICC profile. * * Must match the profile's color space: * - 3 for RGB profiles * - 4 for CMYK profiles * - 1 for Gray profiles * * @default 3 */ components?: number; } /** * Build an OutputIntent dictionary and register it in the given registry. * * This creates: * 1. An ICC profile stream object (with `/N` set to the number of components) * 2. An OutputIntent dictionary referencing that profile * * Both objects are registered as indirect objects. The returned `PdfRef` * points to the OutputIntent dictionary, which should be added to the * catalog's `/OutputIntents` array. * * @param registry The PDF object registry to register objects into. * @param options Configuration for the output intent. * @returns An indirect reference to the OutputIntent dictionary. * * @example * ```ts * import { PdfObjectRegistry } from 'modern-pdf-lib'; * import { buildOutputIntent } from 'modern-pdf-lib'; * * const registry = new PdfObjectRegistry(); * const intentRef = buildOutputIntent(registry); * // Add intentRef to catalog's /OutputIntents array * ``` */ declare function buildOutputIntent(registry: PdfObjectRegistry, options?: OutputIntentOptions): PdfRef; //#endregion //#region src/compliance/toUnicodeCmap.d.ts /** * @module compliance/toUnicodeCmap * * ToUnicode CMap generator for PDF/A compliance. * * PDF/A-2u (and higher) requires every font to have a ToUnicode CMap * so that text can be extracted from the PDF. The standard 14 fonts * don't normally include this, so we generate it. * * A ToUnicode CMap maps character codes to Unicode code points: * * ``` * /CMapType 2 def * 1 begincodespacerange * <00> * endcodespacerange * N beginbfchar * * endbfchar * ``` * * Three encodings are supported: * - **WinAnsi** (Windows-1252): used by the 12 Latin standard fonts * - **Symbol**: Adobe Symbol encoding * - **ZapfDingbats**: Adobe ZapfDingbats encoding * * Reference: PDF Reference 1.7, Section 5.9 — ToUnicode CMaps; * Adobe Glyph List; Windows-1252 code page. */ /** * Generate a ToUnicode CMap string for a standard WinAnsi-encoded font. * * WinAnsi (Windows-1252) is the default encoding for the 12 Latin * standard 14 fonts (all except Symbol and ZapfDingbats). * This maps each byte code (32–255) to its Unicode equivalent. * * @returns A complete CMap program as a string. */ declare function generateWinAnsiToUnicodeCmap(): string; /** * Generate a ToUnicode CMap for the Symbol font. * * The Symbol font uses the Adobe Symbol encoding, which maps * character codes to Greek letters, mathematical symbols, and * other special characters. * * @returns A complete CMap program as a string. */ declare function generateSymbolToUnicodeCmap(): string; /** * Generate a ToUnicode CMap for the ZapfDingbats font. * * The ZapfDingbats font uses its own built-in encoding that maps * character codes to decorative symbols, arrows, and ornaments. * * @returns A complete CMap program as a string. */ declare function generateZapfDingbatsToUnicodeCmap(): string; /** * Get the appropriate ToUnicode CMap for a standard 14 font. * * - Symbol → Symbol encoding CMap * - ZapfDingbats → ZapfDingbats encoding CMap * - All others → WinAnsi (Windows-1252) encoding CMap * * @param fontName The PDF base font name (e.g. `'Helvetica'`, `'Symbol'`). * @returns A complete CMap program as a string. */ declare function getToUnicodeCmap(fontName: string): string; //#endregion //#region src/compliance/pdfAProfiles.d.ts interface PdfAProfile { readonly part: 1 | 2 | 3; readonly conformance: 'a' | 'b' | 'u'; readonly pdfVersion: string; readonly allowsTransparency: boolean; readonly allowsJpeg2000: boolean; readonly allowsLayers: boolean; readonly allowsEmbeddedFiles: boolean; readonly requiresStructureTree: boolean; readonly requiresToUnicode: boolean; readonly outputIntentSubtype: string; } /** * Get the profile definition for a PDF/A level. */ declare function getProfile(level: PdfALevel): PdfAProfile; /** * Get all supported PDF/A levels. */ declare function getSupportedLevels(): PdfALevel[]; /** * Check if a PDF/A level is supported. */ declare function isValidLevel(level: string): level is PdfALevel; //#endregion //#region src/compliance/xmpValidator.d.ts /** * @module compliance/xmpValidator * * XMP metadata validator for PDF/A compliance. * * PDF/A requires specific XMP metadata properties: * - pdfaid:part — PDF/A part number (1, 2, or 3) * - pdfaid:conformance — Conformance level (A, B, or U) * - dc:title — Document title (recommended) * - xmp:CreateDate — Creation date in ISO 8601 * - xmp:ModifyDate — Modification date in ISO 8601 * - xmp:CreatorTool — Creator application name * - pdf:Producer — PDF producer application * * Reference: ISO 19005-1:2005 §6.6, ISO 19005-2:2011 §6.6. */ /** Result of XMP metadata validation for PDF/A. */ interface XmpValidationResult { readonly valid: boolean; readonly issues: XmpIssue[]; readonly metadata: ParsedXmpMetadata; } /** A single XMP validation issue. */ interface XmpIssue { readonly code: string; readonly message: string; readonly severity: 'error' | 'warning'; readonly namespace?: string; readonly property?: string; } /** Structured XMP metadata extracted from a PDF. */ interface ParsedXmpMetadata { readonly pdfaidPart?: number; readonly pdfaidConformance?: string; readonly dcTitle?: string; readonly xmpCreateDate?: string; readonly xmpModifyDate?: string; readonly xmpCreatorTool?: string; readonly pdfProducer?: string; readonly raw?: string; } /** * Extract XMP metadata from raw PDF bytes. * * Searches for the `` envelope in the * decoded text of the PDF and returns the full XMP XML string, or * `undefined` if no XMP metadata is present. * * @param pdfBytes The raw PDF bytes. * @returns The XMP XML string, or `undefined`. */ declare function extractXmpMetadata(pdfBytes: Uint8Array): string | undefined; /** * Parse an XMP metadata string into structured data. * * Uses lightweight regex-based extraction (no XML parser needed). * Missing properties are returned as `undefined`. * * @param xmp The raw XMP XML string. * @returns Parsed metadata fields. */ declare function parseXmpMetadata(xmp: string): ParsedXmpMetadata; /** * Validate XMP metadata in a PDF against PDF/A requirements. * * Checks that the mandatory PDF/A identification properties exist and * match the expected conformance level. Also reports warnings for * recommended-but-optional fields (CreatorTool, CreateDate, etc.). * * @param pdfBytes The raw PDF bytes. * @param level The target PDF/A conformance level string (e.g. "1b", "2a"). * @returns Validation result with issues and parsed metadata. */ declare function validateXmpMetadata(pdfBytes: Uint8Array, level: string): XmpValidationResult; //#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/compliance/stripProhibited.d.ts /** * Strip PDF/A prohibited features from raw PDF bytes. * * PDF/A prohibits several features. This module removes them * from the raw PDF bytes so that enforcePdfA can fix documents * that would otherwise be rejected. * * Prohibited features (PDF/A-1 through PDF/A-3): * - JavaScript actions (/JS, /JavaScript) * - Launch actions (/Launch) * - Sound actions (/Sound) * - Movie actions (/Movie) * - ResetForm actions (/ResetForm) * - ImportData actions (/ImportData) * - Named actions except NextPage, PrevPage, FirstPage, LastPage * - Encryption (/Encrypt) * - Embedded multimedia (/RichMedia) */ /** Result returned by {@link stripProhibitedFeatures}. */ interface StripResult { /** Modified PDF bytes. */ readonly bytes: Uint8Array; /** Features that were stripped. */ readonly stripped: StrippedFeature[]; /** Whether any modifications were made. */ readonly modified: boolean; } /** A single category of stripped feature. */ interface StrippedFeature { /** Feature type that was stripped (e.g. "JavaScript", "Launch"). */ readonly type: string; /** Number of occurrences that were removed/neutralized. */ readonly count: number; } /** Options controlling which prohibited features to strip. */ interface StripOptions { /** Strip /JavaScript and /JS actions. Default: `true`. */ stripJavaScript?: boolean; /** Strip /Launch actions. Default: `true`. */ stripLaunch?: boolean; /** Strip /Sound actions. Default: `true`. */ stripSound?: boolean; /** Strip /Movie actions. Default: `true`. */ stripMovie?: boolean; /** Strip /RichMedia annotations. Default: `true`. */ stripRichMedia?: boolean; } /** * Count non-overlapping occurrences of `pattern` in `text`. * * @internal Exported only for unit testing. */ declare function countOccurrences(text: string, pattern: string): number; /** * Strip prohibited features from PDF bytes. * * Each prohibited feature category can be individually enabled or disabled * via {@link StripOptions}. By default all categories are stripped. * * Stripping works by replacing action type entries with harmless equivalents * (e.g. `/S /JavaScript` becomes `/S /URI`) and removing inline script * payloads (`/JS (...)` or `/JS <...>`). * * @param pdfBytes - Raw PDF bytes. * @param options - What to strip. All categories enabled by default. * @returns Modified bytes and a strip report. */ declare function stripProhibitedFeatures(pdfBytes: Uint8Array, options?: StripOptions): StripResult; //#endregion //#region src/compliance/xmpGenerator.d.ts /** * @module compliance/xmpGenerator * * XMP metadata generator for PDF/A documents. * * Generates well-formed XMP metadata packets that include all * mandatory and recommended PDF/A fields. Uses the correct * namespace URIs and element structures. * * Mandatory fields (per ISO 19005): * - pdfaid:part — PDF/A part number (1, 2, or 3) * - pdfaid:conformance — Conformance level (A, B, or U) * * Recommended fields: * - dc:title — Document title (Dublin Core) * - dc:creator — Document author (Dublin Core) * - dc:description — Document subject/description (Dublin Core) * - xmp:CreatorTool — Creator application name * - xmp:CreateDate — Creation date in ISO 8601 * - xmp:ModifyDate — Modification date in ISO 8601 * - pdf:Producer — PDF producer application * - pdf:Keywords — Document keywords * * Reference: ISO 19005-1:2005 §6.6, ISO 19005-2:2011 §6.6, ISO 19005-3:2012 §6.6. */ /** Options for generating PDF/A XMP metadata. */ interface PdfAXmpOptions { /** PDF/A part number (1, 2, or 3). */ readonly part: number; /** PDF/A conformance level ('A', 'B', or 'U'). */ readonly conformance: string; /** Document title. */ readonly title?: string; /** Document author. */ readonly author?: string; /** Document subject/description. */ readonly subject?: string; /** Keywords. */ readonly keywords?: string; /** Creator tool name. Default: 'modern-pdf-lib'. */ readonly creatorTool?: string; /** PDF producer name. Default: 'modern-pdf-lib'. */ readonly producer?: string; /** Creation date (ISO 8601). Default: current date. */ readonly createDate?: string; /** Modification date (ISO 8601). Default: current date. */ readonly modifyDate?: string; /** Document language (BCP 47). Default: 'en'. */ readonly language?: string; } /** * Generate a complete XMP metadata packet for PDF/A. * * The returned string is a well-formed XMP packet wrapped in * `` processing instructions and containing separate * `rdf:Description` blocks for each namespace. * * @param options - Metadata options including the mandatory `part` * and `conformance` fields. * @returns XMP metadata as a string. */ declare function generatePdfAXmp(options: PdfAXmpOptions): string; /** * Generate XMP metadata bytes for embedding in a PDF stream. * * This is a convenience wrapper around {@link generatePdfAXmp} that * encodes the resulting string as UTF-8 bytes suitable for use in a * PDF metadata stream object. * * @param options - Metadata options. * @returns XMP metadata as a `Uint8Array`. */ declare function generatePdfAXmpBytes(options: PdfAXmpOptions): Uint8Array; //#endregion //#region src/compliance/enforcePdfAv2.d.ts /** Options for the enhanced PDF/A enforcement pipeline. */ interface EnforcePdfAOptions { /** Whether to strip JavaScript and other prohibited actions. Default: true. */ readonly stripProhibited?: boolean; /** Whether to flatten transparency for PDF/A-1. Default: true. */ readonly flattenTransparency?: boolean; /** Whether to add XMP metadata. Default: true. */ readonly addXmpMetadata?: boolean; /** Whether to add file ID. Default: true. */ readonly addFileId?: boolean; /** Document title for XMP metadata. */ readonly title?: string; /** Document author for XMP metadata. */ readonly author?: string; /** Document language. Default: 'en'. */ readonly language?: string; } /** Result of the enhanced PDF/A enforcement. */ interface EnforcePdfAResult { /** Modified PDF bytes. */ readonly bytes: Uint8Array; /** Validation result after enforcement. */ readonly validation: PdfAValidationResult; /** Actions taken during enforcement. */ readonly actions: EnforcementAction[]; /** Whether all errors were resolved. */ readonly fullyCompliant: boolean; /** Remaining error-level issues (if any). */ readonly remainingIssues: number; } /** A single action taken during enforcement. */ interface EnforcementAction { readonly action: string; readonly description: string; } /** * Enforce PDF/A compliance with a full pipeline. * * Unlike the basic `enforcePdfA()` which only adds XMP metadata and /ID * (and throws on JavaScript), this function actively: * * 1. **Strips** prohibited features (JavaScript, Launch, Sound, Movie, * RichMedia) so they no longer cause validation failures. * 2. **Flattens** transparency features for PDF/A-1 (sets opacity to 1.0, * replaces SMask with /None, normalizes blend modes to /Normal). * 3. **Adds** XMP metadata with correct `pdfaid:part` and * `pdfaid:conformance` values. * 4. **Adds** a file identifier (`/ID`) to the trailer when missing. * 5. **Validates** the result and reports remaining issues. * * @param pdfBytes The raw PDF bytes. * @param level The target PDF/A conformance level (e.g. '1b', '2b'). * @param options Fine-grained control over which steps to execute. * @returns The enforcement result including modified bytes, * validation report, and actions taken. * * @throws {Error} If the PDF is encrypted (cannot be fixed automatically). * * @example * ```ts * import { enforcePdfAFull } from 'modern-pdf-lib'; * * const result = await enforcePdfAFull(pdfBytes, '1b', { * title: 'My Document', * author: 'Jane Doe', * }); * * if (result.fullyCompliant) { * console.log('PDF/A-1b compliant!'); * } * ``` */ declare function enforcePdfAFull(pdfBytes: Uint8Array, level: PdfALevel, options?: EnforcePdfAOptions): Promise; //#endregion //#region src/annotation/applyRedactions.d.ts /** Result of applying redactions to a document. */ interface RedactionResult { /** Total number of redaction annotations that were applied. */ appliedCount: number; /** Zero-based indices of pages that had redactions applied. */ pages: number[]; } /** * Apply a single redaction annotation identified by page and annotation * index. * * @param doc The PDF document. * @param pageIndex Zero-based page index. * @param annotIndex Zero-based annotation index within the page. * @returns A {@link RedactionResult} (appliedCount 0 or 1). * @throws RangeError if pageIndex or annotIndex is out of bounds. * @throws TypeError if the annotation at annotIndex is not a * /Redact annotation. */ declare function applyRedaction(doc: PdfDocument, pageIndex: number, annotIndex: number): RedactionResult; //#endregion //#region src/wasm/jpeg/bridge.d.ts /** * @module wasm/jpeg/bridge * * TypeScript bridge for the JPEG WASM encoder/decoder module. * * Provides JPEG encoding (raw pixels → JPEG bytes) and decoding (JPEG bytes → * raw pixels) via a Rust WASM module compiled with wasm-bindgen. * * If the WASM module is not available, all functions fail gracefully and * callers should fall back to JS alternatives. * * No Buffer — uses Uint8Array exclusively. */ /** Pre-built wasm-bindgen module interface (when passed directly). */ interface JpegWasmModule { encode_jpeg(pixels: Uint8Array, width: number, height: number, channels: number, quality: number, progressive: boolean, chroma_subsampling: number): Uint8Array; decode_jpeg(data: Uint8Array): Uint8Array; } /** * Chroma subsampling modes for JPEG encoding. * * - `'4:4:4'`: No subsampling — best quality, largest file. * - `'4:2:2'`: Horizontal subsampling — good balance. * - `'4:2:0'`: Both directions — smallest file, default for most encoders. */ type ChromaSubsampling = '4:4:4' | '4:2:2' | '4:2:0'; /** Result of decoding a JPEG image. */ interface JpegDecodeResult { /** Raw pixel data (row-major, channel-interleaved). */ readonly pixels: Uint8Array; /** Image width in pixels. */ readonly width: number; /** Image height in pixels. */ readonly height: number; /** Number of channels (1=grayscale, 3=RGB). */ readonly channels: number; } /** * Initialize the JPEG WASM module. * * @param wasmSource - The WASM binary as `Uint8Array`, URL, `Response`, * or a pre-built wasm-bindgen module. When omitted, * the function uses the universal WASM loader. */ declare function initJpegWasm(wasmSource?: JpegWasmModule | Uint8Array | URL | string | Response): Promise; /** * Check whether the JPEG WASM module has been initialized. * * @returns `true` if {@link initJpegWasm} completed successfully. */ declare function isJpegWasmReady(): boolean; /** * Encode raw pixel data to JPEG using the WASM encoder. * * @param pixels - Raw pixel data (row-major, channel-interleaved). * @param width - Image width in pixels. * @param height - Image height in pixels. * @param channels - Number of channels: 1 (grayscale), 3 (RGB), or 4 (RGBA). * @param quality - JPEG quality 1–100. * @param progressive - Encode as progressive JPEG (default: false). * @param chroma - Chroma subsampling mode (default: '4:2:0'). * @returns JPEG-encoded bytes, or `undefined` if WASM is not available. */ declare function encodeJpegWasm(pixels: Uint8Array, width: number, height: number, channels: 1 | 3 | 4, quality: number, progressive?: boolean, chroma?: ChromaSubsampling): Uint8Array | undefined; /** * Decode JPEG bytes to raw pixel data using the WASM decoder. * * The WASM module returns a flat byte array with layout: * `[width_u32_le, height_u32_le, channels_u8, ...pixels]`. * * @param jpegBytes - JPEG-encoded image data. * @returns Decoded pixel data with metadata, or `undefined` if WASM is not * available or decoding failed. */ declare function decodeJpegWasm(jpegBytes: Uint8Array): JpegDecodeResult | undefined; //#endregion //#region src/assets/image/imageOptimize.d.ts /** * Options for image downscaling. */ interface DownscaleOptions { /** Target maximum width in pixels. The image is scaled proportionally. */ readonly maxWidth?: number; /** Target maximum height in pixels. The image is scaled proportionally. */ readonly maxHeight?: number; /** * Target DPI for the image at its intended print size. If specified * along with `printWidth` / `printHeight`, the image is downscaled * to match the target DPI. * * For example, a 3000×2000 image printed at 10×6.67 inches would be * 300 DPI. Setting `targetDpi: 150` would downscale to 1500×1000. */ readonly targetDpi?: number; /** * Intended print width in points (1/72 inch). * Used together with `targetDpi` to compute the target pixel dimensions. */ readonly printWidth?: number; /** * Intended print height in points (1/72 inch). * Used together with `targetDpi` to compute the target pixel dimensions. */ readonly printHeight?: number; /** * Resampling algorithm. * - `'nearest'`: Nearest-neighbor (fast, blocky) * - `'bilinear'`: Bilinear interpolation (good quality, moderate speed) * - `'lanczos'`: Lanczos-3 resampling (best quality, slowest) * * Default: `'lanczos'`. */ readonly algorithm?: 'nearest' | 'bilinear' | 'lanczos'; } /** * Options for image recompression. */ interface RecompressOptions { /** * Output format. * - `'jpeg'`: JPEG compression (lossy, good for photographs) * - `'deflate'`: Deflate/zlib compression (lossless, used in PDF FlateDecode) * * Default: `'deflate'`. */ readonly format?: 'jpeg' | 'deflate'; /** * JPEG quality (1–100). Only used when `format` is `'jpeg'`. * Higher values produce larger files with better quality. * * Default: `85`. */ readonly quality?: number; /** * Deflate compression level (1–9). Only used when `format` is `'deflate'`. * Higher values produce smaller files but take longer. * * Default: `6`. */ readonly compressionLevel?: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; /** * Encode as progressive JPEG. Only used when `format` is `'jpeg'`. * * Progressive JPEGs render in multiple passes (low-res → full-res) * which improves perceived loading speed on slow connections. * They are also often slightly smaller than baseline JPEGs. * * Requires the JPEG WASM module to be initialized. * * Default: `false`. */ readonly progressive?: boolean; /** * Chroma subsampling mode. Only used when `format` is `'jpeg'`. * * - `'4:4:4'`: No subsampling — best color fidelity, largest file. * - `'4:2:2'`: Horizontal subsampling — good balance. * - `'4:2:0'`: Both horizontal and vertical — smallest file. * * Requires the JPEG WASM module to be initialized. * * Default: `'4:2:0'`. */ readonly chromaSubsampling?: ChromaSubsampling; } /** * Combined options for the full optimization pipeline. */ interface ImageOptimizeOptions extends DownscaleOptions, RecompressOptions { /** * Skip optimization if the input data is already smaller than this * threshold (in bytes). * * Default: `0` (always optimize). */ readonly skipBelowBytes?: number; } /** * Raw image pixel data with metadata. */ interface RawImageData { /** Pixel data in row-major order, channel-interleaved. */ readonly pixels: Uint8Array; /** Image width in pixels. */ readonly width: number; /** Image height in pixels. */ readonly height: number; /** * Number of channels: * - 1: Grayscale * - 2: Grayscale + Alpha * - 3: RGB * - 4: RGBA or CMYK (see `colorSpace`) */ readonly channels: 1 | 2 | 3 | 4; /** Bits per channel (typically 8). */ readonly bitsPerChannel: number; /** * Color space of the pixel data. * * - `'rgb'` — Channels are R, G, B (and optionally A). * - `'cmyk'` — Channels are C, M, Y, K (only when `channels` is 4). * CMYK pixels are converted to RGB before JPEG encoding. * - `'gray'` — Grayscale (only when `channels` is 1 or 2). * * Default: inferred from channel count (`1|2 → 'gray'`, `3|4 → 'rgb'`). */ readonly colorSpace?: 'rgb' | 'cmyk' | 'gray'; } /** * The result of an optimization operation. */ interface OptimizeResult { /** The optimized pixel data (or compressed data if recompressed). */ readonly data: Uint8Array; /** Output width in pixels. */ readonly width: number; /** Output height in pixels. */ readonly height: number; /** Number of channels in the output. */ readonly channels: number; /** The compression format applied, if any. */ readonly format: 'raw' | 'jpeg' | 'deflate'; /** Whether any actual optimization was performed. */ readonly wasOptimized: boolean; } /** * Downscale an image to fit within the specified dimensions. * * If the image is already smaller than the target dimensions, it is * returned unchanged. * * @param image - The raw image pixel data. * @param options - Downscaling options (target dimensions, algorithm). * @returns The downscaled image, or the original if no scaling needed. * * @example * ```ts * const result = downscaleImage(rawImage, { * maxWidth: 1024, * maxHeight: 768, * algorithm: 'lanczos', * }); * ``` */ declare function downscaleImage(image: RawImageData, options?: DownscaleOptions): RawImageData; /** * Recompress raw image pixel data using the specified format. * * @param image - The raw image pixel data. * @param options - Recompression options (format, quality). * @returns The compressed image data. * * @example * ```ts * const result = await recompressImage(rawImage, { * format: 'deflate', * compressionLevel: 9, * }); * ``` */ declare function recompressImage(image: RawImageData, options?: RecompressOptions): Promise; /** * Run the full image optimization pipeline: downscale then recompress. * * @param image - The raw image pixel data. * @param options - Combined optimization options. * @returns The optimized result. */ declare function optimizeImage(image: RawImageData, options?: ImageOptimizeOptions): Promise; /** * Estimate the JPEG quality level (1–100) from the quantization tables * embedded in a JPEG file. * * Parses the DQT (Define Quantization Table, marker 0xFFDB) segments * from the raw JPEG bytes and compares the table values against the * standard JPEG luminance quantization table to estimate the quality * factor that was used during encoding. * * If no DQT marker is found, returns `undefined`. * * @param jpegBytes - Raw JPEG file bytes. * @returns Estimated quality 1–100, or `undefined` if no DQT is found. * * @example * ```ts * import { estimateJpegQuality } from 'modern-pdf-lib'; * * const quality = estimateJpegQuality(jpegBytes); * if (quality !== undefined) { * console.log(`Estimated JPEG quality: ${quality}`); * } * ``` */ declare function estimateJpegQuality(jpegBytes: Uint8Array): number | undefined; //#endregion //#region src/assets/image/batchOptimize.d.ts /** * Progress information passed to the `onProgress` callback. */ interface ProgressInfo { /** 1-based index of the current image being processed. */ readonly current: number; /** Total number of images to process. */ readonly total: number; /** Resource name of the current image (e.g., '/Im1'). */ readonly imageName: string; /** Page index (0-based) where the image appears. */ readonly pageIndex: number; /** Bytes saved for this image (negative if image grew). */ readonly savedBytes: number; /** Cumulative bytes saved so far. */ readonly totalSavedBytes: number; /** Whether this image was skipped (by filter or incompatibility). */ readonly skipped: boolean; } /** * Options for batch image optimization. */ interface BatchOptimizeOptions { /** * JPEG quality (1–100) for recompressed images. * * Default: `80`. */ readonly quality?: number; /** * Maximum DPI for images. Images exceeding this DPI at their * display size will be downscaled before recompression. * * Default: `150`. */ readonly maxDpi?: number; /** * Encode as progressive JPEG. * * Default: `false`. */ readonly progressive?: boolean; /** * Chroma subsampling mode for JPEG encoding. * * Default: `'4:2:0'`. */ readonly chromaSubsampling?: ChromaSubsampling; /** * Skip images smaller than this threshold (in bytes). * * Default: `false` (process all images). */ readonly skipSmallImages?: boolean; /** * Minimum savings percentage required to replace an image. * If the recompressed image is not at least this much smaller, * the original is kept. * * Default: `10`. */ readonly minSavingsPercent?: number; /** * Auto-detect and convert pseudo-grayscale RGB images to true * grayscale before encoding. * * Default: `false`. */ readonly autoGrayscale?: boolean; /** * Only optimize images on pages within this range (0-indexed, inclusive). * * Images on pages outside this range are skipped and counted as * `skippedByFilter` in the report. */ readonly pageRange?: { readonly start: number; readonly end: number; }; /** * Skip images with compressed size below this threshold in bytes. * * Default: `0` (no minimum). */ readonly minImageSize?: number; /** * Only optimize images in these color spaces * (e.g. `'DeviceRGB'`, `'DeviceCMYK'`, `'ICCBased'`). * * Images in other color spaces are skipped. */ readonly colorSpaces?: readonly string[]; /** * Only optimize images whose resource name matches this pattern. * * For example, `/Im[0-3]/` would only optimize images named * `/Im0` through `/Im3`. */ readonly namePattern?: RegExp; /** * Maximum number of images to process concurrently. * * Default: `1` (sequential). Values less than 1 are treated as 1. */ readonly concurrency?: number; /** * Progress callback invoked after each image is processed. */ readonly onProgress?: (info: ProgressInfo) => void; } /** * Per-image optimization report entry. */ interface ImageOptimizeEntry { /** Resource name (e.g. '/Im1'). */ readonly name: string; /** Page index where this image appears. */ readonly pageIndex: number; /** Original compressed size in bytes. */ readonly originalSize: number; /** New compressed size in bytes (same as original if skipped). */ readonly newSize: number; /** Whether this image was skipped. */ readonly skipped: boolean; /** Whether this image was skipped due to a selective filter. */ readonly skippedByFilter: boolean; /** Reason for skipping, if applicable. */ readonly reason?: string; } /** * Summary report from batch image optimization. */ interface OptimizationReport { /** Total number of image XObjects found. */ readonly totalImages: number; /** Number of images that were recompressed. */ readonly optimizedImages: number; /** Number of images skipped due to selective filters. */ readonly skippedByFilter: number; /** Total original compressed size (all images). */ readonly originalTotalBytes: number; /** Total new compressed size (all images). */ readonly optimizedTotalBytes: number; /** Overall savings percentage. */ readonly savings: number; /** Per-image details. */ readonly perImage: readonly ImageOptimizeEntry[]; } /** * Optimize all images in a PDF document by recompressing them as JPEG. * * Walks every image XObject in the document, decodes its pixel data, * recompresses it as JPEG using the WASM encoder (if available), and * replaces the stream data in-place when the result is smaller. * * **Requires the JPEG WASM module to be initialized** via * `initJpegWasm()` or `initWasm({ jpeg: true })`. Without it, * no images will be optimized (all will be skipped). * * @param doc - A parsed `PdfDocument` (from `loadPdf()`). * @param options - Optimization settings. * @returns A report summarizing the optimization results. * * @example * ```ts * import { loadPdf, initWasm, optimizeAllImages } from 'modern-pdf-lib'; * * await initWasm({ jpeg: true }); * * const doc = await loadPdf(pdfBytes); * const report = await optimizeAllImages(doc); * * console.log(`Optimized ${report.optimizedImages} of ${report.totalImages} images`); * console.log(`Savings: ${report.savings.toFixed(1)}%`); * * const optimizedBytes = await doc.save(); * ``` */ declare function optimizeAllImages(doc: PdfDocument, options?: BatchOptimizeOptions): Promise; //#endregion //#region src/assets/image/deduplicateImages.d.ts /** * Report from image deduplication. */ interface DeduplicationReport { /** Total number of image XObjects found. */ readonly totalImages: number; /** Number of unique images (after deduplication). */ readonly uniqueImages: number; /** Number of duplicate references replaced. */ readonly duplicatesRemoved: number; /** Estimated bytes saved by deduplication. */ readonly bytesSaved: number; } /** * Deduplicate identical images in a PDF document. * * Scans all image XObjects, hashes their compressed stream data (plus * dimensions and filter), and replaces duplicate references in page * resource dictionaries with the canonical (first-seen) copy. * * This operation modifies the document in-place. Duplicate streams * are not removed from the object registry (they become unreferenced * and will be omitted on save if the writer supports garbage collection). * * @param doc - A parsed `PdfDocument` (from `loadPdf()`). * @returns A report summarizing deduplication results. * * @example * ```ts * import { loadPdf, deduplicateImages } from 'modern-pdf-lib'; * * const doc = await loadPdf(pdfBytes); * const report = await deduplicateImages(doc); * * console.log(`Removed ${report.duplicatesRemoved} duplicate images`); * console.log(`Saved ~${(report.bytesSaved / 1024).toFixed(0)} KB`); * * const optimizedBytes = await doc.save(); * ``` */ declare function deduplicateImages(doc: PdfDocument): DeduplicationReport; //#endregion //#region src/assets/image/grayscaleDetect.d.ts /** * @module assets/image/grayscaleDetect * * Grayscale detection and conversion for image optimization. * * Detects RGB images where all pixels are effectively grayscale * (R ≈ G ≈ B) and converts them to single-channel grayscale, * reducing data size by ~66%. * * No Buffer — uses Uint8Array exclusively. */ /** * Check whether an RGB/RGBA image is effectively grayscale. * * Scans all pixels and checks if R, G, and B channels are within * `tolerance` of each other. If ≥99% of pixels pass, the image * is considered grayscale. * * @param pixels - Raw pixel data (row-major, channel-interleaved). * @param width - Image width in pixels. * @param height - Image height in pixels. * @param channels - Number of channels: 3 (RGB) or 4 (RGBA). * @param tolerance - Maximum allowed difference between R, G, and B * values for a pixel to be considered gray. * Default: `2`. * @returns `true` if the image is effectively grayscale. * * @example * ```ts * import { isGrayscaleImage, convertToGrayscale } from 'modern-pdf-lib'; * * if (isGrayscaleImage(pixels, width, height, 3)) { * const grayPixels = convertToGrayscale(pixels, width, height, 3); * // grayPixels has 1 byte per pixel instead of 3 * } * ``` */ declare function isGrayscaleImage(pixels: Uint8Array, width: number, height: number, channels: 3 | 4, tolerance?: number): boolean; /** * Convert an RGB/RGBA image to single-channel grayscale. * * Uses the ITU-R BT.601 luma formula: * ``` * gray = 0.299 × R + 0.587 × G + 0.114 × B * ``` * * The alpha channel (if present) is discarded. * * @param pixels - Raw pixel data (row-major, channel-interleaved). * @param width - Image width in pixels. * @param height - Image height in pixels. * @param channels - Number of channels: 3 (RGB) or 4 (RGBA). * @returns Grayscale pixel data (1 byte per pixel). */ declare function convertToGrayscale(pixels: Uint8Array, width: number, height: number, channels: 3 | 4): Uint8Array; //#endregion //#region src/assets/image/iccProfile.d.ts /** * Represents an extracted ICC color profile. */ interface IccProfile { /** Raw ICC profile data bytes. */ readonly data: Uint8Array; /** Number of color components (1 = gray, 3 = RGB, 4 = CMYK). */ readonly components: number; /** ICC color space signature (e.g. 'RGB ', 'CMYK', 'GRAY'). */ readonly colorSpace: string; /** Human-readable profile description from the 'desc' tag, if present. */ readonly description: string | undefined; } /** * Read the color space signature from raw ICC profile data. * * The ICC profile header stores a 4-byte color space of data field * at byte offset 16. This function reads and decodes that signature * into a human-readable string. * * @param data - Raw ICC profile bytes. * @returns The color space name (e.g. `'RGB'`, `'CMYK'`, `'GRAY'`), * or `'Unknown'` if the data is too short or the signature * is not recognized. * * @example * ```ts * import { parseIccColorSpace } from 'modern-pdf-lib'; * * const colorSpace = parseIccColorSpace(iccProfileBytes); * console.log(colorSpace); // 'RGB' * ``` */ declare function parseIccColorSpace(data: Uint8Array): string; /** * Parse the human-readable description from an ICC profile's 'desc' tag. * * Searches the ICC tag table for a tag with signature `'desc'` * (0x64657363) and reads the ASCII description string from it. * * The 'desc' tag (ICC v2) has the structure: * - Bytes 0–3: type signature ('desc') * - Bytes 4–7: reserved (0) * - Bytes 8–11: ASCII description length (uint32 BE) * - Bytes 12+: ASCII description string * * @param data - Raw ICC profile bytes. * @returns The description string, or `undefined` if the tag is not * found or cannot be parsed. */ declare function parseIccDescription(data: Uint8Array): string | undefined; /** * Extract the ICC color profile from a PDF image XObject's `/ColorSpace`. * * Checks whether the image's `/ColorSpace` entry is an ICCBased array * (i.e. `[/ICCBased ]`), and if so, extracts the raw ICC * profile bytes and metadata from the referenced stream. * * @param stream - The `PdfStream` for the image XObject. * @param registry - The document's `PdfObjectRegistry` for resolving * indirect references. * @returns An `IccProfile` if the image uses an ICCBased color space, * or `undefined` if no ICC profile is attached. * * @example * ```ts * import { extractIccProfile, extractImages, loadPdf } from 'modern-pdf-lib'; * * const doc = await loadPdf(pdfBytes); * const images = extractImages(doc); * * for (const img of images) { * const profile = extractIccProfile(img.stream, doc.getRegistry()); * if (profile) { * console.log(`ICC: ${profile.colorSpace}, ${profile.components} channels`); * console.log(`Description: ${profile.description ?? 'none'}`); * } * } * ``` */ declare function extractIccProfile(stream: PdfStream, registry: PdfObjectRegistry): IccProfile | undefined; /** * Embed an ICC color profile into the PDF object registry and return * a reference that can be used as a `/ColorSpace` entry. * * Creates a new `PdfStream` for the ICC profile data with the required * `/N` (number of components) entry, registers it, and returns a * `PdfRef` to the stream. The caller should then set the image's * `/ColorSpace` to `[/ICCBased ]`. * * @param profile - The `IccProfile` to embed. * @param registry - The document's `PdfObjectRegistry`. * @returns A `PdfRef` pointing to the newly created ICC profile stream. * * @example * ```ts * import { embedIccProfile, extractIccProfile } from 'modern-pdf-lib'; * * const profile = extractIccProfile(imageStream, registry); * if (profile) { * const profileRef = embedIccProfile(profile, registry); * const colorSpace = PdfArray.of([PdfName.of('/ICCBased'), profileRef]); * imageStream.dict.set('/ColorSpace', colorSpace); * } * ``` */ declare function embedIccProfile(profile: IccProfile, registry: PdfObjectRegistry): PdfRef; //#endregion //#region src/assets/image/dpiAnalyze.d.ts /** * @module assets/image/dpiAnalyze * * DPI analysis for PDF image XObjects. * * Computes the effective DPI of an image based on its pixel dimensions * and its display size in the PDF (determined by the content stream's * current transformation matrix). * * No Buffer — uses Uint8Array exclusively. */ /** * DPI information for an image. */ interface ImageDpi { /** Horizontal DPI. */ readonly xDpi: number; /** Vertical DPI. */ readonly yDpi: number; /** Effective DPI (minimum of xDpi and yDpi). */ readonly effectiveDpi: number; } /** * Compute the effective DPI of an image given its pixel dimensions * and display dimensions in points. * * PDF uses 72 points per inch, so: * ``` * DPI = imagePixels / (displayPoints / 72) * ``` * * @param imageWidth - Image width in pixels. * @param imageHeight - Image height in pixels. * @param displayWidth - Display width in PDF points (1/72 inch). * @param displayHeight - Display height in PDF points (1/72 inch). * @returns DPI information. * * @example * ```ts * import { computeImageDpi } from 'modern-pdf-lib'; * * // A 3000×2000 image displayed at 4.17×2.78 inches (300×200 points) * const dpi = computeImageDpi(3000, 2000, 300, 200); * console.log(dpi.effectiveDpi); // 720 * ``` */ declare function computeImageDpi(imageWidth: number, imageHeight: number, displayWidth: number, displayHeight: number): ImageDpi; /** * Compute the target pixel dimensions for downscaling an image * to a maximum DPI at a given display size. * * @param imageWidth - Current image width in pixels. * @param imageHeight - Current image height in pixels. * @param displayWidth - Display width in PDF points. * @param displayHeight - Display height in PDF points. * @param maxDpi - Maximum allowed DPI. * @returns Target dimensions, or the original dimensions if no * downscaling is needed. */ declare function computeTargetDimensions(imageWidth: number, imageHeight: number, displayWidth: number, displayHeight: number, maxDpi: number): { width: number; height: number; downscaled: boolean; }; //#endregion //#region src/assets/image/jpegMarkers.d.ts /** * @module assets/image/jpegMarkers * * JPEG marker analysis for detecting arithmetic coding and other properties. * * Scans JPEG marker segments without decoding image data to determine * the coding method (Huffman vs arithmetic), progressive vs sequential * encoding, and basic frame parameters (width, height, components, bpc). * * This is useful for PDF batch optimization: arithmetic-coded JPEGs * (SOF9/SOF10/SOF11) cannot be decoded by most JPEG decoders and must * be skipped during recompression. * * No Buffer — uses Uint8Array exclusively. */ /** Result of JPEG marker analysis. */ interface JpegMarkerInfo { /** Whether the JPEG uses arithmetic coding (SOF9, SOF10, or SOF11). */ readonly isArithmeticCoded: boolean; /** Whether the JPEG uses progressive encoding (SOF2 or SOF10). */ readonly isProgressive: boolean; /** The SOF marker type (e.g. 0xC0 for baseline, 0xC2 for progressive). */ readonly sofType: number; /** Image width in pixels. */ readonly width: number; /** Image height in pixels. */ readonly height: number; /** Number of color components (1=gray, 3=YCbCr, 4=CMYK). */ readonly components: number; /** Bits per component (typically 8, sometimes 12). */ readonly bitsPerComponent: number; } /** * Parse JPEG markers to detect arithmetic coding and other properties. * Scans marker segments without decoding image data. * * @param data - Raw JPEG bytes (must start with FF D8). * @returns Marker info, or `undefined` if not valid JPEG. * * @example * ```ts * import { analyzeJpegMarkers } from 'modern-pdf-lib'; * * const info = analyzeJpegMarkers(jpegBytes); * if (info?.isArithmeticCoded) { * console.log('Cannot re-encode: arithmetic-coded JPEG'); * } * ``` */ declare function analyzeJpegMarkers(data: Uint8Array): JpegMarkerInfo | undefined; //#endregion //#region src/assets/image/imageMetadata.d.ts /** * @module assets/image/imageMetadata * * JPEG EXIF metadata extraction and re-injection. * * When images are recompressed (e.g. via `encodeJpegWasm()`), the encoder * produces a minimal JPEG containing only SOI + DQT + SOF + DHT + SOS. * All APP markers — including JFIF (APP0) and EXIF (APP1) — are stripped. * * This module extracts key metadata fields (orientation, DPI, copyright) * and the raw APP marker segments from the original JPEG, then re-injects * them into the recompressed output so that downstream consumers (PDF * viewers, print RIPs, image editors) see correct metadata. * * APP2 (ICC profile) markers are excluded because ICC profiles are * handled separately by `iccProfile.ts`. * * No Buffer — uses Uint8Array exclusively. */ /** * Extracted JPEG metadata from APP markers. */ interface JpegMetadata { /** EXIF orientation tag (1-8). 1 = normal, 6 = rotated 90 CW, etc. */ readonly orientation?: number; /** Horizontal DPI from EXIF or JFIF. */ readonly dpiX?: number; /** Vertical DPI from EXIF or JFIF. */ readonly dpiY?: number; /** Copyright string from EXIF. */ readonly copyright?: string; /** Raw APP marker segments to preserve (excluding APP2/ICC). */ readonly appMarkers: readonly Uint8Array[]; } /** * Extract metadata from JPEG APP markers. * * Scans after the SOI (FF D8) marker for APP markers (FF E0 through FF EF). * Extracts key metadata from JFIF (APP0) and EXIF (APP1) segments, and * collects all APP marker segments as raw bytes (excluding APP2/ICC, which * is handled separately by `iccProfile.ts`). * * Scanning stops at the first non-APP marker (SOF, DQT, DHT, SOS, etc.). * * @param jpegBytes - Raw JPEG file bytes. * @returns Extracted metadata with collected APP marker segments. * * @example * ```ts * import { extractJpegMetadata } from 'modern-pdf-lib'; * * const metadata = extractJpegMetadata(jpegBytes); * console.log(`Orientation: ${metadata.orientation}`); * console.log(`DPI: ${metadata.dpiX} x ${metadata.dpiY}`); * console.log(`Copyright: ${metadata.copyright}`); * ``` */ declare function extractJpegMetadata(jpegBytes: Uint8Array): JpegMetadata; /** * Inject preserved APP markers into a recompressed JPEG. * * Inserts the collected APP marker segments after the SOI (FF D8) marker * and before any existing content. This restores metadata that was * stripped during recompression. * * @param jpegBytes - The recompressed JPEG bytes (starting with FF D8). * @param metadata - The metadata extracted from the original JPEG. * @returns A new Uint8Array with the APP markers injected. * * @example * ```ts * import { extractJpegMetadata, injectJpegMetadata } from 'modern-pdf-lib'; * * // Before recompression, extract metadata from original * const metadata = extractJpegMetadata(originalJpeg); * * // After recompression, inject metadata back * const recompressed = encodeJpegWasm(pixels, w, h, 3, 85); * const withMetadata = injectJpegMetadata(recompressed, metadata); * ``` */ declare function injectJpegMetadata(jpegBytes: Uint8Array, metadata: JpegMetadata): Uint8Array; //#endregion //#region src/assets/image/tiffCmyk.d.ts /** * @module assets/image/tiffCmyk * * TIFF CMYK color space handling for PDF embedding. * * Provides: * - CMYK-to-RGB conversion for display/rendering * - Native CMYK embedding in PDF (no conversion needed) * - CMYK TIFF detection via IFD tag inspection * * No Buffer — uses Uint8Array exclusively. * No fs — no file system access. * No require() — ESM import only. */ /** * An IFD entry from a TIFF file, containing a tag number and its value. */ interface TiffIfdEntry { /** The TIFF tag number (e.g. 262 for PhotometricInterpretation). */ readonly tag: number; /** The resolved integer value of the tag. */ readonly value: number; } /** * Result of embedding CMYK TIFF data for use in a PDF image XObject. */ interface TiffCmykEmbedResult { /** PDF color space — always `'DeviceCMYK'`. */ readonly colorSpace: string; /** The raw CMYK pixel data (4 channels, 8 bits per component). */ readonly data: Uint8Array; /** Bits per component — always `8`. */ readonly bitsPerComponent: number; } /** * Convert CMYK pixel data to RGB. * * Uses the standard CMYK-to-RGB formula: * ``` * R = 255 * (1 - C/255) * (1 - K/255) * G = 255 * (1 - M/255) * (1 - K/255) * B = 255 * (1 - Y/255) * (1 - K/255) * ``` * * @param cmykPixels Flat array of CMYK pixel data (4 bytes per pixel: C, M, Y, K). * @param width Image width in pixels. * @param height Image height in pixels. * @returns Flat array of RGB pixel data (3 bytes per pixel: R, G, B). * @throws If the input array length does not match width * height * 4. */ declare function convertTiffCmykToRgb(cmykPixels: Uint8Array, width: number, height: number): Uint8Array; /** * Prepare CMYK pixel data for native embedding in a PDF using /DeviceCMYK. * * PDF natively supports CMYK color spaces, so no RGB conversion is * needed — the raw CMYK data can be used directly as the image stream. * * @param pixels Flat array of CMYK pixel data (4 bytes per pixel: C, M, Y, K). * @param width Image width in pixels. * @param height Image height in pixels. * @returns Embedding result with colorSpace, data, and bitsPerComponent. * @throws If the input array length does not match width * height * 4. */ declare function embedTiffCmyk(pixels: Uint8Array, width: number, height: number): TiffCmykEmbedResult; /** * Detect whether a TIFF image uses CMYK color space by inspecting IFD entries. * * A TIFF is considered CMYK when: * - PhotometricInterpretation (tag 262) has value 5 (Separated), AND * - If InkSet (tag 332) is present, its value must be 1 (CMYK inks) * * If InkSet is not present but PhotometricInterpretation is 5, the image * is assumed to be CMYK (per the TIFF specification default). * * @param ifdEntries Array of IFD entries with tag and value fields. * @returns `true` if the TIFF uses CMYK color space. */ declare function isCmykTiff(ifdEntries: Array<{ tag: number; value: number; }>): boolean; //#endregion //#region src/assets/image/formatDetect.d.ts /** * @module assets/image/formatDetect * * Image format detection from magic bytes. * * Detects the following image formats by inspecting the file header: * - **PNG**: `89 50 4E 47` (first 4 bytes) * - **JPEG**: `FF D8 FF` (first 3 bytes) * - **WebP**: `52 49 46 46` (RIFF) at offset 0 + `57 45 42 50` (WEBP) at offset 8 * - **TIFF LE**: `49 49 2A 00` (II\*\0) — little-endian byte order * - **TIFF BE**: `4D 4D 00 2A` (MM\0\*) — big-endian byte order * * No Buffer — uses Uint8Array exclusively. * No fs — no file system access. * No require() — ESM import only. */ /** * Supported image format identifiers. */ type ImageFormat = 'png' | 'jpeg' | 'webp' | 'tiff' | 'unknown'; /** * Detect the image format from the raw file bytes by inspecting magic bytes. * * @param data Raw image file bytes. * @returns The detected format, or `'unknown'` if unrecognized. */ declare function detectImageFormat(data: Uint8Array): ImageFormat; /** * Get a human-readable name for an image format identifier. * * @param format The format identifier string. * @returns A human-readable format name. */ declare function getImageFormatName(format: string): string; /** * Get the list of all supported image formats for embedding. * * @returns An array of format identifier strings. */ declare function getSupportedFormats(): string[]; //#endregion //#region src/assets/image/webpOptimize.d.ts /** * @module assets/image/webpOptimize * * WebP optimization and conversion utilities. * * Since WebP cannot be embedded directly in PDF, these utilities * convert decoded WebP pixel data to JPEG or PNG format for embedding. * * - `recompressWebP()` — re-encode decoded pixels as JPEG * - `webpToJpeg()` — decode WebP then encode as JPEG (convenience) * - `webpToPng()` — decode WebP then encode as PNG (lossless, convenience) * * No Buffer — uses Uint8Array exclusively. * No fs — no file system access. * No require() — ESM import only. */ /** * Encode RGB/RGBA pixels as a PNG file. * @internal */ declare function encodePngFromPixels(pixels: Uint8Array, width: number, height: number, channels: number): Uint8Array; /** * Re-encode decoded WebP pixels as JPEG data for PDF embedding. * * WebP cannot be embedded directly in PDF files. This function takes * decoded pixel data (from a WebP decoder) and produces JPEG bytes * suitable for PDF embedding with /DCTDecode filter. * * @param pixels Decoded pixel data (RGB or RGBA, row-major). * @param width Image width in pixels. * @param height Image height in pixels. * @param quality JPEG quality (1-100). Default: 85. * @returns JPEG-encoded bytes. */ declare function recompressWebP(pixels: Uint8Array, width: number, height: number, quality?: number | undefined): Uint8Array; /** * Decode a WebP file and re-encode as JPEG. * * Convenience function that combines WebP decoding with JPEG encoding. * Imports the WebP decoder dynamically from the webpDecode module * (provided by v0.24.0). * * @param webpData Raw WebP file bytes. * @param quality JPEG quality (1-100). Default: 85. * @returns JPEG-encoded bytes. */ declare function webpToJpeg(webpData: Uint8Array, quality?: number | undefined): Uint8Array; /** * Decode a WebP file and re-encode as PNG. * * Convenience function that combines WebP decoding with PNG encoding. * Produces lossless output suitable for images requiring transparency * or exact color reproduction. * * @param webpData Raw WebP file bytes. * @returns PNG-encoded bytes. */ declare function webpToPng(webpData: Uint8Array): Uint8Array; //#endregion //#region src/assets/image/tiffDirectEmbed.d.ts /** * @module assets/image/tiffDirectEmbed * * Direct TIFF-to-PDF strip/tile mapping for efficient embedding. * * For certain TIFF compression types, the image data can be mapped * directly into a PDF image XObject without a full decode-re-encode * cycle: * * - **Uncompressed TIFF**: Raw pixel data is used directly with no filter. * - **Deflate-compressed TIFF**: Strips/tiles can be passed through as * FlateDecode streams. * - **JPEG-in-TIFF**: The embedded JPEG data is extracted and used * directly as a DCTDecode stream. * * This avoids the overhead of decompressing and recompressing image data, * resulting in faster processing and no quality loss. * * No Buffer — uses Uint8Array exclusively. * No fs — no file system access. * No require() — ESM import only. */ /** * Options for direct TIFF embedding. */ interface DirectEmbedOptions { /** Page index for multi-page TIFFs (0-based). Default: 0. */ page?: number | undefined; } /** * Result of a direct TIFF embedding operation. */ interface DirectEmbedResult { /** Image width in pixels. */ readonly width: number; /** Image height in pixels. */ readonly height: number; /** The image data for the PDF stream. */ readonly data: Uint8Array; /** PDF color space name (e.g. 'DeviceRGB', 'DeviceGray', 'DeviceCMYK'). */ readonly colorSpace: string; /** Bits per component (1, 2, 4, 8, or 16). */ readonly bitsPerComponent: number; /** PDF filter to use, if any (e.g. 'FlateDecode', 'DCTDecode'). */ readonly filter?: string | undefined; } /** * Check whether a TIFF file can be directly embedded in PDF without * a full decode-re-encode cycle. * * Direct embedding is supported for: * - Uncompressed TIFFs (compression = 1) * - Deflate-compressed TIFFs (compression = 8 or 32946) * - JPEG-in-TIFF (compression = 7 or 6) * * @param data Raw TIFF file bytes. * @returns `true` if the TIFF can be directly embedded. */ declare function canDirectEmbed(data: Uint8Array): boolean; /** * Directly embed a TIFF image in a PDF image XObject. * * For supported compression types, this avoids the decode-re-encode * cycle by mapping TIFF strips/tiles directly to PDF stream data: * * - **Uncompressed**: Raw pixel data used with no filter. * - **Deflate**: Compressed data passed through as FlateDecode. * - **JPEG-in-TIFF**: JPEG data extracted and used as DCTDecode. * * @param data Raw TIFF file bytes. * @param options Optional settings (page index for multi-page TIFFs). * @returns The embedding result with all data needed for a PDF image XObject. * @throws If the TIFF format does not support direct embedding. */ declare function embedTiffDirect(data: Uint8Array, options?: DirectEmbedOptions | undefined): DirectEmbedResult; //#endregion //#region src/assets/image/webpDecode.d.ts /** * @module assets/image/webpDecode * * WebP image decoder — pure TypeScript, no WASM, no Buffer. * * Supports: * - VP8 (lossy) bitstream decoding with macroblock processing * - VP8L (lossless) bitstream decoding with Huffman coding, LZ77, color cache, spatial prediction * - ALPH chunk (alpha channel) with filtering and compression * - RIFF/WebP container parsing * * Magic bytes: 52 49 46 46 (RIFF) + offset 8-11: 57 45 42 50 (WEBP) */ /** Decoded WebP image data. */ interface WebPImage { /** Image width in pixels. */ readonly width: number; /** Image height in pixels. */ readonly height: number; /** Raw pixel data (RGB or RGBA). */ readonly pixels: Uint8Array; /** Number of channels (3 for RGB, 4 for RGBA). */ readonly channels: 3 | 4; /** Whether the image has an alpha channel. */ readonly hasAlpha: boolean; } /** Check if data is a WebP file by examining RIFF + WEBP magic bytes. */ declare function isWebP(data: Uint8Array): boolean; /** Check if a WebP file contains a VP8L (lossless) bitstream. */ declare function isWebPLossless(data: Uint8Array): boolean; /** * Decode a WebP image to raw pixel data. * * Supports VP8 (lossy), VP8L (lossless), and VP8+ALPH (lossy with alpha). * Auto-detects the format from chunk headers. * * @param data Raw WebP file bytes. * @returns Decoded image with width, height, and pixel data. */ declare function decodeWebP(data: Uint8Array): WebPImage; //#endregion //#region src/assets/image/tiffDecode.d.ts /** * @module assets/image/tiffDecode * * TIFF image decoder — pure TypeScript, no WASM, no Buffer. * * Supports: * - IFD (Image File Directory) parsing with byte order detection * - Strip-based and tile-based image data extraction * - Compressions: None (1), LZW (5), JPEG-in-TIFF (6/7), Deflate (8), PackBits (32773) * - BitsPerSample: 1, 4, 8, 16 * - SamplesPerPixel: 1, 3, 4 * - PhotometricInterpretation: 0 (WhiteIsZero), 1 (BlackIsZero), 2 (RGB) * - Multi-page TIFF support via IFD chain * * Magic bytes: 49 49 (II, little-endian) or 4D 4D (MM, big-endian) + 42 (0x002A) */ /** Decoded TIFF image data. */ interface TiffImage { /** Image width in pixels. */ readonly width: number; /** Image height in pixels. */ readonly height: number; /** Raw pixel data (normalized to 8-bit per channel). */ readonly pixels: Uint8Array; /** Number of channels. */ readonly channels: 1 | 3 | 4; /** Original bits per sample. */ readonly bitsPerSample: number; } /** Options for TIFF decoding. */ interface TiffDecodeOptions { /** Page index for multi-page TIFFs (0-based). Default: 0. */ page?: number | undefined; } /** A single IFD entry (tag). */ interface IfdEntry { /** Tag ID (e.g., 256 = ImageWidth). */ readonly tag: number; /** Data type (1=BYTE, 2=ASCII, 3=SHORT, 4=LONG, 5=RATIONAL, etc.). */ readonly type: number; /** Number of values. */ readonly count: number; /** The value(s) or offset to value data. */ readonly values: number[]; } /** Check if data is a TIFF file by examining the byte order marker and magic number. */ declare function isTiff(data: Uint8Array): boolean; /** * Parse a single IFD from TIFF data. * * @param data Raw TIFF bytes. * @param offset Byte offset to the IFD. * @param littleEndian Whether the TIFF uses little-endian byte order. * @returns Array of IFD entries. */ declare function parseTiffIfd(data: Uint8Array, offset: number, littleEndian: boolean): IfdEntry[]; /** * Get the number of pages in a multi-page TIFF. * * @param data Raw TIFF bytes. * @returns Number of IFDs (pages). */ declare function getTiffPageCount(data: Uint8Array): number; /** * Decode a specific page from a multi-page TIFF. * * @param data Raw TIFF bytes. * @param pageIndex 0-based page index. * @returns Decoded image. */ declare function decodeTiffPage(data: Uint8Array, pageIndex: number): TiffImage; /** * Decode all pages from a multi-page TIFF. * * @param data Raw TIFF bytes. * @returns Array of decoded images. */ declare function decodeTiffAll(data: Uint8Array): TiffImage[]; /** * Decode a TIFF image. * * @param data Raw TIFF bytes. * @param options Decode options (page selection). * @returns Decoded image data. */ declare function decodeTiff(data: Uint8Array, options?: TiffDecodeOptions | undefined): TiffImage; //#endregion //#region src/wasm/loader.d.ts /** * @module wasm/loader * * Universal WASM module loader for the modern-pdf library. * * Provides a single entry point for loading `.wasm` binaries across * all supported JavaScript runtimes: * * - **Browser**: Uses `fetch()` to load from a URL. * - **Node.js**: Uses `fs/promises` via dynamic import to read from disk. * - **Deno**: Uses `Deno.readFile()` or `fetch()` for local/remote files. * - **Bun**: Uses `Bun.file()` for local files or `fetch()` for URLs. * - **Cloudflare Workers / Edge**: Must provide WASM bytes directly * (no filesystem access), or use bundled imports. * * Loaded modules are cached by name to avoid redundant fetches. * * @packageDocumentation */ /** Supported runtime environments. */ type RuntimeKind = 'browser' | 'node' | 'deno' | 'bun' | 'workerd' | 'service-worker' | 'unknown'; /** Configuration for custom WASM module paths. */ interface WasmLoaderConfig { /** * Base path or URL for WASM modules. * * - In browsers, this should be a URL path (e.g. `/wasm/`). * - In Node.js, this should be a filesystem path. * - If not set, the loader attempts to resolve relative to the * package installation. */ basePath?: string | undefined; /** * Custom per-module paths. * * Keys are module names (e.g. `'libdeflate'`, `'png'`), values are * full paths or URLs to the `.wasm` file. * * These take precedence over `basePath`. */ modulePaths?: Record | undefined; /** * Pre-loaded WASM bytes keyed by module name. * * When provided, the loader skips fetching and uses these bytes * directly. This is the recommended approach for: * * - Cloudflare Workers (no filesystem) * - Bundled applications (WASM embedded in JS) * - Testing */ moduleBytes?: Record | undefined; /** * Disable all WASM loading. * * When set to `true`, all calls to `loadWasmModule()` will throw * an error, forcing the library to use pure-JS fallback * implementations instead. * * This is useful for environments with strict Content Security * Policies that do not allow `wasm-unsafe-eval`. */ disableWasm?: boolean | undefined; } /** * Detect the current JavaScript runtime environment. * * @returns The detected runtime kind. * * @example * ```ts * const runtime = detectRuntime(); * if (runtime === 'node') { ... } * ``` */ declare function detectRuntime(): RuntimeKind; /** * Set the global WASM loader configuration. * * Call this once at application startup before any WASM modules * are loaded. * * @param config - Loader configuration. * * @example * ```ts * configureWasmLoader({ * basePath: '/assets/wasm/', * moduleBytes: { libdeflate: myBundledWasmBytes }, * }); * ``` */ declare function configureWasmLoader(config: WasmLoaderConfig): void; /** * Load a WASM module by name. * * Returns the raw `.wasm` bytes, suitable for passing to * `WebAssembly.compile()` or `WebAssembly.instantiate()`. * * Results are cached -- subsequent calls for the same module name * return the cached bytes without re-fetching. * * @param name - Module name. One of: `'libdeflate'`, `'png'`, `'ttf'`, `'shaping'`, `'jbig2'`. * @returns The raw WASM bytes. * @throws If the module cannot be loaded in the current runtime. * * @example * ```ts * // Auto-detect runtime and load * const wasmBytes = await loadWasmModule('libdeflate'); * * // Pre-configure for Workers * configureWasmLoader({ moduleBytes: { libdeflate: bundledBytes } }); * const bytes = await loadWasmModule('libdeflate'); * ``` */ declare function loadWasmModule(name: string): Promise; /** * Load and compile a WASM module using streaming compilation when available. * * In browsers with `WebAssembly.compileStreaming`, this compiles the module * while the response is still downloading, significantly reducing load time. * Falls back to `WebAssembly.compile` on the raw bytes when streaming is * not available (Node.js, older browsers). * * @param name - Module name (e.g., 'libdeflate', 'png'). * @returns A compiled WebAssembly.Module ready for instantiation. * * @example * ```ts * const module = await loadWasmModuleStreaming('libdeflate'); * const instance = await WebAssembly.instantiate(module, imports); * ``` */ declare function loadWasmModuleStreaming(name: string): Promise; /** * Load, compile, and instantiate a WASM module with streaming when available. * * In browsers with `WebAssembly.instantiateStreaming`, this compiles and * instantiates the module while the response is still downloading. * Falls back to `WebAssembly.instantiate` on the raw bytes when streaming * is not available (Node.js, older browsers). * * @param name - Module name (e.g., 'libdeflate', 'png'). * @param imports - WebAssembly import object. * @returns An instantiated WebAssembly module. * * @example * ```ts * const instance = await instantiateWasmModuleStreaming('libdeflate', {}); * const { compress } = instance.exports; * ``` */ declare function instantiateWasmModuleStreaming(name: string, imports?: WebAssembly.Imports): Promise; /** * Provide WASM bytes directly for a module. * * This bypasses all runtime detection and path resolution. Use this * for bundled scenarios or when WASM bytes are loaded through a * custom mechanism. * * @param name - Module name. * @param bytes - Raw WASM bytes. * * @example * ```ts * // In a Cloudflare Worker * import wasmModule from './deflate.wasm'; * provideWasmBytes('libdeflate', new Uint8Array(wasmModule)); * ``` */ declare function provideWasmBytes(name: string, bytes: Uint8Array): void; /** * Check whether a WASM module is cached (either pre-provided or * previously loaded). * * @param name - Module name. * @returns `true` if bytes are available without loading. */ declare function isWasmModuleCached(name: string): boolean; /** * Clear the WASM module cache. * * Primarily useful for testing. Does not affect pre-provided bytes * in the global configuration. */ declare function clearWasmCache(): void; /** * Check whether WASM loading has been globally disabled. * * @returns `true` if `configureWasmLoader({ disableWasm: true })` was called. * * @example * ```ts * configureWasmLoader({ disableWasm: true }); * console.log(isWasmDisabled()); // true * ``` */ declare function isWasmDisabled(): boolean; /** * Reset the loader to its initial state (clears cache and config). * * Primarily useful for testing. */ declare function resetWasmLoader(): void; //#endregion //#region src/browser/worker.d.ts /** * Web Worker wrapper for offloading PDF generation off the main thread. * * In browser applications, generating large PDFs can block the main * thread and cause UI jank. This module provides a {@link PdfWorker} * class that runs PDF generation inside a Web Worker, keeping the * main thread responsive. * * Usage: * ```ts * import { PdfWorker } from 'modern-pdf-lib/browser'; * * const worker = new PdfWorker(); * const bytes = await worker.generate(async (pdf) => { * const doc = pdf.createPdf(); * const page = doc.addPage(pdf.PageSizes.A4); * page.drawText('Hello from Worker!', { x: 50, y: 750, size: 24 }); * return doc.save(); * }); * worker.terminate(); * ``` * * @module browser/worker */ /** Options for creating a {@link PdfWorker}. */ interface PdfWorkerOptions { /** * URL to a custom worker script. If not provided, an inline worker * is created via `Blob` + `URL.createObjectURL`. * * The custom script must import `modern-pdf-lib` and expose the * same message-handling protocol (receive `{ id, taskCode }`, * respond with `{ id, result }` or `{ id, error }`). */ readonly workerUrl?: string | URL; } /** * Manages a Web Worker for PDF generation tasks. * * Each call to {@link generate} serializes the task function as a * string, sends it to the worker, and returns the resulting PDF bytes. * The worker is created lazily on the first `generate()` call. * * **Important:** The task function is serialized via `.toString()` and * reconstructed with `new Function()` inside the worker. This means: * * - The function **cannot** close over variables from the calling scope. * - It receives the full `modern-pdf-lib` module as its sole argument. * - It must return a `Promise` (typically from `doc.save()`). */ declare class PdfWorker { private worker; private nextId; private readonly pending; private readonly options; constructor(options?: PdfWorkerOptions); /** * Generate a PDF in the worker thread. * * @param taskFn - A function that receives the `modern-pdf-lib` * module and returns PDF bytes. This function is * serialized to a string and executed in the worker, * so it **must not** reference any outer-scope * variables. * @returns The generated PDF as a `Uint8Array`. * * @example * ```ts * const bytes = await worker.generate(async (pdf) => { * const doc = pdf.createPdf(); * const page = doc.addPage(pdf.PageSizes.A4); * page.drawText('Generated in a worker', { x: 50, y: 750, size: 18 }); * return doc.save(); * }); * ``` */ generate(taskFn: (pdf: typeof index_d_exports) => Promise): Promise; /** Terminate the worker and reject all pending tasks. */ terminate(): void; /** Whether the worker is currently active (has been created and not yet terminated). */ get isActive(): boolean; /** Number of in-flight tasks awaiting a response. */ get pendingCount(): number; private getOrCreateWorker; } //#endregion //#region src/utils/base64.d.ts /** * @module utils/base64 * * Base64 encoding and decoding utilities using native `Uint8Array` methods. * * These functions work in all modern JavaScript runtimes (Node 25+, Deno, * Bun, Cloudflare Workers, modern browsers) using the native * `Uint8Array.prototype.toBase64()` and `Uint8Array.fromBase64()` APIs. * * The implementation follows RFC 4648 (standard Base64 alphabet). */ /** * Encode a `Uint8Array` to a standard Base64 string. * * @param data The bytes to encode. * @returns A Base64-encoded string. */ declare function base64Encode(data: Uint8Array): string; /** * Decode a standard Base64 string to a `Uint8Array`. * * Whitespace characters (spaces, tabs, newlines) are stripped before * decoding. Trailing `=` padding is handled correctly. * * @param str A Base64-encoded string. * @returns The decoded bytes. * @throws If the string contains invalid Base64 characters. */ declare function base64Decode(str: string): Uint8Array; //#endregion //#region src/barcode/types.d.ts /** * Encoded barcode data — a sequence of modules (bars and spaces). * * Each entry in `modules` is `true` for a dark bar and `false` for a * light space. The `width` property gives the total number of modules. */ interface BarcodeMatrix { /** Module pattern: `true` = dark bar, `false` = light space. */ readonly modules: readonly boolean[]; /** Total number of modules (= `modules.length`). */ readonly width: number; } /** * Common options for rendering a barcode into PDF content-stream operators. */ interface BarcodeOptions { /** Height of the bars in user-space units. Default: `50`. */ readonly height?: number | undefined; /** Width of a single module in user-space units. Default: `1`. */ readonly moduleWidth?: number | undefined; /** Quiet-zone width in modules on each side. Default: `10`. */ readonly quietZone?: number | undefined; /** Bar colour. Default: grayscale black. */ readonly color?: Color | undefined; /** * Whether to render human-readable text below the barcode. * Note: text rendering requires a font to be set in the content stream * beforehand. Default: `false`. */ readonly showText?: boolean | undefined; /** Font size for human-readable text. Default: `10`. */ readonly fontSize?: number | undefined; } //#endregion //#region src/barcode/code128.d.ts /** * Options for rendering a Code 128 barcode as PDF operators. */ interface Code128Options { /** Bar height in points. Default: `50`. */ readonly height?: number; /** Narrow bar (module) width in points. Default: `1`. */ readonly moduleWidth?: number; /** Quiet zone width in modules. Default: `10`. */ readonly quietZone?: number; /** Bar colour. Default: black (grayscale 0). */ readonly color?: Color; /** Show human-readable text below the barcode. Default: `false`. */ readonly showText?: boolean; /** Font size for the human-readable text. Default: `10`. */ readonly fontSize?: number; } /** * Encode a string as a sequence of Code 128 symbol values (including * START code, data symbols, code-set switches, check digit, and STOP). * * @param data The string to encode. * @returns Array of symbol values (0-106). * @throws If the data contains characters that cannot be encoded. */ declare function encodeCode128Values(data: string): readonly number[]; /** * Convert a sequence of Code 128 symbol values to a module (bar/space) array. * * @param values Array of symbol values as returned by {@link encodeCode128Values}. * @returns A {@link BarcodeMatrix} with the module array and total width. */ declare function valuesToModules(values: readonly number[]): BarcodeMatrix; /** * Encode data as a Code 128 barcode. * * This is the primary encoding function. It analyzes the input string, * automatically selects optimal code sets (A/B/C), calculates the * check digit, and returns the complete barcode as a module array. * * @param data The string to encode (ASCII 0-127). * @returns A {@link BarcodeMatrix} with the module pattern. * @throws If the data is empty or contains non-encodable characters. */ declare function encodeCode128(data: string): BarcodeMatrix; /** * Generate PDF content-stream operators for a Code 128 barcode. * * The barcode is drawn as filled rectangles (one per bar), using the * `q`/`Q` graphics state save/restore operators for isolation. * * @param matrix The barcode matrix from {@link encodeCode128}. * @param x X coordinate of the barcode origin (lower-left). * @param y Y coordinate of the barcode origin (lower-left). * @param options Rendering options. * @returns A string of PDF content-stream operators. */ declare function code128ToOperators(matrix: BarcodeMatrix, x: number, y: number, options?: Code128Options): string; //#endregion //#region src/barcode/code39.d.ts /** * Options for rendering a Code 39 barcode as PDF operators. */ interface Code39Options { /** Height of the bars in user-space units. Default: `50`. */ readonly height?: number | undefined; /** Width of a narrow module in user-space units. Default: `1`. */ readonly moduleWidth?: number | undefined; /** Wide-to-narrow ratio. Default: `3`. Must be >= 2. */ readonly wideToNarrowRatio?: number | undefined; /** Quiet-zone width in narrow modules on each side. Default: `10`. */ readonly quietZone?: number | undefined; /** Bar colour. Default: grayscale black. */ readonly color?: Color | undefined; /** Show human-readable text below the barcode. Default: `false`. */ readonly showText?: boolean | undefined; /** Include a modulo-43 check digit. Default: `false`. */ readonly includeCheckDigit?: boolean | undefined; } /** * Compute the modulo-43 check digit for a Code 39 data string. * * @param data Uppercase data string (without start/stop `*`). * @returns The check digit character. * @throws If the data contains characters not in the Code 39 set. */ declare function computeCode39CheckDigit(data: string): string; /** * Encode a string as a Code 39 barcode. * * The input is automatically wrapped with start/stop `*` characters. * If `includeCheckDigit` is true, a modulo-43 check digit is appended * before the stop character. * * @param data The string to encode (digits, uppercase A-Z, * space, `-`, `.`, `$`, `/`, `+`, `%`). * @param includeCheckDigit Whether to append a modulo-43 check digit. * Default: `false`. * @param wideToNarrowRatio Wide-to-narrow ratio for module expansion. * Default: `3`. * @returns A {@link BarcodeMatrix} with the module pattern. * @throws If the data contains invalid characters (lowercase, * `*`, or characters outside the Code 39 set). */ declare function encodeCode39(data: string, includeCheckDigit?: boolean, wideToNarrowRatio?: number): BarcodeMatrix; /** * Generate PDF content-stream operators for a Code 39 barcode. * * The barcode is drawn as filled rectangles (one per contiguous bar run), * wrapped in `q`/`Q` graphics state save/restore operators. * * @param matrix The barcode matrix from {@link encodeCode39}. * @param x X coordinate of the barcode origin (lower-left). * @param y Y coordinate of the barcode origin (lower-left). * @param options Rendering options. * @returns A string of PDF content-stream operators. */ declare function code39ToOperators(matrix: BarcodeMatrix, x: number, y: number, options?: Code39Options): string; //#endregion //#region src/barcode/itf.d.ts /** * Options for rendering an ITF barcode as PDF operators. */ interface ItfOptions { /** Height of the bars in user-space units. Default: `50`. */ readonly height?: number | undefined; /** Width of a narrow module in user-space units. Default: `1`. */ readonly moduleWidth?: number | undefined; /** Wide-to-narrow ratio. Default: `3`. Must be >= 2. */ readonly wideToNarrowRatio?: number | undefined; /** Quiet-zone width in narrow modules on each side. Default: `10`. */ readonly quietZone?: number | undefined; /** Bar colour. Default: grayscale black. */ readonly color?: Color | undefined; /** Show human-readable text below the barcode. Default: `false`. */ readonly showText?: boolean | undefined; /** * Add horizontal bearer bars at the top and bottom of the barcode. * Bearer bars help prevent partial reads. Default: `false`. */ readonly bearerBars?: boolean | undefined; /** * Width of the bearer bars in user-space units. Only used when * `bearerBars` is `true`. Default: `2`. */ readonly bearerBarWidth?: number | undefined; } /** * Encode a numeric string as an ITF barcode. * * If the input has an odd number of digits, a leading `0` is prepended * to make it even. * * @param data A string of digits (0-9 only). * @returns A {@link BarcodeMatrix} with the module pattern. * @throws If the data contains non-digit characters. */ declare function encodeItf(data: string, wideToNarrowRatio?: number): BarcodeMatrix; /** * Generate PDF content-stream operators for an ITF barcode. * * The barcode is drawn as filled rectangles (one per contiguous bar run), * wrapped in `q`/`Q` graphics state save/restore operators. If bearer * bars are enabled, horizontal bars are drawn at the top and bottom. * * @param matrix The barcode matrix from {@link encodeItf}. * @param x X coordinate of the barcode origin (lower-left). * @param y Y coordinate of the barcode origin (lower-left). * @param options Rendering options. * @returns A string of PDF content-stream operators. */ declare function itfToOperators(matrix: BarcodeMatrix, x: number, y: number, options?: ItfOptions): string; //#endregion //#region src/barcode/ean.d.ts /** * Calculate the EAN / UPC check digit using the Modulo-10 algorithm. * * Works for both EAN-13 (pass 12 digits) and EAN-8 (pass 7 digits). * The algorithm weights digits alternately by 1 and 3 starting from * the rightmost position. * * @param data Numeric string of 7 or 12 digits (without check digit). * @returns The single check digit (0-9). */ declare function calculateEanCheckDigit(data: string): number; /** * Encode an EAN-13 barcode. * * @param data 12- or 13-digit numeric string. If 12 digits are given * the check digit is calculated and appended. If 13 digits * are given the last digit is validated as the correct check. * @returns A {@link BarcodeMatrix} with 95 modules (the standard EAN-13 * symbol width without quiet zones). * @throws If the input is not 12 or 13 numeric digits, or if a * provided check digit does not match. */ declare function encodeEan13(data: string): BarcodeMatrix; /** * Encode an EAN-8 barcode. * * @param data 7- or 8-digit numeric string. If 7 digits are given * the check digit is calculated and appended. If 8 digits * are given the last digit is validated. * @returns A {@link BarcodeMatrix} with 67 modules. * @throws If the input is invalid. */ declare function encodeEan8(data: string): BarcodeMatrix; /** * Generate PDF content-stream operators for an EAN-13 barcode. * * The barcode is rendered as filled rectangles (one per contiguous run * of dark modules) inside a `q … Q` graphics-state block. * * @param matrix Encoded barcode from {@link encodeEan13}. * @param x Lower-left x coordinate of the barcode (including quiet zone). * @param y Lower-left y coordinate. * @param options Rendering options. * @returns A string of PDF operators ready to be appended to a * content stream. */ declare function ean13ToOperators(matrix: BarcodeMatrix, x: number, y: number, options?: BarcodeOptions): string; /** * Generate PDF content-stream operators for an EAN-8 barcode. * * @param matrix Encoded barcode from {@link encodeEan8}. * @param x Lower-left x coordinate (including quiet zone). * @param y Lower-left y coordinate. * @param options Rendering options. * @returns A string of PDF operators. */ declare function ean8ToOperators(matrix: BarcodeMatrix, x: number, y: number, options?: BarcodeOptions): string; //#endregion //#region src/barcode/upc.d.ts /** * Calculate the UPC-A check digit (Modulo-10 algorithm). * * @param data 11-digit numeric string (without check digit). * @returns The single check digit (0-9). */ declare function calculateUpcCheckDigit(data: string): number; /** * Encode a UPC-A barcode. * * UPC-A is encoded as an EAN-13 barcode with a leading `0`. The * resulting {@link BarcodeMatrix} has 95 modules (identical to EAN-13). * * @param data 11- or 12-digit numeric string. If 11 digits are given * the check digit is calculated and appended. If 12 digits * are given the last digit is validated. * @returns A {@link BarcodeMatrix} with 95 modules. * @throws If the input is not 11 or 12 numeric digits, or if a * provided check digit does not match. */ declare function encodeUpcA(data: string): BarcodeMatrix; /** * Generate PDF content-stream operators for a UPC-A barcode. * * @param matrix Encoded barcode from {@link encodeUpcA}. * @param x Lower-left x coordinate (including quiet zone). * @param y Lower-left y coordinate. * @param options Rendering options. * @returns A string of PDF operators. */ declare function upcAToOperators(matrix: BarcodeMatrix, x: number, y: number, options?: BarcodeOptions): string; //#endregion //#region src/barcode/dataMatrix.d.ts /** Options for rendering a Data Matrix to PDF operators. */ interface DataMatrixOptions { /** Size of each module in PDF points. Default: `2`. */ readonly moduleSize?: number; /** Foreground (dark module) colour. Default: black. */ readonly color?: Color; /** Background colour. Default: white. */ readonly backgroundColor?: Color; /** Number of quiet-zone modules around the code. Default: `1`. */ readonly quietZone?: number; } /** The result of Data Matrix encoding — a boolean matrix. */ interface DataMatrixResult { /** Number of rows in the symbol. */ readonly rows: number; /** Number of columns in the symbol. */ readonly cols: number; /** Row-major boolean array. `true` = dark module. */ readonly modules: readonly boolean[]; } /** * Encode a string as a Data Matrix ECC200 symbol. * * @param data The string to encode (ASCII characters supported). * @returns A {@link DataMatrixResult} with the encoded symbol. * @throws If the data exceeds maximum capacity. */ declare function encodeDataMatrix(data: string): DataMatrixResult; /** * Convert a {@link DataMatrixResult} to PDF content-stream operators. * * The Data Matrix 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 symbol. * * @param matrix The Data Matrix from {@link encodeDataMatrix}. * @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 dataMatrixToOperators(matrix: DataMatrixResult, x: number, y: number, options?: DataMatrixOptions): string; //#endregion //#region src/barcode/pdf417.d.ts /** Options for encoding a PDF417 barcode. */ interface Pdf417Options { /** Number of data columns (1-30). Default: auto-calculated. */ readonly columns?: number; /** Error correction level (0-8). Default: `2`. */ readonly errorLevel?: number; /** Row height in PDF points. Default: `8`. */ readonly rowHeight?: number; /** Width of a single module in PDF points. Default: `1`. */ readonly moduleWidth?: number; /** Bar colour. Default: black. */ readonly color?: Color; /** Quiet zone width in modules. Default: `2`. */ readonly quietZone?: number; } /** The result of PDF417 encoding — a 2D boolean matrix. */ interface Pdf417Matrix { /** Number of rows. */ readonly rows: number; /** Number of data columns. */ readonly columns: number; /** Total modules per row. */ readonly moduleWidth: number; /** Row-major boolean array. `true` = dark bar. */ readonly modules: readonly boolean[]; } /** * Encode a string as a PDF417 2D stacked barcode. * * @param data The string to encode. * @param options Encoding options (columns, error level). * @returns A {@link Pdf417Matrix} with the encoded barcode. * @throws If the data is empty or too long to encode. */ declare function encodePdf417(data: string, options?: { columns?: number; errorLevel?: number; }): Pdf417Matrix; /** * Convert a {@link Pdf417Matrix} to PDF content-stream operators. * * The barcode is rendered as filled rectangles, positioned at `(x, y)` * in PDF user-space coordinates. The `y` coordinate refers to the * **bottom-left** corner of the barcode. * * @param matrix The PDF417 matrix from {@link encodePdf417}. * @param x X position in PDF points. * @param y Y position in PDF points. * @param options Rendering options. * @returns A string of PDF content-stream operators. */ declare function pdf417ToOperators(matrix: Pdf417Matrix, x: number, y: number, options?: Pdf417Options): string; //#endregion //#region src/barcode/style.d.ts /** * Full styling options for rendering a barcode with background, * borders, colours, and human-readable text. */ interface StyledBarcodeOptions { /** Bar height in points. Default: 50. */ readonly height?: number; /** Module width in points. Default: 1. */ readonly moduleWidth?: number; /** Quiet zone in modules. Default: 10. */ readonly quietZone?: number; /** Bar color. Default: black. */ readonly color?: Color; /** Background color. Default: white. */ readonly backgroundColor?: Color; /** Show human-readable text below the barcode. Default: false. */ readonly showText?: boolean; /** Font name for human-readable text. Default: 'Helvetica'. */ readonly fontName?: string; /** Font size for text. Default: 10. */ readonly fontSize?: number; /** Text color. Default: same as bar color. */ readonly textColor?: Color; /** Add a border around the barcode. Default: false. */ readonly border?: boolean; /** Border width in points. Default: 0.5. */ readonly borderWidth?: number; /** Border color. Default: black. */ readonly borderColor?: Color; /** Padding inside border in points. Default: 4. */ readonly padding?: number; } /** * Calculate the total dimensions of a styled barcode. * * Returns the outer bounding box including quiet zones, padding, * borders, and optional text area. * * @param matrix The encoded barcode matrix. * @param options Styling options. * @returns `{ width, height }` in points. */ declare function calculateBarcodeDimensions(matrix: BarcodeMatrix, options?: StyledBarcodeOptions): { width: number; height: number; }; /** * Render a barcode matrix with full styling options. * * This combines the barcode modules with background, text, * border, and color options into a single set of PDF operators. * The result is wrapped in `q` / `Q` (save / restore graphics state) * for clean isolation. * * @param matrix The encoded barcode matrix. * @param x X coordinate of the barcode origin (lower-left of outer box). * @param y Y coordinate of the barcode origin (lower-left of outer box). * @param text Human-readable text to show below the bars (used only * when `options.showText` is `true`). * @param options Styling options. * @returns A string of PDF content-stream operators. */ declare function renderStyledBarcode(matrix: BarcodeMatrix, x: number, y: number, text: string, options?: StyledBarcodeOptions): string; //#endregion //#region src/barcode/reader.d.ts /** * @module barcode/reader * * Barcode reader for verification purposes. * * Reads barcode data from module arrays to verify that our encoders * produce correct output. This is a "round-trip" verification tool, * not a general-purpose image scanner. * * Supported formats: * - Code 128 (A, B, C code sets) * - EAN-13 * - EAN-8 * - Code 39 */ /** * Result of a barcode read operation. */ interface BarcodeReadResult { /** The decoded data string. */ readonly data: string; /** The detected barcode format. */ readonly format: string; /** Whether decoding was successful. */ readonly valid: boolean; /** Whether the check digit is valid (if applicable). */ readonly checkDigitValid?: boolean; } /** * Decode a Code 128 barcode from its module array. * * Finds the START pattern, decodes symbols according to the active * code set, verifies the check digit, and finds the STOP pattern. * * @param modules Boolean array where `true` = dark bar. * @returns A {@link BarcodeReadResult} with the decoded data. */ declare function readCode128(modules: readonly boolean[]): BarcodeReadResult; /** * Decode an EAN-13 barcode from its module array. * * EAN-13 structure (95 modules total): * - Start guard: 3 modules (101) * - Left digits (6 x 7 modules): 42 modules * - Center guard: 5 modules (01010) * - Right digits (6 x 7 modules): 42 modules * - End guard: 3 modules (101) * * @param modules Boolean array of 95 modules. * @returns A {@link BarcodeReadResult}. */ declare function readEan13(modules: readonly boolean[]): BarcodeReadResult; /** * Decode an EAN-8 barcode from its module array. * * EAN-8 structure (67 modules total): * - Start guard: 3 modules (101) * - Left digits (4 x 7 modules, L patterns): 28 modules * - Center guard: 5 modules (01010) * - Right digits (4 x 7 modules, R patterns): 28 modules * - End guard: 3 modules (101) * * @param modules Boolean array of 67 modules. * @returns A {@link BarcodeReadResult}. */ declare function readEan8(modules: readonly boolean[]): BarcodeReadResult; /** * Decode a Code 39 barcode from its module array. * * The reader dynamically determines the wide/narrow threshold from * the module widths, making it robust to different ratios. * * @param modules Boolean array where `true` = dark bar. * @returns A {@link BarcodeReadResult} with the decoded data. */ declare function readCode39(modules: readonly boolean[]): BarcodeReadResult; /** * Auto-detect barcode format and decode. * * Tries multiple decoders and returns the first successful result, * or `null` if no format matches. * * Detection order: * 1. EAN-13 (95 modules) * 2. EAN-8 (67 modules) * 3. Code 128 (starts with a known START pattern) * 4. Code 39 (starts and ends with '*' pattern) * * @param modules Boolean array where `true` = dark bar. * @returns A {@link BarcodeReadResult} or `null` if unrecognised. */ declare function readBarcode(modules: readonly boolean[]): BarcodeReadResult | null; //#endregion //#region src/layout/presets.d.ts /** * A partial set of table options that can be applied as a style preset. * Excludes positional / data fields (`x`, `y`, `width`, `rows`) that * must always be supplied by the caller. */ type TablePreset = Partial>; /** * Clean, minimal style — no cell borders, generous padding, dark-gray * header text. * * Good for reports and dashboards where visual clutter should be low. */ declare function minimalPreset(): TablePreset; /** * Alternating row background colours (white / light gray) with a dark * header row. * * A classic "zebra-stripe" look that improves readability for wide * tables. */ declare function stripedPreset(): TablePreset; /** * Full visible borders with a dark header row. * * Suitable for structured data where every cell boundary should be * clearly delineated. */ declare function borderedPreset(): TablePreset; /** * Business / formal style — subtle alternating rows with a dark-blue * header. * * Ideal for invoices, financial reports, and formal documents. */ declare function professionalPreset(): TablePreset; /** * Merge a preset with explicit table options. * * Values supplied in `options` always override the preset defaults — * the preset acts as a fallback layer beneath the caller's choices. * * @param preset A partial options object returned by one of the * preset factory functions. * @param options The caller's table options (must include `x`, `y`, * `width`, and `rows` at minimum). * @returns A fully-merged {@link DrawTableOptions} object. */ declare function applyPreset(preset: TablePreset, options: DrawTableOptions): DrawTableOptions; /** Preset name for use with {@link applyTablePreset}. */ type PresetName = 'minimal' | 'striped' | 'bordered' | 'professional'; /** Options to customise a named preset. */ interface PresetOptions { /** Base font size. Default: 11. */ readonly fontSize?: number; /** Primary color (used for headers, accents). */ readonly primaryColor?: Color; /** Whether table has header row(s). Default: true. */ readonly hasHeader?: boolean; } /** * Select a preset by name and optionally customise it. * * Returns a partial {@link DrawTableOptions} that can be spread into * the full options object. * * @param preset One of 'minimal', 'striped', 'bordered', 'professional'. * @param options Optional overrides for font size and primary color. */ declare function applyTablePreset(preset: PresetName, options?: PresetOptions): Partial; //#endregion //#region src/layout/overflow.d.ts /** * @module layout/overflow * * Text overflow handling utilities for table cells. * * Provides five overflow modes that control how text is rendered * when it exceeds the available width of a cell: * * - **visible** — render as-is, text may extend beyond the cell * - **wrap** — split text into multiple lines that fit within the cell * - **truncate** — cut text that exceeds the cell width * - **ellipsis** — cut text and append "..." when it exceeds the cell width * - **shrink** — reduce font size to fit text within the cell width */ /** Controls how text that exceeds a cell's available width is handled. */ type OverflowMode = 'visible' | 'wrap' | 'truncate' | 'ellipsis' | 'shrink'; /** Result of applying an overflow mode to a text string. */ interface OverflowResult { /** The processed line(s) of text. */ readonly lines: readonly string[]; /** The font size to use (may differ from input for 'shrink' mode). */ readonly fontSize: number; /** Whether the text was modified (truncated, wrapped, or shrunk). */ readonly wasModified: boolean; } /** * Estimate the width of text using character count * fontSize * avgCharWidth. * * This is a rough approximation suitable for layout purposes when real * font metrics are unavailable. The default `avgCharWidth` of `0.5` is * a reasonable average for proportional Latin fonts like Helvetica. * * @param text The text to measure. * @param fontSize Font size in points. * @param avgCharWidth Average character width as a fraction of fontSize. * Default: `0.5`. * @returns Estimated width in points. */ declare function estimateTextWidth(text: string, fontSize: number, avgCharWidth?: number): number; /** * Split text into lines that fit within `availableWidth`. * * Word boundaries (spaces) are preferred. If a single word is wider * than `availableWidth`, it is broken mid-word to guarantee every * returned line fits. * * @param text The text to wrap. * @param availableWidth Maximum line width in points. * @param fontSize Font size in points. * @param avgCharWidth Average character width as a fraction of fontSize. * Default: `0.5`. * @returns Array of lines. */ declare function wrapText(text: string, availableWidth: number, fontSize: number, avgCharWidth?: number): string[]; /** * Truncate text to fit within `availableWidth`. * * If the text already fits, it is returned unchanged. * * @param text The text to truncate. * @param availableWidth Maximum width in points. * @param fontSize Font size in points. * @param avgCharWidth Average character width as a fraction of fontSize. * Default: `0.5`. * @returns The (possibly truncated) text. */ declare function truncateText(text: string, availableWidth: number, fontSize: number, avgCharWidth?: number): string; /** * Truncate text and append an ellipsis string to fit within `availableWidth`. * * If the text already fits, it is returned unchanged. * * @param text The text to truncate. * @param availableWidth Maximum width in points. * @param fontSize Font size in points. * @param options Optional configuration. * @param options.avgCharWidth Average character width fraction. Default: `0.5`. * @param options.ellipsisChar The ellipsis suffix. Default: `'...'`. * @returns The (possibly truncated + ellipsis) text. */ declare function ellipsisText(text: string, availableWidth: number, fontSize: number, options?: { avgCharWidth?: number; ellipsisChar?: string; }): string; /** * Calculate the font size needed to fit text within `availableWidth`. * * If the text already fits at the given `fontSize`, that size is returned. * The result is clamped to `minFontSize` so text never becomes illegibly small. * * @param text The text to fit. * @param availableWidth Maximum width in points. * @param fontSize Starting font size in points. * @param options Optional configuration. * @param options.avgCharWidth Average character width fraction. Default: `0.5`. * @param options.minFontSize Minimum font size floor. Default: `6`. * @returns The (possibly reduced) font size. */ declare function shrinkFontSize(text: string, availableWidth: number, fontSize: number, options?: { avgCharWidth?: number; minFontSize?: number; }): number; /** * Apply overflow handling to text, returning processed line(s) and * an adjusted fontSize. * * This is the primary entry point — it dispatches to the appropriate * strategy function based on the requested `mode`. * * @param text The text to process. * @param mode The overflow mode to apply. * @param availableWidth Maximum width in points. * @param fontSize Font size in points. * @param options Optional configuration. * @returns An {@link OverflowResult} with lines, fontSize, * and a flag indicating whether the text was modified. */ declare function applyOverflow(text: string, mode: OverflowMode, availableWidth: number, fontSize: number, options?: { avgCharWidth?: number; minFontSize?: number; ellipsisChar?: string; }): OverflowResult; //#endregion //#region src/errors.d.ts /** * @module errors * * Typed error classes for common failure modes in the modern-pdf library. * Each error class extends the native `Error` and carries a descriptive * `name` so callers can use `instanceof` checks or `error.name` comparisons. * * All constructors accept an optional `ErrorOptions` parameter to support * error chaining via the standard `{ cause }` option (ES2022+). * * These match the pdf-lib error hierarchy for API compatibility. */ /** * Thrown when attempting to load or manipulate an encrypted PDF without * providing the correct password. */ declare class EncryptedPdfError extends Error { readonly name = "EncryptedPdfError"; constructor(message?: string, options?: ErrorOptions); } /** * Thrown when a font operation requires an embedded font but none has been * registered or the font reference is invalid. */ declare class FontNotEmbeddedError extends Error { readonly name = "FontNotEmbeddedError"; constructor(fontName?: string, options?: ErrorOptions); } /** * Thrown when attempting to use a page from a different document without * first copying it. */ declare class ForeignPageError extends Error { readonly name = "ForeignPageError"; constructor(options?: ErrorOptions); } /** * Thrown when attempting to remove a page from a document that has no pages. */ declare class RemovePageFromEmptyDocumentError extends Error { readonly name = "RemovePageFromEmptyDocumentError"; constructor(options?: ErrorOptions); } /** * Thrown when looking up a form field by name that does not exist. */ declare class NoSuchFieldError extends Error { readonly name = "NoSuchFieldError"; constructor(fieldName: string, options?: ErrorOptions); } /** * Thrown when a form field is accessed via the wrong typed getter * (e.g. calling `getTextField()` on a checkbox field). */ declare class UnexpectedFieldTypeError extends Error { readonly name = "UnexpectedFieldTypeError"; constructor(fieldName: string, expected: string, actual: string, options?: ErrorOptions); } /** * Thrown when a checkbox or radio button is checked but no "on" value * can be determined from its appearance dictionary. */ declare class MissingOnValueCheckError extends Error { readonly name = "MissingOnValueCheckError"; constructor(fieldName: string, options?: ErrorOptions); } /** * Thrown when creating a form field with a name that is already in use. */ declare class FieldAlreadyExistsError extends Error { readonly name = "FieldAlreadyExistsError"; constructor(fieldName: string, options?: ErrorOptions); } /** * Thrown when a field name part (between dots in a qualified name) is * empty or contains invalid characters. */ declare class InvalidFieldNamePartError extends Error { readonly name = "InvalidFieldNamePartError"; constructor(namePart: string, options?: ErrorOptions); } /** * Thrown when attempting to create a terminal field but a non-terminal * node (a field with /Kids but no /FT) already uses the same name. */ declare class FieldExistsAsNonTerminalError extends Error { readonly name = "FieldExistsAsNonTerminalError"; constructor(fieldName: string, options?: ErrorOptions); } /** * Thrown when attempting to read the rich text value (/RV) of a field * that does not support it or whose rich text is malformed. */ declare class RichTextFieldReadError extends Error { readonly name = "RichTextFieldReadError"; constructor(fieldName: string, options?: ErrorOptions); } /** * Thrown when a combed text field receives more characters than its * maximum length allows. */ declare class CombedTextLayoutError extends Error { readonly name = "CombedTextLayoutError"; constructor(textLength: number, maxLength: number, options?: ErrorOptions); } /** * Thrown when a text field value exceeds the field's declared * maximum length (/MaxLen). */ declare class ExceededMaxLengthError extends Error { readonly name = "ExceededMaxLengthError"; constructor(textLength: number, maxLength: number, fieldName: string, options?: ErrorOptions); } //#endregion //#region src/form/formFlatten.d.ts /** * Options for form flattening operations. */ interface FlattenOptions { /** * If `true`, read-only fields are skipped and left interactive. * All other fields are flattened normally. * * Default: `false` (all fields are flattened, including read-only ones). */ preserveReadOnly?: boolean | undefined; } /** * Flatten ALL form fields into static page content. * * For each field in the document's AcroForm: * 1. Generate / retrieve the field's appearance stream * 2. Embed the appearance as a Form XObject in the page's content stream * 3. Remove the widget annotation from the page * 4. Remove the field from the AcroForm * * After all fields are processed, the /AcroForm dictionary is cleared. * * @param form The document's PdfForm. * @param options Optional flatten options. * @returns An object describing the flatten operations performed, suitable * for the caller to apply to page content streams and resources. */ declare function flattenForm(form: PdfForm, options?: FlattenOptions): FlattenFormResult; /** * Flatten a SINGLE field by name. * * Locates the field in the form, merges its appearance into the page * content, removes the widget annotation, and removes the field from * the AcroForm's /Fields array. Other fields remain interactive. * * @param form The document's PdfForm. * @param fieldName The name of the field to flatten (partial or fully-qualified). * @param options Optional flatten options. * @returns An object describing the flatten operations performed. * @throws If the field is not found. */ declare function flattenField(form: PdfForm, fieldName: string, options?: FlattenOptions): FlattenFormResult; /** * Flatten specific fields by name. * * @param form The document's PdfForm. * @param fieldNames Array of field names to flatten. * @param options Optional flatten options. * @returns An object describing the flatten operations performed. * @throws If any field name is not found. */ declare function flattenFields(form: PdfForm, fieldNames: string[], options?: FlattenOptions): FlattenFormResult; /** * Result of a form flatten operation. * * Contains the content stream operators and XObject resources that * must be applied to the page(s) to complete the flattening. */ interface FlattenFormResult { /** Content stream operators to append to the page. */ contentOps: string; /** XObject name-to-stream pairs to add to page resources. */ xObjects: Array<{ name: string; stream: PdfStream; }>; /** Names of fields that were flattened. */ flattenedFields: string[]; /** Names of fields that were skipped (e.g. read-only with preserveReadOnly). */ skippedFields: string[]; /** Whether the AcroForm was fully removed (all fields flattened). */ acroFormRemoved: boolean; } //#endregion //#region src/core/outlines.d.ts /** * An opaque handle returned by {@link addBookmark} that identifies * a bookmark in the outline tree. Used as a `parent` to create * nested bookmarks, or passed to {@link removeBookmark} to delete * an entry. */ interface BookmarkRef { /** @internal The underlying outline item. */ readonly _item: PdfOutlineItem; } /** * Represents a single node in the bookmark tree, as returned by * {@link getBookmarks}. */ interface BookmarkNode { /** The displayed bookmark title. */ readonly title: string; /** Zero-based page index this bookmark points to. */ readonly pageIndex: number; /** Vertical position on the target page (if set). */ readonly y?: number | undefined; /** Whether the title is bold. */ readonly bold?: boolean | undefined; /** Whether the title is italic. */ readonly italic?: boolean | undefined; /** Colour of the bookmark title (RGB, 0-1 range). */ readonly color?: { readonly r: number; readonly g: number; readonly b: number; } | undefined; /** Child bookmarks. */ readonly children: readonly BookmarkNode[]; /** The handle for this bookmark node. */ readonly ref: BookmarkRef; } /** * Options for {@link addBookmark}. */ interface AddBookmarkOptions { /** The display title for the bookmark. */ title: string; /** Zero-based page index to navigate to. */ pageIndex: number; /** Parent bookmark for nesting. Omit for a top-level bookmark. */ parent?: BookmarkRef | undefined; /** Vertical position on the page (top coordinate for FitH). */ y?: number | undefined; /** Whether the title text is bold. */ bold?: boolean | undefined; /** Whether the title text is italic. */ italic?: boolean | undefined; /** Colour of the bookmark title (RGB, 0-1 range). */ color?: { r: number; g: number; b: number; } | undefined; /** * Whether the bookmark's children are initially expanded. * Default: `true`. */ isOpen?: boolean | undefined; } /** * Add a bookmark entry to the document's outline tree. * * @param doc The document to add the bookmark to. * @param options Bookmark configuration (title, page, nesting, style). * @returns A {@link BookmarkRef} identifying the new bookmark. */ declare function addBookmark(doc: PdfDocument, options: AddBookmarkOptions): BookmarkRef; /** * Return the bookmark tree for the document. * * Returns an array of top-level {@link BookmarkNode} objects, each * with a `children` array for nested bookmarks. * * @param doc The document to read bookmarks from. * @returns The bookmark tree. */ declare function getBookmarks(doc: PdfDocument): readonly BookmarkNode[]; /** * Remove a specific bookmark from the document. * * If the bookmark has children, they are also removed. * * @param doc The document to modify. * @param ref The handle of the bookmark to remove. * @throws If the bookmark is not found in the tree. */ declare function removeBookmark(doc: PdfDocument, ref: BookmarkRef): void; /** * Remove all bookmarks from the document. * * @param doc The document to clear bookmarks from. */ declare function removeAllBookmarks(doc: PdfDocument): void; //#endregion //#region src/core/pageLabels.d.ts /** * Numbering style for page labels. * * | Value | PDF /S | Description | Example | * |------------|--------|------------------------------|----------------| * | `decimal` | `/D` | Arabic numerals | 1, 2, 3, … | * | `roman` | `/r` | Lowercase Roman numerals | i, ii, iii, … | * | `Roman` | `/R` | Uppercase Roman numerals | I, II, III, … | * | `alpha` | `/a` | Lowercase alphabetic | a, b, c, … | * | `Alpha` | `/A` | Uppercase alphabetic | A, B, C, … | */ type PageLabelStyle = 'decimal' | 'roman' | 'Roman' | 'alpha' | 'Alpha'; /** * Defines a contiguous range of pages that share a labelling scheme. * * Each range starts at `startPage` (zero-based page index) and extends * to the next range's `startPage` (or the end of the document). */ interface PageLabelRange { /** * Zero-based index of the first page this label range applies to. */ startPage: number; /** * The numbering style for this range. */ style: PageLabelStyle; /** * An optional prefix string prepended to each page label. * For example, `"A-"` produces labels like "A-1", "A-2", etc. */ prefix?: string | undefined; /** * The numeric value of the first page label in this range. * Defaults to `1`. * * For example, `{ startPage: 4, style: 'decimal', start: 5 }` means * page index 4 is labelled "5", page index 5 is labelled "6", etc. */ start?: number | undefined; } /** * Set the page label ranges for the document. * * Each entry in the `labels` array defines a contiguous range of pages * that share a numbering style. Ranges must be sorted by `startPage` * in ascending order. * * @param doc The document to set page labels on. * @param labels An array of label range definitions. * @throws If `labels` is empty or ranges are not sorted. */ declare function setPageLabels(doc: PdfDocument, labels: readonly PageLabelRange[]): void; /** * Get the current page label ranges for the document. * * Returns `undefined` if no page labels have been set. * * @param doc The document to read page labels from. * @returns The page label ranges, or `undefined`. */ declare function getPageLabels(doc: PdfDocument): readonly PageLabelRange[] | undefined; /** * Remove all page labels from the document. * * @param doc The document to clear page labels from. */ declare function removePageLabels(doc: PdfDocument): void; //#endregion //#region src/batch/batchProcessor.d.ts /** Callback invoked as batch items complete. */ type BatchProgressCallback = (done: number, total: number) => void; /** Options for batch processing. */ interface BatchOptions { /** * Maximum number of PDFs processed concurrently. * Defaults to 4 in Node (worker threads), or `files.length` elsewhere. */ concurrency?: number | undefined; /** Progress callback invoked after each file completes. */ onProgress?: BatchProgressCallback | undefined; } /** Result of a batch operation. */ interface BatchResult { /** Output PDF bytes for each input file (same order). */ outputs: Uint8Array[]; /** Number of files that were processed successfully. */ successCount: number; /** Indices of files that failed, mapped to their error. */ errors: Map; } /** * Process multiple PDFs in parallel (or with bounded concurrency). * * Each input `Uint8Array` is loaded as a {@link PdfDocument}, the * caller-supplied `operation` is applied, and the resulting bytes * are collected. * * In Node.js, true parallelism is available via `worker_threads` * (though this implementation uses async concurrency for simplicity * and to avoid serialization overhead). In all runtimes the * concurrency limiter ensures memory pressure stays manageable. * * @param files Array of raw PDF bytes. * @param operation An async function that receives a loaded * {@link PdfDocument} and returns the processed * PDF as `Uint8Array`. * @param options Concurrency and progress options. * @returns A {@link BatchResult} with outputs, success * count, and any per-file errors. */ declare function processBatch(files: Uint8Array[], operation: (doc: PdfDocument) => Promise, options?: BatchOptions): Promise; /** * Merge multiple PDFs in parallel chunks, then merge the chunks. * * For large collections this is significantly faster than sequential * merging because parsing and page-copying can overlap. * * @param files Array of raw PDF bytes to merge (in order). * @param options Concurrency and progress options. * @returns The merged PDF as `Uint8Array`. */ declare function batchMerge(files: Uint8Array[], options?: BatchOptions): Promise; /** * Flatten interactive form fields across many PDFs. * * Each PDF is loaded, its form is flattened (field values are burned * into page content), and the result is saved. * * @param files Array of raw PDF bytes. * @param options Concurrency and progress options. * @returns A {@link BatchResult} with flattened PDF outputs. */ declare function batchFlatten(files: Uint8Array[], options?: BatchOptions): Promise; //#endregion //#region src/wasm/inlineWasm.d.ts /** * @module wasm/inlineWasm * * Provides runtime access to inline (base64-encoded) WASM module bytes. * * This module is the runtime companion to the build-time code generation * script `scripts/generate-inline-wasm.ts`. It imports the generated * constants from `inlineWasm.generated.ts` and exposes a single function, * {@link getInlineWasmBytes}, that decodes a module's base64 string into * a `Uint8Array` on demand. * * Design: * - The heavy lifting (reading WASM files, base64 encoding) happens at * **build time** via the code generation script. * - At **runtime**, only a single base64 decode is needed per module, * and the result is cached. * - This approach avoids shipping base64 strings in the default bundle. * The generated file is only imported when inline WASM is needed * (e.g., as a fallback when no WASM path is configured). * * @packageDocumentation */ /** * The set of all WASM module names supported by the library. * * These correspond to the crate directories under `src/wasm/`. */ declare const WASM_MODULE_NAMES: readonly ["libdeflate", "png", "ttf", "shaping", "jbig2", "jpeg"]; /** Union type of all valid WASM module names. */ type WasmModuleName = (typeof WASM_MODULE_NAMES)[number]; /** * Retrieve the decoded WASM bytes for a given module name. * * On first call for a module, the base64 string from the generated file * is decoded into a `Uint8Array`. Subsequent calls return the cached * result. * * @param name The WASM module name (e.g., `'libdeflate'`, `'png'`). * @returns The decoded WASM binary as a `Uint8Array`. * @throws If the module name is unknown or the generated file does * not contain data for the requested module. * * @example * ```ts * const wasmBytes = getInlineWasmBytes('libdeflate'); * const module = await WebAssembly.compile(wasmBytes); * ``` */ declare function getInlineWasmBytes(name: string): Uint8Array; /** * Check whether a given module name is a valid WASM module name. * * @param name The name to check. * @returns `true` if the name is one of the known WASM modules. */ declare function isValidModuleName(name: string): name is WasmModuleName; /** * Check whether inline WASM data is available for a given module. * * Returns `true` if the generated file contains base64 data for the * requested module. Returns `false` if the generated file does not * exist or does not include the module. * * @param name The WASM module name. * @returns `true` if inline bytes can be retrieved for this module. */ declare function hasInlineWasmData(name: string): boolean; declare namespace index_d_exports { export { AFRelationship, AccessibilityIssue, AddBookmarkOptions, AnalysisReport, AnalyzeImagesOptions, Angle, AnnotationFlags, AnnotationOptions, AnnotationType, AppearanceProviderFor, AppendOptions, AssociatedFileOptions, AssociatedFileResult, BarcodeMatrix, BarcodeOptions, BarcodeReadResult, BatchOptimizeOptions, BatchOptions, BatchProgressCallback, BatchResult, BlendMode, BookmarkNode, BookmarkRef, ButtonAppearanceOptions, ByteRangeResult, ByteWriter, CIDFontData, CIDSystemInfoData, CaretSymbol, CatalogOptions, CellContent, ChangeTracker, CheckboxAppearanceOptions, ChromaSubsampling, CmykColor, Code128Options, Code39Options, Color, ColorStop, CombedTextLayoutError, ComputeFontSizeOptions, ContentStreamOperator, CounterSignatureInfo, CropBox, DataMatrixOptions, DataMatrixResult, DeduplicationReport, Degrees, DiffEntry, DirectEmbedOptions, DirectEmbedResult, DocumentDiff, DocumentMetadata, DocumentStructure, DownscaleOptions, DrawCircleOptions, DrawEllipseOptions, DrawImageOptions, DrawLineOptions, DrawPageOptions, DrawQrCodeOptions, DrawRectangleOptions, DrawSquareOptions, DrawSvgPathOptions, DrawTableOptions, DrawTextOptions, DropdownAppearanceOptions, DssData, BarcodeOptions as EanOptions, EmbedFontOptions, EmbedPageOptions, EmbeddedFile, EmbeddedFont, EmbeddedPdfPage, EncryptAlgorithm, EncryptDictValues, EncryptOptions, EncryptedPdfError, EnforcePdfAOptions, EnforcePdfAResult, EnforcementAction, ErrorCorrectionLevel, ExceededMaxLengthError, FieldAlreadyExistsError, FieldExistsAsNonTerminalError, FieldFlags, FieldLockInfo, FieldLockOptions, FieldType, FileAttachmentIcon, FlattenFormResult, FlattenOptions, FontDescriptorData, FontEmbeddingResult, FontMetrics, FontNotEmbeddedError, FontRef, ForeignPageError, FreeTextAlignment, GradientFill, GrayscaleColor, IccProfile, IfdEntry, ImageAlignment, ImageAnalysis, ImageDpi, ImageFormat, ImageInfo, ImageOptimizeEntry, ImageOptimizeOptions, ImageRef, IncrementalChange, IncrementalObject, IncrementalSaveOptions, IncrementalSaveResult, InitWasmOptions, InvalidFieldNamePartError, ItfOptions, JpegDecodeResult, JpegMarkerInfo, JpegMetadata, JpegWasmModule, LayoutCombedOptions, LayoutMultilineOptions, LayoutMultilineResult, LayoutSinglelineOptions, LayoutSinglelineResult, LineCapStyle, LineEndingStyle, LineJoinStyle, LinearGradientOptions, LinearizationInfo, LinearizationOptions, LinkHighlightMode, ListboxAppearanceOptions, LoadPdfOptions, LtvOptions, MarkedContentScope, MdpPermission, MissingOnValueCheckError, ModificationReport, ModificationViolation, ModificationViolationType, MultiPageTableResult, NestedTableContent, NoSuchFieldError, NormalizedStop, Operand, OptimizationReport, OptimizeResult, OutlineDestination, OutlineItemOptions, OutputIntentOptions, OverflowMode, OverflowResult, PDFOperator, PageContent, PageEntry, PageLabelRange, PageLabelStyle, PageRange, PageSize, PageSizes, ParseSpeeds, ParsedXmpMetadata, PatternFill, Pdf417Matrix, Pdf417Options, PdfAIssue, PdfALevel, PdfAProfile, PdfAValidationResult, PdfAXmpOptions, PdfAnnotation, PdfArray, PdfBool, PdfButtonField, PdfCaretAnnotation, PdfCheckboxField, PdfCircleAnnotation, PdfDict, PdfDocument, PdfDropdownField, PdfEncryptionHandler, PdfField, PdfFileAttachmentAnnotation, PdfForm, PdfFreeTextAnnotation, PdfHighlightAnnotation, PdfInkAnnotation, PdfLayer, PdfLayerManager, PdfLineAnnotation, PdfLinkAnnotation, PdfListboxField, PdfName, PdfNull, PdfNumber, PdfObject, PdfObjectRegistry, PdfOutlineItem, PdfOutlineTree, PdfPage, PdfParseError, PdfPermissionFlags, PdfPolyLineAnnotation, PdfPolygonAnnotation, PdfPopupAnnotation, PdfRadioGroup, PdfRedactAnnotation, PdfRef, PdfSaveOptions, PdfSignatureField, PdfSignatureInfo, PdfSquareAnnotation, PdfSquigglyAnnotation, PdfStampAnnotation, PdfStream, PdfStreamWriter, PdfStrikeOutAnnotation, PdfString, PdfStructureElement, PdfStructureTree, PdfTextAnnotation, PdfTextField, PdfUaEnforcementResult, PdfUaError, PdfUaLevel, PdfUaValidationResult, PdfUaWarning, PdfUnderlineAnnotation, PdfViewerPreferences, PdfWorker, PdfWorkerOptions, PdfWriter, PrepareAppearanceOptions, PresetName, PresetOptions, ProgressInfo, QrCodeMatrix, QrCodeOptions, RadialGradientFill, RadialGradientOptions, Radians, RadioAppearanceOptions, RawImageData, RecompressOptions, RedactionMark, RedactionOptions, RedactionResult, RefResolver, RegistryEntry, RemovePageFromEmptyDocumentError, RgbColor, RichTextFieldReadError, RuntimeKind, SRGB_ICC_PROFILE, SetTitleOptions, SignOptions, SignatureAppearanceOptions, SignatureByteRange, SignatureChainEntry, SignatureChainResult, SignatureOptions, SignatureVerificationResult, SignerInfo, SoftMaskBuilder, SoftMaskRef, StandardFontName, StandardFonts, StandardStampName, StripOptions, StripResult, StrippedFeature, StructureElementOptions, StructureType, StyledBarcodeOptions, SubsetCmap, SubsetResult, SvgDrawCommand, SvgElement, SvgRenderOptions, TableCell, TableColumn, TablePreset, TableRenderResult, TableRow, TextAlignment, TextAnnotationIcon, TextAppearanceOptions, TextExtractionOptions, TextItem, TextRenderingMode, TextRun, TiffCmykEmbedResult, TiffDecodeOptions, TiffIfdEntry, TiffImage, TilingPatternOptions, TimestampResult, TrailerInfo, TransparencyFinding, TransparencyGroupOptions, TransparencyInfo, Type0FontData, UnexpectedFieldTypeError, BarcodeOptions as UpcOptions, ViewerPreferences, VisibleSignatureOptions, WasmLoaderConfig, WasmModuleName, WatermarkOptions, WebPImage, WidgetAnnotationHost, WidthEntry, XmpIssue, XmpValidationResult, addBookmark, addCounterSignature, addFieldLock, addWatermark, addWatermarkToPage, aesDecryptCBC, aesEncryptCBC, analyzeImages, analyzeJpegMarkers, annotationFromDict, appendIncrementalUpdate, applyFillColor, applyOverflow, applyPreset, applyRedaction, applyRedactions, applyStrokeColor, applyTablePreset, asNumber, asPDFName, asPDFNumber, attachFile, base64Decode, base64Encode, batchFlatten, batchMerge, beginArtifact, beginArtifactWithType, beginLayerContent, beginMarkedContent, beginMarkedContentSequence, beginMarkedContentWithProperties, beginText, borderedPreset, buildAfArray, buildAnnotationDict, buildCatalog, buildDocMdpReference, buildDocumentStructure, buildDssDictionary, buildEmbeddedFilesNameTree, buildFieldLockDict, buildGradientObjects, buildInfoDict, buildOutputIntent, buildPageTree, buildPatternObjects, buildPkcs7Signature, buildTimestampRequest, buildViewerPreferencesDict, buildXmpMetadata, calculateBarcodeDimensions, calculateEanCheckDigit, calculateUpcCheckDigit, canDirectEmbed, checkAccessibility, circlePath, clearWasmCache, clipEvenOdd, clip as clipOp, closeAndStroke, closeFillAndStroke, closeFillEvenOddAndStroke, closePath as closePathOp, cmyk, code128ToOperators, code39ToOperators, colorToComponents, componentsToColor, computeCode39CheckDigit, computeFileEncryptionKey, computeFontSize, computeImageDpi, computeObjectHash, computeSignatureHash, computeTargetDimensions, concatMatrix, concatMatrix as concatTransformationMatrix, configureWasmLoader, convertTiffCmykToRgb, convertToGrayscale, copyPages, countOccurrences, createAnnotation, createAssociatedFile, createMarkedContentScope, createPdf, createXmpStream, cropPage, curveToFinal, curveToInitial, curveTo as curveToOp, dataMatrixToOperators, decodeImageStream, decodeJpegWasm, decodePermissions, decodeStream, decodeTiff, decodeTiffAll, decodeTiffPage, decodeWebP, deduplicateImages, degrees, degreesToRadians, delinearizePdf, detectImageFormat, detectModifications, detectRuntime, detectTransparency, diffSignedContent, downscaleImage, drawImageWithMatrix, drawImageXObject, drawXObject as drawObject, drawSvgOnPage, drawXObject, ean13ToOperators, ean8ToOperators, ellipsePath, ellipsisText, embedIccProfile, embedLtvData, embedPageAsFormXObject, embedSignature, embedTiffCmyk, embedTiffDirect, encodeCode128, encodeCode128Values, encodeCode39, encodeContextTag, encodeDataMatrix, encodeEan13, encodeEan8, encodeInteger, encodeItf, encodeJpegWasm, encodeLength, encodeOID, encodeOctetString, encodePdf417, encodePermissions, encodePngFromPixels, encodePrintableString, encodeQrCode, encodeSequence, encodeSet, encodeUTCTime, encodeUpcA, encodeUtf8String, endArtifact, endLayerContent, endMarkedContent, endPath as endPathOp, endText, enforcePdfA, enforcePdfAFull, enforcePdfUa, estimateJpegQuality, estimateTextWidth, extractIccProfile, extractImages, extractJpegMetadata, extractMetrics, extractText, extractTextWithPositions, extractXmpMetadata, fillAndStroke as fillAndStrokeOp, fillEvenOdd, fillEvenOddAndStroke, fill as fillOp, findChangedObjects, findExistingSignatures, findSignatures, flattenField, flattenFields, flattenForm, flattenTransparency, formatHexContext, formatPdfDate, generateButtonAppearance, generateCheckboxAppearance, generateCircleAppearance, generateDropdownAppearance, generateFreeTextAppearance, generateHighlightAppearance, generateInkAppearance, generateLineAppearance, generateListboxAppearance, generatePdfAXmp, generatePdfAXmpBytes, generateRadioAppearance, generateSignatureAppearance, generateSquareAppearance, generateSquigglyAppearance, generateSrgbIccProfile, generateStrikeOutAppearance, generateSymbolToUnicodeCmap, generateTextAppearance, generateUnderlineAppearance, generateWinAnsiToUnicodeCmap, generateZapfDingbatsToUnicodeCmap, getAttachments, getBookmarks, getCertificationLevel, getCounterSignatures, getFieldLocks, getImageFormatName, getInlineWasmBytes, getLinearizationInfo, getPageLabels, getPageSize, getProfile, getRedactionMarks, getSignatures, getSupportedFormats, getSupportedLevels, getTiffPageCount, getToUnicodeCmap, grayscale, hasInlineWasmData, hasLtvData, initJpegWasm, initWasm, injectJpegMetadata, insertPage, instantiateWasmModuleStreaming, isAccessible, isCmykTiff, isGrayscaleImage, isJpegWasmReady, isLinearized, isOpenTypeCFF, isTiff, isTrueType, isValidLevel, isValidModuleName, isWasmDisabled, isWasmModuleCached, isWebP, isWebPLossless, itfToOperators, layoutCombedText, layoutMultilineText, layoutSinglelineText, lineTo as lineToOp, linearGradient, linearizePdf, loadPdf, loadWasmModule, loadWasmModuleStreaming, markForRedaction, md5, mergePdfs, minimalPreset, movePage, moveText as moveTextOp, moveTextSetLeading, moveTo as moveToOp, nextLine as nextLineOp, optimizeAllImages, optimizeImage, optimizeIncrementalSave, parseContentStream, parseExistingTrailer, parseIccColorSpace, parseIccDescription, parseSvg, parseSvgColor, parseSvgPath, parseSvgTransform, parseTiffIfd, parseTimestampResponse, parseViewerPreferences, parseXmpMetadata$1 as parseXmpMetadata, parseXmpMetadata as parseXmpPdfAMetadata, pdf417ToOperators, restoreState as popGraphicsState, prepareForSigning, processBatch, professionalPreset, provideWasmBytes, saveState as pushGraphicsState, qrCodeToOperators, radialGradient, radians, radiansToDegrees, rc4, readBarcode, readCode128, readCode39, readEan13, readEan8, recompressImage, recompressWebP, rectangle as rectangleOp, removeAllBookmarks, removeBookmark, removePage, removePageLabels, removePages, renderMultiPageTable, renderStyledBarcode, renderTable, requestTimestamp, resetWasmLoader, resizePage, restoreState, reversePages, rgb, rotateAllPages, rotate as rotateOp, rotatePage, rotationMatrix, saveDocumentIncremental, saveIncremental, saveIncrementalWithSignaturePreservation, saveState, scale as scaleOp, serializePdf, setCertificationLevel, setCharacterSpacing as setCharacterSpacingOp, setCharacterSpacing as setCharacterSqueeze, setColorSpace, setDashPattern as setDashPatternOp, setFillColor, setFillColorCmyk, setFillColorGray, setFillColorRgb, setFillingColor, setFlatness, setFont as setFontAndSize, setFont as setFontOp, setFontSize as setFontSizeOp, setGraphicsState as setGraphicsStateOp, setLeading as setLeadingOp, setLineCap as setLineCapOp, setLeading as setLineHeight, setLineJoin as setLineJoinOp, setLineWidth as setLineWidthOp, setMiterLimit, setPageLabels, setStrokeColor, setStrokeColorCmyk, setStrokeColorGray, setStrokeColorRgb, setStrokeColorSpace, setStrokingColor, setTextMatrix as setTextMatrixOp, setTextRenderingMode as setTextRenderingModeOp, setTextRise as setTextRiseOp, setWordSpacing as setWordSpacingOp, sha256, sha384, sha512, showTextArray, showTextHex, showTextNextLine, showText as showTextOp, showTextWithSpacing, shrinkFontSize, signPdf, skew as skewOp, splitPdf, stripProhibitedFeatures, stripedPreset, stroke as strokeOp, summarizeIssues, svgToPdfOperators, tilingPattern, translate as translateOp, truncateText, upcAToOperators, validateByteRangeIntegrity, validatePdfA, validatePdfUa, validateSignatureChain, validateXmpMetadata, valuesToModules, verifyOwnerPassword, verifySignature, verifySignatures, verifyUserPassword, webpToJpeg, webpToPng, wrapInMarkedContent, wrapText }; } /** * Options for WASM module initialization. */ interface InitWasmOptions { /** Initialize the deflate/inflate WASM module. Default: `false`. */ deflate?: boolean | undefined; /** Initialize the PNG decoding WASM module. Default: `false`. */ png?: boolean | undefined; /** Initialize the font subsetting WASM module. Default: `false`. */ fonts?: boolean | undefined; /** * Pre-loaded WASM bytes for the deflate module. * When provided, the module is instantiated directly from these bytes. */ deflateWasm?: Uint8Array | undefined; /** * Pre-loaded WASM bytes for the PNG decoding module. */ pngWasm?: Uint8Array | undefined; /** * Pre-loaded WASM bytes for the font subsetting module. */ fontWasm?: Uint8Array | undefined; /** Initialize the JPEG encoding/decoding WASM module. Default: `false`. */ jpeg?: boolean | undefined; /** * Pre-loaded WASM bytes for the JPEG encoding/decoding module. */ jpegWasm?: Uint8Array | undefined; } /** * Initialize the optional WASM acceleration modules. * * Call this once before `save()` if you want WASM-accelerated * compression, PNG decoding, or font subsetting. It is safe to call * multiple times -- subsequent calls are no-ops. * * If not called, the library falls back to pure-JS implementations * (fflate for compression, JS for PNG decoding). * * @param options Configuration for which WASM modules to load, * and optionally pre-loaded WASM binary bytes. * When a string or URL is passed, it is treated as * a legacy `wasmUrl` parameter (ignored for backward * compatibility). * @returns A promise that resolves when all requested modules * are ready. */ declare function initWasm(options?: string | URL | InitWasmOptions): Promise; //#endregion export { PresetOptions as $, PdfSquareAnnotation as $a, IncrementalSaveOptions as $i, DeduplicationReport as $n, nextLine as $o, generateZapfDingbatsToUnicodeCmap as $r, configureWasmLoader as $t, flattenForm as A, generateCircleAppearance as Aa, addCounterSignature as Ai, detectImageFormat as An, summarizeIssues as Ao, generatePdfAXmpBytes as Ar, moveTo as As, encodeEan13 as At, NoSuchFieldError as B, PdfFileAttachmentAnnotation as Ba, ModificationReport as Bi, injectJpegMetadata as Bn, beginMarkedContentSequence as Bo, createAssociatedFile as Br, isTrueType as Bs, code128ToOperators as Bt, getBookmarks as C, encodeUtf8String as Ca, optimizeIncrementalSave as Ci, canDirectEmbed as Cn, PdfUaLevel as Co, applyRedaction as Cr, ellipsePath as Cs, encodeDataMatrix as Ct, FlattenOptions as D, embedSignature as Da, embedLtvData as Di, webpToJpeg as Dn, validatePdfUa as Do, enforcePdfAFull as Dr, fillEvenOdd as Ds, calculateEanCheckDigit as Dt, FlattenFormResult as E, computeSignatureHash as Ea, buildDssDictionary as Ei, recompressWebP as En, enforcePdfUa as Eo, EnforcementAction as Er, fillAndStroke as Es, upcAToOperators as Et, FieldExistsAsNonTerminalError as F, generateSquareAppearance as Fa, FieldLockInfo as Fi, convertTiffCmykToRgb as Fn, PDFOperator as Fo, stripProhibitedFeatures as Fr, setLineJoin as Fs, Code39Options as Ft, OverflowResult as G, PdfInkAnnotation as Ga, buildDocMdpReference as Gi, computeTargetDimensions as Gn, wrapInMarkedContent as Go, parseXmpMetadata as Gr, __exportAll as Gs, BarcodeOptions as Gt, RichTextFieldReadError as H, PdfCaretAnnotation as Ha, ModificationViolationType as Hi, analyzeJpegMarkers as Hn, createMarkedContentScope as Ho, XmpIssue as Hr, IncrementalSaveResult as Hs, encodeCode128Values as Ht, FontNotEmbeddedError as I, generateSquigglyAppearance as Ia, FieldLockOptions as Ii, embedTiffCmyk as In, MarkedContentScope as Io, AFRelationship as Ir, setLineWidth as Is, code39ToOperators as It, estimateTextWidth as J, LineEndingStyle as Ja, SignatureChainEntry as Ji, extractIccProfile as Jn, drawXObject as Jo, getProfile as Jr, PdfWorker as Jt, applyOverflow as K, PdfStampAnnotation as Ka, getCertificationLevel as Ki, IccProfile as Kn, drawImageWithMatrix as Ko, validateXmpMetadata as Kr, base64Decode as Kt, ForeignPageError as L, generateStrikeOutAppearance as La, addFieldLock as Li, isCmykTiff as Ln, beginArtifact as Lo, AssociatedFileOptions as Lr, setMiterLimit as Ls, computeCode39CheckDigit as Lt, EncryptedPdfError as M, generateHighlightAppearance as Ma, DiffEntry as Mi, getSupportedFormats as Mn, createXmpStream as Mo, StripResult as Mr, setDashPattern as Ms, ItfOptions as Mt, ExceededMaxLengthError as N, generateInkAppearance as Na, DocumentDiff as Ni, TiffCmykEmbedResult as Nn, parseXmpMetadata$1 as No, StrippedFeature as Nr, setFlatness as Ns, encodeItf as Nt, flattenField as O, findSignatures as Oa, hasLtvData as Oi, webpToPng as On, checkAccessibility as Oo, PdfAXmpOptions as Or, fillEvenOddAndStroke as Os, ean13ToOperators as Ot, FieldAlreadyExistsError as P, generateLineAppearance as Pa, diffSignedContent as Pi, TiffIfdEntry as Pn, PdfStreamWriter as Po, countOccurrences as Pr, setLineCap as Ps, itfToOperators as Pt, PresetName as Q, PdfPolygonAnnotation as Qa, IncrementalObject as Qi, isGrayscaleImage as Qn, moveTextSetLeading as Qo, generateWinAnsiToUnicodeCmap as Qr, clearWasmCache as Qt, InvalidFieldNamePartError as R, generateUnderlineAppearance as Ra, buildFieldLockDict as Ri, JpegMetadata as Rn, beginArtifactWithType as Ro, AssociatedFileResult as Rr, stroke as Rs, encodeCode39 as Rt, addBookmark as S, encodeUTCTime as Sa, findChangedObjects as Si, DirectEmbedResult as Sn, PdfUaError as So, RedactionResult as Sr, curveToInitial as Ss, dataMatrixToOperators as St, removeBookmark as T, PrepareAppearanceOptions as Ta, LtvOptions as Ti, encodePngFromPixels as Tn, PdfUaWarning as To, EnforcePdfAResult as Tr, fill as Ts, encodeUpcA as Tt, UnexpectedFieldTypeError as U, PdfPopupAnnotation as Ua, detectModifications as Ui, ImageDpi as Un, endArtifact as Uo, XmpValidationResult as Ur, saveDocumentIncremental as Us, valuesToModules as Ut, RemovePageFromEmptyDocumentError as V, CaretSymbol as Va, ModificationViolation as Vi, JpegMarkerInfo as Vn, beginMarkedContentWithProperties as Vo, ParsedXmpMetadata as Vr, ChangeTracker as Vs, encodeCode128 as Vt, OverflowMode as W, PdfRedactAnnotation as Wa, MdpPermission as Wi, computeImageDpi as Wn, endMarkedContent as Wo, extractXmpMetadata as Wr, saveIncremental as Ws, BarcodeMatrix as Wt, truncateText as X, PdfLineAnnotation as Xa, validateSignatureChain as Xi, parseIccDescription as Xn, endText as Xo, isValidLevel as Xr, RuntimeKind as Xt, shrinkFontSize as Y, PdfCircleAnnotation as Ya, SignatureChainResult as Yi, parseIccColorSpace as Yn, beginText as Yo, getSupportedLevels as Yr, PdfWorkerOptions as Yt, wrapText as Z, PdfPolyLineAnnotation as Za, AppendOptions as Zi, convertToGrayscale as Zn, moveText as Zo, generateSymbolToUnicodeCmap as Zr, WasmLoaderConfig as Zt, removePageLabels as _, encodeOID as _a, getLinearizationInfo as _i, WebPImage as _n, EncryptDictValues as _o, JpegWasmModule as _r, closeFillAndStroke as _s, Pdf417Options as _t, getInlineWasmBytes as a, saveIncrementalWithSignaturePreservation as aa, TransparencyFinding as ai, loadWasmModuleStreaming as an, PdfFreeTextAnnotation as ao, optimizeAllImages as ar, setTextRenderingMode as as, professionalPreset as at, BookmarkNode as b, encodeSequence as ba, IncrementalChange as bi, isWebPLossless as bn, verifyUserPassword as bo, initJpegWasm as br, curveTo as bs, DataMatrixOptions as bt, BatchOptions as c, buildTimestampRequest as ca, flattenTransparency as ci, IfdEntry as cn, PdfTextAnnotation as co, OptimizeResult as cr, showText as cs, readBarcode as ct, batchFlatten as d, SignatureOptions as da, PdfAValidationResult as di, decodeTiff as dn, sha384 as do, downscaleImage as dr, showTextNextLine as ds, readEan13 as dt, SignatureByteRange as ea, getToUnicodeCmap as ei, detectRuntime as en, PdfHighlightAnnotation as eo, deduplicateImages as er, setCharacterSpacing as es, TablePreset as et, batchMerge as f, SignerInfo as fa, enforcePdfA as fi, decodeTiffAll as fn, sha512 as fo, estimateJpegQuality as fr, showTextWithSpacing as fs, readEan8 as ft, getPageLabels as g, encodeLength as ga, delinearizePdf as gi, parseTiffIfd as gn, md5 as go, JpegDecodeResult as gr, closeAndStroke as gs, Pdf417Matrix as gt, PageLabelStyle as h, encodeInteger as ha, LinearizationOptions as hi, isTiff as hn, rc4 as ho, ChromaSubsampling as hr, clipEvenOdd as hs, renderStyledBarcode as ht, WasmModuleName as i, parseExistingTrailer as ia, generateSrgbIccProfile as ii, loadWasmModule as in, FreeTextAlignment as io, ProgressInfo as ir, setTextMatrix as is, minimalPreset as it, CombedTextLayoutError as j, generateFreeTextAppearance as ja, getCounterSignatures as ji, getImageFormatName as jn, buildXmpMetadata as jo, StripOptions as jr, rectangle as js, encodeEan8 as jt, flattenFields as k, prepareForSigning as ka, CounterSignatureInfo as ki, ImageFormat as kn, isAccessible as ko, generatePdfAXmp as kr, lineTo as ks, ean8ToOperators as kt, BatchProgressCallback as l, parseTimestampResponse as la, PdfAIssue as li, TiffDecodeOptions as ln, TextAnnotationIcon as lo, RawImageData as lr, showTextArray as ls, readCode128 as lt, PageLabelRange as m, encodeContextTag as ma, LinearizationInfo as mi, getTiffPageCount as mn, aesEncryptCBC as mo, recompressImage as mr, clip as ms, calculateBarcodeDimensions as mt, index_d_exports as n, appendIncrementalUpdate as na, buildOutputIntent as ni, isWasmDisabled as nn, PdfStrikeOutAnnotation as no, ImageOptimizeEntry as nr, setFontSize as ns, applyTablePreset as nt, hasInlineWasmData as o, validateByteRangeIntegrity as oa, TransparencyInfo as oi, provideWasmBytes as on, LinkHighlightMode as oo, DownscaleOptions as or, setTextRise as os, stripedPreset as ot, processBatch as p, buildPkcs7Signature as pa, validatePdfA as pi, decodeTiffPage as pn, aesDecryptCBC as po, optimizeImage as pr, circlePath as ps, StyledBarcodeOptions as pt, ellipsisText as q, StandardStampName as qa, setCertificationLevel as qi, embedIccProfile as qn, drawImageXObject as qo, PdfAProfile as qr, base64Encode as qt, initWasm as r, findExistingSignatures as ra, SRGB_ICC_PROFILE as ri, isWasmModuleCached as rn, PdfUnderlineAnnotation as ro, OptimizationReport as rr, setLeading as rs, borderedPreset as rt, isValidModuleName as s, TimestampResult as sa, detectTransparency as si, resetWasmLoader as sn, PdfLinkAnnotation as so, ImageOptimizeOptions as sr, setWordSpacing as ss, BarcodeReadResult as st, InitWasmOptions as t, TrailerInfo as ta, OutputIntentOptions as ti, instantiateWasmModuleStreaming as tn, PdfSquigglyAnnotation as to, BatchOptimizeOptions as tr, setFont as ts, applyPreset as tt, BatchResult as u, requestTimestamp as ua, PdfALevel as ui, TiffImage as un, sha256 as uo, RecompressOptions as ur, showTextHex as us, readCode39 as ut, setPageLabels as v, encodeOctetString as va, isLinearized as vi, decodeWebP as vn, computeFileEncryptionKey as vo, decodeJpegWasm as vr, closeFillEvenOddAndStroke as vs, encodePdf417 as vt, removeAllBookmarks as w, ByteRangeResult as wa, DssData as wi, embedTiffDirect as wn, PdfUaValidationResult as wo, EnforcePdfAOptions as wr, endPath as ws, calculateUpcCheckDigit as wt, BookmarkRef as x, encodeSet as xa, computeObjectHash as xi, DirectEmbedOptions as xn, PdfUaEnforcementResult as xo, isJpegWasmReady as xr, curveToFinal as xs, DataMatrixResult as xt, AddBookmarkOptions as y, encodePrintableString as ya, linearizePdf as yi, isWebP as yn, verifyOwnerPassword as yo, encodeJpegWasm as yr, closePath as ys, pdf417ToOperators as yt, MissingOnValueCheckError as z, FileAttachmentIcon as za, getFieldLocks as zi, extractJpegMetadata as zn, beginMarkedContent as zo, buildAfArray as zr, isOpenTypeCFF as zs, Code128Options as zt }; //# sourceMappingURL=index-B4S61WjK.d.mts.map