import { $ as PageEntry, $n as rotationMatrix, $t as EmbedPageOptions, A as signPdf, An as createAnnotation, Ar as setStrokeColor, At as TableRow, B as loadPdf, Bn as ParseSpeeds, Bt as GradientFill, C as attachFile, Cn as parseSvgTransform, Cr as rgbToCmyk, Ct as DrawTableOptions, D as SignOptions, Dn as PdfAnnotation, Dr as setFillColorGray, Dt as TableCell, E as PdfSignatureInfo, En as AnnotationType, Er as setFillColorCmyk, Et as PageContent, F as OutlineDestination, Fn as StructureType, Fr as setStrokingColor, Ft as QrCodeMatrix, G as EncryptOptions, Gn as Radians, Gt as RadialGradientOptions, H as PdfWriter, Hn as TextRenderingMode, Ht as NormalizedStop, I as OutlineItemOptions, In as BlendMode$1, Ir as spotColor, It as QrCodeOptions, J as decodePermissions, Jn as degreesToRadians, Jt as buildPatternObjects, K as PdfEncryptionHandler, Kn as concatMatrix, Kt as TilingPatternOptions, L as PdfOutlineItem, Ln as ImageAlignment, Lr as spotResourceName, Lt as encodeQrCode, M as ViewerPreferences, Mn as PdfStructureElement, Mr as setStrokeColorGray, Mt as renderMultiPageTable, N as buildViewerPreferencesDict, Nn as PdfStructureTree, Nr as setStrokeColorRgb, Nt as renderTable, O as VisibleSignatureOptions, On as annotationFromDict, Or as setFillColorRgb, Ot as TableColumn, P as parseViewerPreferences, Pn as StructureElementOptions, Pr as setStrokeColorSpace, Pt as ErrorCorrectionLevel, Q as DocumentStructure, Qn as rotate, Qt as DrawPageOptions, R as PdfOutlineTree, Rn as LineCapStyle, Rt as qrCodeToOperators, S as EmbeddedFile, Sn as parseSvgPath, Sr as rgb, St as CellContent, T as getAttachments, Tn as AnnotationOptions, Tr as setFillColor, Tt as NestedTableContent, U as serializePdf, Un as Angle, Ut as PatternFill, V as PdfSaveOptions, Vn as TextAlignment$1, Vt as LinearGradientOptions, W as EncryptAlgorithm, Wn as Degrees, Wt as RadialGradientFill, X as CatalogOptions, Xn as radiansToDegrees, Xt as radialGradient, Y as encodePermissions, Yn as radians, Yt as linearGradient, Z as DocumentMetadata, Zn as restoreState, Zt as tilingPattern, _ as AFRelationship, _n as SvgGradientStop, _r as componentsToColor, _t as PageSizes, a as StandardFonts, an as getRedactionMarks, ar as CmykColor, at as DrawCircleOptions, b as buildAfArray, bn as parseSvg, br as grayscale, bt as SoftMaskRef, c as PdfPluginManager, cn as PdfLayerManager, cr as GrayscaleColor, ct as DrawLineOptions, d as SignatureVerificationResult, dn as SvgRenderOptions, dr as applyFillColor, dt as DrawSquareOptions, en as EmbeddedPdfPage, er as saveState, et as buildCatalog, f as verifySignature, fn as drawSvgOnPage, fr as applyStrokeColor, ft as DrawSvgPathOptions, g as addWatermarkToPage, gn as SvgGradient, gr as colorToHex, gt as PageSize, h as addWatermark, hn as SvgElement, hr as colorToComponents, ht as ImageRef, i as StandardFontName, in as applyRedactions, ir as translate, it as formatPdfDate, j as PdfViewerPreferences, jn as AccessibilityIssue, jr as setStrokeColorCmyk, jt as TextRun, k as getSignatures, kn as buildAnnotationDict, kr as setFillingColor, kt as TableRenderResult, l as PluginDocument, ln as beginLayerContent, lr as RgbColor, lt as DrawQrCodeOptions, m as WatermarkOptions, mn as SvgDrawCommand, mr as cmykToRgb, mt as FontRef, n as PdfDocument, nn as RedactionMark, nr as setGraphicsState, nt as buildInfoDict, o as createPdf, on as markForRedaction, or as Color, ot as DrawEllipseOptions, p as verifySignatures, pn as svgToPdfOperators, pr as cmyk, pt as DrawTextOptions, q as PdfPermissionFlags, qn as degrees, qt as buildGradientObjects, r as SetTitleOptions, rn as RedactionOptions, rr as skew, rt as buildPageTree, s as PdfPlugin, sn as PdfLayer, sr as DeviceNColor, st as DrawImageOptions, t as EmbedFontOptions, tn as embedPageAsFormXObject, tr as scale, tt as buildDocumentStructure, u as PluginPage, un as endLayerContent, ur as SpotColor, ut as DrawRectangleOptions, v as AssociatedFileOptions, vn as applySpreadMethod, vr as deviceNColor, vt as PdfPage, w as buildEmbeddedFilesNameTree, wn as AnnotationFlags, wr as setColorSpace, wt as MultiPageTableResult, x as createAssociatedFile, xn as parseSvgColor, xr as hexToColor, xt as TransparencyGroupOptions, y as AssociatedFileResult, yn as interpolateLinearRgb, yr as deviceNResourceName, yt as SoftMaskBuilder, z as LoadPdfOptions, zn as LineJoinStyle, zt as ColorStop } from "./pdfDocument-C7TItmPQ.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-Ca86NDWn.mjs"; import { A as movePage, B as asPdfName, 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, V as asPdfNumber, _ 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-CTTeV1mZ.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-_CZdoUCD.mjs"; import { _ as parseContentStream, a as ImageInfo, c as PdfParseError, d as TextExtractionOptions, f as TextItem$1, 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$1, t as AnalysisReport, u as decodeStream } from "./compressionAnalysis-4EW8MJBa.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 /** * 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/spotColor.d.ts /** * Build a Separation colour space array for a spot colour. * * The returned `PdfArray` has the structure: * ``` * [/Separation /ColorantName /DeviceCMYK ] * ``` * * This array should be registered as a page colour space resource * under the name returned by {@link spotResourceName}. * * @param name Colorant name (e.g. `'PANTONE 185 C'`). * @param alternate The fallback colour whose space and values define * the tint-transform mapping. * @returns A `PdfArray` representing the Separation colour space. * * @example * ```ts * import { buildSeparationColorSpace, cmyk, spotResourceName } from 'modern-pdf-lib'; * * const pantone = cmyk(0, 0.91, 0.76, 0); * const csArray = buildSeparationColorSpace('PANTONE 185 C', pantone); * // Register as page resource: * // page.node.get('/Resources').get('/ColorSpace').set( * // `/${spotResourceName('PANTONE 185 C')}`, csArray * // ); * ``` */ declare function buildSeparationColorSpace(name: string, alternate: RgbColor | CmykColor | GrayscaleColor): PdfArray; /** * Build a DeviceN colour space array for multi-ink printing. * * The returned `PdfArray` has the structure: * ``` * [/DeviceN [/Colorant1 /Colorant2 ...] /DeviceCMYK ] * ``` * * @param colorants Ordered list of colorant names. * @param alternateSpace The alternate device colour space. * @returns A `PdfArray` representing the DeviceN colour space. */ declare function buildDeviceNColorSpace(colorants: string[], alternateSpace: "DeviceCMYK" | "DeviceRGB"): PdfArray; //#endregion //#region src/core/operators/text.d.ts /** * 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 /** * 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(registry: PdfObjectRegistry, 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 (section-aware, same-parent skip detection) * 5. Alt text on all illustration elements (excluding artifacts) * 6. Table header cells (size-aware, layout table aware) * 7. List structure (L/LI/Lbl/LBody) * 8. Reading order via structure tree * 9. Font embedding (excluding form-field-only fonts) * 10. Color contrast (AA: 4.5:1, AAA: 7:1) * 11. Bookmarks for navigation (documents > 3 pages) * 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 /** * 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 /** * 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): 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 /** * 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/form/fieldValidation.d.ts /** * Result of a field validation check. * * @property valid - Whether the value passed validation. * @property message - Optional human-readable error message when invalid. */ interface ValidationResult { valid: boolean; message?: string; } /** * Validate a field's value using a validation script string. * * The script is parsed to determine the validation type. If the script * matches a known Acrobat validation pattern (email, phone, range, etc.), * the corresponding built-in validation is applied. Otherwise, the value * is considered valid (custom scripts are not executed). * * @param field - The PdfField being validated. * @param value - The string value to validate. * @param script - The validation script (Acrobat JavaScript). * @returns A {@link ValidationResult} indicating whether the value is valid. */ declare function validateFieldValue(field: PdfField, value: string, script: string): ValidationResult; //#endregion //#region src/form/acrobatSpecialBuiltins.d.ts /** * Create a special field formatter matching Acrobat's `AFSpecial_Format`. * * | psf | Format | Example | * | --- | ------------------ | ------------- | * | 0 | ZIP Code | 12345 | * | 1 | ZIP+4 | 12345-6789 | * | 2 | Phone | (123) 456-7890 | * | 3 | SSN | 123-45-6789 | * * @param psf - The predefined special format type (0–3). * @returns A function that formats a digit string using the special mask. */ declare function AFSpecial_Format(psf: number): (value: string) => string; //#endregion //#region src/form/fieldVisibility.d.ts /** * A condition that determines whether a field should be visible, * based on another field's value. * * @property operator - The comparison operator. * @property value - The comparison value (not used for 'empty'/'notEmpty'). */ interface VisibilityCondition { operator: "equals" | "notEquals" | "contains" | "empty" | "notEmpty"; value?: string; } /** * Set the visibility of a form field. * * When `visible` is `true`, the Hidden and NoView flags are cleared. * When `visible` is `false`, the Hidden flag is set (the field is * completely hidden — not displayed and not printed). * * @param field - The field to show or hide. * @param visible - Whether the field should be visible. */ declare function setFieldVisibility(field: PdfField, visible: boolean): void; /** * Add a JavaScript action to a field that toggles the visibility of * another field based on a condition. * * This creates an `/AA` (additional actions) entry with a `/V` * (value-changed) trigger containing a JavaScript action. The script * reads the trigger field's value and shows/hides the target field * according to the given condition. * * Note: The generated JavaScript uses Acrobat's `getField()` API and * `display` property. It will only execute in viewers that support * JavaScript (e.g., Adobe Acrobat, Foxit). * * @param field - The field to attach the action to (trigger). * @param triggerField - The name of the field whose value is checked. * @param condition - The condition to evaluate. */ declare function addVisibilityAction(field: PdfField, triggerField: string, condition: VisibilityCondition): void; //#endregion //#region src/form/fieldReferences.d.ts /** * Resolve a field name to a PdfField instance. * * Handles hierarchical names (e.g., `"form.section.field"`) by looking * up the fully-qualified name in the form's field index. * * @param form - The PdfForm to search. * @param fieldName - The field name (partial or fully-qualified). * @returns The PdfField if found, or `null`. */ declare function resolveFieldReference(form: PdfForm, fieldName: string): PdfField | null; /** * Get a field's value by name. * * Convenience function that resolves the field and returns its string value. * * @param form - The PdfForm to search. * @param fieldName - The field name. * @returns The field's value as a string, or `null` if the field is not found. */ declare function getFieldValue(form: PdfForm, fieldName: string): string | null; /** * Set a field's value by name. * * Convenience function that resolves the field and sets its value. * * @param form - The PdfForm to search. * @param fieldName - The field name. * @param value - The value to set. * @returns `true` if the field was found and the value was set, `false` otherwise. */ declare function setFieldValue(form: PdfForm, fieldName: string, value: string): boolean; //#endregion //#region src/form/scriptSandbox.d.ts /** * @module form/scriptSandbox * * Sandboxed execution environment for PDF form JavaScript. * * PDF forms can contain JavaScript for calculations, validation, and * formatting (a subset of the Acrobat JavaScript API). This module * provides a secure sandbox that executes those scripts without * granting access to the host environment. */ /** Options for creating a sandbox. */ interface SandboxOptions { /** Maximum execution time in milliseconds (default: 1000). */ timeout?: number | undefined; /** Maximum memory usage in bytes (advisory, default: 10 MB). */ maxMemory?: number | undefined; /** Additional global names to allow in the sandbox scope. */ allowedGlobals?: string[] | undefined; } /** Result of executing a script in the sandbox. */ interface SandboxResult { /** Whether the script executed without errors. */ success: boolean; /** The return value of the script expression (if any). */ returnValue?: unknown; /** Error message if `success` is false. */ error?: string; /** Execution time in milliseconds. */ executionTimeMs: number; } /** * A sandboxed execution environment for PDF form JavaScript. * Create via {@link createSandbox}. */ declare class FormScriptSandbox { private readonly timeout; private readonly allowedGlobals; private fieldValues; private builtins; private destroyed; constructor(options?: SandboxOptions); /** Execute a script in the sandbox. */ execute(script: string): SandboxResult; /** Set field values available to scripts. */ setFieldValues(values: Map): void; /** Get field values (possibly modified by scripts). */ getFieldValues(): Map; /** Register a built-in function. */ registerBuiltin(name: string, fn: (...args: unknown[]) => unknown): void; /** Reset state (field values and custom builtins). */ reset(): void; /** Destroy the sandbox. */ destroy(): void; private registerDefaultBuiltins; private buildScope; } /** * Create a new sandboxed execution environment for PDF form scripts. */ declare function createSandbox(options?: SandboxOptions): FormScriptSandbox; //#endregion //#region src/form/acrobatBuiltins.d.ts /** * @module form/acrobatBuiltins * * Acrobat-compatible number formatting and validation built-ins. * * Implements: * - `AFNumber_Format` — format a number string for display * - `AFNumber_Keystroke` — validate a keystroke for number input * - `formatNumber` — general-purpose number formatter * - `parseFormattedNumber` — parse a formatted number back to numeric * * These are pure string transformers — they do not require PDF access. * * Reference: Acrobat JavaScript Scripting Reference, * AFNumber_Format / AFNumber_Keystroke. */ /** * Options for the general-purpose number formatter. */ interface NumberFormatOptions { /** Number of decimal places (default: 2). */ decimals?: number; /** Thousands separator character (default: ','). */ thousandsSep?: string; /** Decimal separator character (default: '.'). */ decimalSep?: string; /** How to display negative numbers (default: 'minus'). */ negativeStyle?: "minus" | "parens"; /** Currency symbol (default: none). */ currency?: string; /** Whether the currency symbol is prepended (default: true). */ currencyPrepend?: boolean; } /** * Format a number according to the given options. * * @param value The number to format. * @param options Formatting options. * @returns The formatted string. */ declare function formatNumber(value: number, options?: NumberFormatOptions): string; /** * Create an Acrobat-compatible number formatting function. * * Returns a function that takes a raw value string and returns the * formatted display string. * * @param nDec Number of decimal places. * @param sepStyle Separator style (0–3). See table above. * @param negStyle Negative style: 0=minus, 1=red (treated as minus), * 2=parens, 3=red+parens (treated as parens). * @param currStyle Currency style (legacy, not used). * @param strCurrency Currency symbol string. * @param bCurrencyPrepend `true` to prepend the currency symbol. * @returns A formatting function `(value: string) => string`. */ declare function AFNumber_Format(nDec: number, sepStyle: number, negStyle: number, currStyle: number, strCurrency: string, bCurrencyPrepend: boolean): (value: string) => string; //#endregion //#region src/form/acrobatDateBuiltins.d.ts /** * Format a `Date` object using an Acrobat-compatible format string. * * @param date The Date to format. * @param format The Acrobat format string. * @returns The formatted date string. */ declare function formatDate$1(date: Date, format: string): string; /** * Parse a date string using an Acrobat-compatible format string. * * Attempts to extract date components (year, month, day, hour, minute, * second) from the input text based on the format pattern. * * @param text The date string to parse. * @param format The Acrobat format string. * @returns A `Date` object, or `null` if parsing fails. */ declare function parseAcrobatDate(text: string, format: string): Date | null; /** * Create an Acrobat-compatible date formatting function. * * The returned function takes a raw date string (which may be in * various formats) and returns it formatted according to the given * Acrobat format pattern. * * @param format The Acrobat date format string (e.g. `"mm/dd/yyyy"`). * @returns A formatting function `(value: string) => string`. */ declare function AFDate_FormatEx(format: string): (value: string) => string; //#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): 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. */ override 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; }): 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; override 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; override 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; override 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; override 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; override 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; override 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; override 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; override 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/parser/textSearch.d.ts /** A rectangle in user-space (PDF) coordinates. */ interface SearchRect { readonly x: number; readonly y: number; readonly width: number; readonly height: number; } /** A single search match and the page rectangles it covers. */ interface TextMatch { /** The matched substring. */ readonly text: string; /** Character offset of the match within the joined search text. */ readonly index: number; /** One hit-rectangle per text item the match spans. */ readonly rects: readonly SearchRect[]; } /** Options for {@link searchTextItems}. */ interface SearchOptions { /** Match case exactly. Default: `false` (case-insensitive). */ readonly caseSensitive?: boolean | undefined; /** Only match whole words (`\b` boundaries). Ignored for RegExp queries. Default: `false`. */ readonly wholeWord?: boolean | undefined; } /** * Search positioned text items for a string or RegExp, returning each match * with its page-coordinate hit-rectangles. * * Items are joined with a single space (the natural inter-run separator); * matches that span items yield one rectangle per item touched. * * @param items - Positioned text items from `extractTextWithPositions`. * @param query - A literal string or a `RegExp` to search for. * @param options - Case-sensitivity / whole-word options (string queries). * @returns The matches in document order. */ declare function searchTextItems(items: readonly TextItem$1[], query: string | RegExp, options?: SearchOptions): TextMatch[]; //#endregion //#region src/parser/jpeg2000Decode.d.ts /** * @module parser/jpeg2000Decode * * JPEG2000 (JPX / JP2) stream decoder for the PDF JPXDecode filter. * * JPEG2000 (ITU-T T.800 / ISO/IEC 15444-1) is a wavelet-based image * compression standard that supports both lossy and lossless coding. * This module implements a pure-JS decoder covering: * * - JP2 file format box parsing (signature, file type, header, codestream) * - J2K codestream marker parsing (SOC, SIZ, COD, QCD, SOT, SOD, EOC) * - Tier-2 decoding (packet headers, code-block inclusion trees) * - Tier-1 decoding (MQ arithmetic coder for code-block bit-planes) * - DWT: 5/3 reversible (lossless) and 9/7 irreversible (lossy) * - Color transforms: ICT (lossy) and RCT (lossless) * - JP2 color specification box parsing (sRGB, greyscale, sYCC, ICC) * - Channel definition box parsing for alpha channel identification * - Multi-resolution decoding via reduceResolution parameter * * Focus: single-tile images (most common in PDFs), 8-bit and 16-bit * component depths, both lossy and lossless modes. * * Reference: PDF 1.7 spec, SS7.4.9; ITU-T T.800; ISO/IEC 15444-1. * * @packageDocumentation */ /** * Color space type for a decoded JPEG2000 image. */ type Jpeg2000ColorSpace = "srgb" | "greyscale" | "sycc" | "icc"; /** * Decoded JPEG2000 image data. */ interface Jpeg2000Image { /** Image width in pixels. */ width: number; /** Image height in pixels. */ height: number; /** Number of color components. */ components: number; /** Bits per component (typically 8 or 16). */ bitsPerComponent: number; /** Raw decoded pixel data (interleaved components). */ data: Uint8Array; /** Detected color space (from JP2 boxes or codestream). */ colorSpace?: Jpeg2000ColorSpace; /** Embedded ICC profile bytes (from JP2 colr box). */ iccProfile?: Uint8Array; } /** * Parameters controlling JPEG2000 decoding behavior. */ interface Jpeg2000DecodeParams { /** * Number of highest resolution levels to skip. * 0 = full resolution, 1 = half, 2 = quarter, etc. */ reduceResolution?: number; /** Maximum number of components to decode. */ maxComponents?: number; } /** * Decode a JPEG2000 (JP2 or raw J2K codestream) image. * * @param data - JP2 file bytes or raw J2K codestream bytes. * @param params - Optional decode parameters. * @returns Decoded image with raw pixel data. */ declare function decodeJpeg2000(data: Uint8Array, params?: Jpeg2000DecodeParams): Jpeg2000Image; //#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, mdpPermission?: number, fieldLock?: { action: "All" | "Include" | "Exclude"; fields?: string[] | 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 /** * 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"; /** * RSA signature scheme. Default `'pkcs1v15'` (RSASSA-PKCS1-v1_5, * byte-identical to prior behaviour). Set `'pss'` to use RSASSA-PSS * (RFC 4055) with MGF1 over the same hash and a salt length equal to * the hash output length. Ignored for ECDSA keys. */ signatureScheme?: "pkcs1v15" | "pss" | undefined; } /** * Options for building a signature. */ interface SignatureOptions { signerInfo: SignerInfo; reason?: string | undefined; location?: string | undefined; contactInfo?: string | undefined; signingDate?: Date | undefined; /** * When `true`, include the ESS `signing-certificate-v2` signed * attribute (RFC 5035), upgrading the signature to the CAdES-BES / * PAdES-B-B baseline. Default `false` ⇒ byte-identical to prior output. */ cades?: boolean | 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 /** * 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/ocsp.d.ts /** * Result of an OCSP certificate status check. */ interface OcspResult$1 { /** Certificate status. */ status: "good" | "revoked" | "unknown"; /** Beginning of validity interval. */ thisUpdate: Date; /** End of validity interval (if present). */ nextUpdate?: Date | undefined; /** When the certificate was revoked (if revoked). */ revokedAt?: Date | undefined; /** Revocation reason string (if revoked). */ revocationReason?: string | undefined; } /** * Extract the OCSP responder URL from a certificate's Authority * Information Access (AIA) extension. * * The AIA extension (OID 1.3.6.1.5.5.7.1.1) contains: * ``` * AuthorityInfoAccessSyntax ::= SEQUENCE OF AccessDescription * AccessDescription ::= SEQUENCE { * accessMethod OID, * accessLocation GeneralName * } * ``` * * We look for accessMethod = id-ad-ocsp (1.3.6.1.5.5.7.48.1) and * extract the URI from the GeneralName (tag [6] uniformResourceIdentifier). * * @param cert DER-encoded X.509 certificate. * @returns The OCSP responder URL, or `null` if not found. */ declare function extractOcspUrl(cert: Uint8Array): string | null; /** * Check the revocation status of a certificate using OCSP. * * Builds an OCSP request, sends it to the specified OCSP responder * URL via HTTP POST (using `fetch()`), and parses the response. * * @param cert DER-encoded certificate to check. * @param issuerCert DER-encoded issuer certificate. * @param ocspUrl URL of the OCSP responder. * @returns The OCSP status result. */ declare function checkCertificateStatus(cert: Uint8Array, issuerCert: Uint8Array, ocspUrl: string): Promise; //#endregion //#region src/signature/crl.d.ts /** * A single revoked certificate entry in a CRL. */ interface CrlEntry { /** Serial number of the revoked certificate (hex-encoded). */ serialNumber: string; /** Date when the certificate was revoked. */ revocationDate: Date; /** CRL reason code string (if present). */ reason?: string | undefined; } /** * Parsed CRL data. */ interface CrlData$1 { /** Issuer distinguished name (hex-encoded DER bytes). */ issuer: string; /** Date this CRL was issued. */ thisUpdate: Date; /** Date the next CRL will be issued (if present). */ nextUpdate?: Date | undefined; /** List of revoked certificate entries. */ entries: CrlEntry[]; } /** * Download and parse a CRL from a URL. * * Uses `fetch()` to retrieve the CRL and then parses it as DER. * If the response is PEM-encoded, it is automatically converted to DER. * * @param url URL of the CRL (typically an HTTP URL from CRL Distribution Points). * @returns Parsed CRL data. */ declare function downloadCrl(url: string): Promise; /** * Check if a certificate's serial number appears in a CRL. * * Compares the certificate's serial number against all entries * in the CRL's revoked certificates list. * * @param cert DER-encoded X.509 certificate to check. * @param crl Parsed CRL data. * @returns `true` if the certificate is listed as revoked. */ declare function isCertificateRevoked(cert: Uint8Array, crl: CrlData$1): boolean; /** * Extract CRL Distribution Points URLs from a certificate. * * Looks for the CRL Distribution Points extension (OID 2.5.29.31) * and extracts HTTP/LDAP URIs from the DistributionPoint structures. * * ``` * CRLDistributionPoints ::= SEQUENCE OF DistributionPoint * DistributionPoint ::= SEQUENCE { * distributionPoint [0] DistributionPointName OPTIONAL, * reasons [1] ReasonFlags OPTIONAL, * cRLIssuer [2] GeneralNames OPTIONAL * } * DistributionPointName ::= CHOICE { * fullName [0] GeneralNames, * nameRelativeToCRLIssuer [1] RelativeDistinguishedName * } * ``` * * @param cert DER-encoded X.509 certificate. * @returns Array of CRL URLs found in the certificate. */ declare function extractCrlUrls(cert: Uint8Array): string[]; //#endregion //#region src/signature/chainValidator.d.ts /** * Options for certificate chain validation. */ interface ChainValidationOptions { /** Trusted root certificates (DER-encoded). If empty, self-signed roots are trusted. */ trustedCerts?: Uint8Array[] | undefined; /** Whether to check certificate revocation via OCSP/CRL. Default: false. */ checkRevocation?: boolean | undefined; /** The point in time for validity checking. Default: current time. */ validationTime?: Date | undefined; } /** * Validation status for a single certificate in the chain. */ interface CertificateStatus { /** Subject Common Name of the certificate. */ subject: string; /** Issuer Common Name of the certificate. */ issuer: string; /** Serial number (hex-encoded). */ serialNumber: string; /** Whether the certificate is valid at the validation time. */ withinValidityPeriod: boolean; /** Whether the issuer's signature on this certificate is valid. */ signatureValid: boolean; /** Whether basic constraints are satisfied (CA flag for non-leaf certs). */ basicConstraintsValid: boolean; /** Certificate validity start. */ notBefore: Date; /** Certificate validity end. */ notAfter: Date; /** Error messages (if any). */ errors: string[]; } /** * Result of building a certificate chain. */ interface CertificateChainResult { /** The ordered chain from leaf to root. */ chain: Uint8Array[]; /** Whether a complete chain to a root/trusted cert was found. */ complete: boolean; } /** * Result of validating a certificate chain. */ interface ChainValidationResult { /** Overall validity of the chain. */ valid: boolean; /** Per-certificate validation status (leaf to root order). */ certificates: CertificateStatus[]; /** Summary error messages. */ errors: string[]; } /** * Build a certificate chain from a leaf certificate to a root. * * Starting from the leaf, finds the issuer among the provided * intermediate certificates, repeating until a self-signed root * is found or no matching issuer exists. * * @param leaf DER-encoded leaf certificate. * @param intermediates DER-encoded intermediate certificates. * @returns The ordered chain (leaf first, root last) and * whether it is complete. */ declare function buildCertificateChain(leaf: Uint8Array, intermediates: Uint8Array[]): CertificateChainResult; /** * Validate a certificate chain. * * Checks each certificate in the chain for: * 1. **Signature verification** — the issuer's public key verifies * the signature on the subject certificate. * 2. **Validity period** — the certificate is within its notBefore * and notAfter dates at the validation time. * 3. **Basic constraints** — intermediate/root certificates have * the CA flag set in the BasicConstraints extension. * * @param chain Ordered array of DER-encoded certificates (leaf first, root last). * @param options Validation options. * @returns Validation result with per-certificate status. */ declare function validateCertificateChain(chain: Uint8Array[], options?: ChainValidationOptions): Promise; //#endregion //#region src/signature/offlineRevocation.d.ts /** * Embedded revocation data extracted from a PKCS#7 signature. * * Contains arrays of raw DER-encoded OCSP responses and CRLs * that were embedded in the signature's signed or unsigned attributes. */ interface EmbeddedRevocationData { /** DER-encoded OCSP responses. */ ocsps: Uint8Array[]; /** DER-encoded CRLs. */ crls: Uint8Array[]; } /** * Result of an offline revocation check. */ interface OfflineRevocationResult { /** Whether a revocation check was actually performed. */ checked: boolean; /** Certificate status: good, revoked, unknown, or no-data. */ status: "good" | "revoked" | "unknown" | "no-data"; /** Source of the revocation information used. */ source: "ocsp" | "crl" | "none"; /** Human-readable details about the check. */ details?: string | undefined; } /** * Extract embedded revocation data (CRLs and OCSP responses) from * a DER-encoded PKCS#7/CMS signature. * * Searches both signed and unsigned attributes for: * - adbe-revocationInfoArchival (OID 1.2.840.113583.1.1.8) * - id-smime-aa-ets-revocationRefs / revocationValues * * @param signatureBytes DER-encoded PKCS#7 signature bytes. * @returns Extracted CRLs and OCSP responses. */ declare function extractEmbeddedRevocationData(signatureBytes: Uint8Array): EmbeddedRevocationData; /** * Verify the revocation status of a certificate using only * embedded revocation data (no network access). * * Checks OCSP responses first (preferred), then falls back to CRLs. * If no embedded revocation data covers the certificate, returns * status 'no-data'. * * @param cert DER-encoded X.509 certificate to check. * @param revocationData Embedded revocation data from `extractEmbeddedRevocationData`. * @returns Revocation check result. */ declare function verifyOfflineRevocation(cert: Uint8Array, revocationData: EmbeddedRevocationData): OfflineRevocationResult; //#endregion //#region src/signature/trustStore.d.ts /** * Options for creating a TrustStore. */ interface TrustStoreOptions { /** Initial set of trusted root certificates (DER-encoded). */ certificates?: Uint8Array[] | undefined; } /** * A custom trust store for managing trusted root CA certificates. * * Certificates are stored in a Map keyed by a SHA-256 hash of their * DER-encoded subject Name, enabling O(1) issuer lookups. * * @example * ```ts * import { TrustStore } from 'modern-pdf-lib'; * * const store = new TrustStore(); * store.addCertificate(rootCaDer); * * if (store.isTrusted(someCert)) { * console.log('Certificate is a trusted root'); * } * * const issuer = store.findIssuer(leafCert); * if (issuer) { * console.log('Found issuer in trust store'); * } * ``` */ declare class TrustStore { /** * Internal storage: subject-hash -> array of StoredCert. * Multiple certificates may share the same subject (e.g. re-issued CAs). */ private readonly _certs; /** Total number of certificates in the store. */ private _size; /** * Pending initialization promise (for constructor certificates). * Methods await this before operating on the store. */ private _ready; /** * Create a new TrustStore, optionally pre-populated with certificates. * * @param options Optional configuration including initial certificates. */ constructor(options?: TrustStoreOptions); /** * Add a trusted root certificate to the store. * * @param cert DER-encoded X.509 certificate. */ addCertificate(cert: Uint8Array): Promise; /** * Add multiple trusted root certificates to the store. * * @param certs Array of DER-encoded X.509 certificates. */ addCertificates(certs: Uint8Array[]): Promise; /** * Remove a certificate from the store by its serial number. * * @param serialNumber The DER-encoded INTEGER serial number * (raw bytes, without ASN.1 tag/length). * @returns `true` if a certificate was removed. */ removeCertificate(serialNumber: Uint8Array): Promise; /** * Check if a certificate is in the trust store (exact DER match). * * @param cert DER-encoded X.509 certificate. * @returns `true` if the certificate is trusted. */ isTrusted(cert: Uint8Array): Promise; /** * Find the issuer certificate for the given certificate. * * Looks up the certificate's issuer Name in the store (by subject hash) * and returns the first matching trusted certificate, or `null` if * no issuer is found. * * @param cert DER-encoded X.509 certificate whose issuer to find. * @returns The DER-encoded issuer certificate, or `null`. */ findIssuer(cert: Uint8Array): Promise; /** * Get all certificates in the trust store. * * @returns Array of DER-encoded X.509 certificates. */ getAllCertificates(): Promise; /** * The number of certificates in the trust store. */ get size(): number; /** * Remove all certificates from the trust store. */ clear(): Promise; /** * Add a single certificate to the store. */ private _addOne; /** * Add multiple certificates. */ private _addMany; } //#endregion //#region src/signature/certPolicy.d.ts /** * Key usage flags defined in RFC 5280 Section 4.2.1.3. * * The KeyUsage extension is a BIT STRING where each bit * corresponds to a specific usage: * - bit 0: digitalSignature * - bit 1: nonRepudiation (contentCommitment) * - bit 2: keyEncipherment * - bit 3: dataEncipherment * - bit 4: keyAgreement * - bit 5: keyCertSign * - bit 6: cRLSign */ type KeyUsageFlag = "digitalSignature" | "nonRepudiation" | "keyEncipherment" | "dataEncipherment" | "keyAgreement" | "keyCertSign" | "crlSign"; /** * Result of validating key usage flags. */ interface KeyUsageValidationResult { /** Whether all required key usage flags are present. */ valid: boolean; /** Key usage flags that are present in the certificate. */ presentFlags: KeyUsageFlag[]; /** Required key usage flags that are missing. */ missingFlags: KeyUsageFlag[]; } /** * Result of validating extended key usage. */ interface EkuValidationResult { /** Whether all required EKU OIDs are present. */ valid: boolean; /** EKU OIDs present in the certificate. */ presentOids: string[]; /** Required EKU OIDs that are missing. */ missingOids: string[]; } /** * Options for comprehensive policy validation. */ interface PolicyValidationOptions { /** Require the digitalSignature key usage flag. Default: true. */ requireDigitalSignature?: boolean | undefined; /** Require the nonRepudiation key usage flag. Default: false. */ requireNonRepudiation?: boolean | undefined; /** Allow expired certificates. Default: false. */ allowExpired?: boolean | undefined; } /** * Comprehensive certificate policy validation result. */ interface PolicyValidationResult { /** Whether the certificate passes all policy checks. */ valid: boolean; /** Key usage validation result. */ keyUsage: KeyUsageValidationResult; /** Extended key usage validation result (if EKU extension present). */ extendedKeyUsage?: EkuValidationResult | undefined; /** Validity period check. */ validityPeriod: { /** Whether the current time is within the certificate's validity period. */valid: boolean; /** Certificate validity start date. */ notBefore: Date; /** Certificate validity end date. */ notAfter: Date; }; /** Whether the certificate is a CA (from Basic Constraints). */ isCA: boolean; /** Non-fatal warnings. */ warnings: string[]; } /** * Well-known Extended Key Usage OIDs. */ declare const EKU_OIDS: { /** id-kp-serverAuth (TLS server) */readonly serverAuth: "1.3.6.1.5.5.7.3.1"; /** id-kp-clientAuth (TLS client) */ readonly clientAuth: "1.3.6.1.5.5.7.3.2"; /** id-kp-codeSigning */ readonly codeSigning: "1.3.6.1.5.5.7.3.3"; /** id-kp-emailProtection (S/MIME) */ readonly emailProtection: "1.3.6.1.5.5.7.3.4"; /** id-kp-timeStamping (RFC 3161 TSA) */ readonly timeStamping: "1.3.6.1.5.5.7.3.8"; /** id-kp-OCSPSigning (OCSP responder) */ readonly ocspSigning: "1.3.6.1.5.5.7.3.9"; /** Adobe authentic document (PDF signing) */ readonly adobeAuthenticDocument: "1.2.840.113583.1.1.5"; /** Microsoft document signing */ readonly msDocumentSigning: "1.3.6.1.4.1.311.10.3.12"; /** anyExtendedKeyUsage */ readonly anyExtendedKeyUsage: "2.5.29.37.0"; }; /** * Validate that a certificate has the required key usage flags. * * Parses the Key Usage extension (OID 2.5.29.15) from the certificate * and checks that all required flags are present. * * If the certificate has no Key Usage extension, the result is * `valid: true` with empty presentFlags (per RFC 5280, the absence * of the extension means all usages are permitted). * * @param cert DER-encoded X.509 certificate. * @param requiredUsage Array of required key usage flags. * @returns Validation result. */ declare function validateKeyUsage(cert: Uint8Array, requiredUsage: KeyUsageFlag[]): KeyUsageValidationResult; /** * Validate that a certificate has the required extended key usage OIDs. * * Parses the Extended Key Usage extension (OID 2.5.29.37) and checks * that all required EKU OIDs are present. * * If the certificate has no EKU extension, the result is `valid: true` * (per RFC 5280, absence means all extended usages are permitted). * * The anyExtendedKeyUsage OID (2.5.29.37.0) satisfies all requirements. * * @param cert DER-encoded X.509 certificate. * @param requiredEku Array of required EKU OIDs (dotted-decimal). * @returns Validation result. */ declare function validateExtendedKeyUsage(cert: Uint8Array, requiredEku: string[]): EkuValidationResult; /** * Perform comprehensive certificate policy validation. * * Checks: * 1. Key usage flags (digitalSignature and/or nonRepudiation) * 2. Extended key usage (if present) * 3. Validity period (notBefore/notAfter) * 4. Basic Constraints (CA flag) * * @param cert DER-encoded X.509 certificate. * @param options Validation options. * @returns Comprehensive validation result. */ declare function validateCertificatePolicy(cert: Uint8Array, options?: PolicyValidationOptions): PolicyValidationResult; //#endregion //#region src/signature/revocationCache.d.ts /** * @module signature/revocationCache * * Revocation response caching for OCSP and CRL data. * * Provides a time-bounded in-memory cache to avoid redundant network * requests when checking certificate revocation status. Cache keys * are derived using FNV-1a hashing of certificate serial numbers and * issuer identifiers. * * @packageDocumentation */ /** * OCSP revocation status result. */ interface OcspResult { /** Certificate status. */ status: "good" | "revoked" | "unknown"; /** When this status information was produced. */ thisUpdate: Date; /** When next status update is expected. */ nextUpdate?: Date | undefined; /** If revoked, the revocation date. */ revokedAt?: Date | undefined; /** If revoked, the reason string. */ revocationReason?: string | undefined; } /** * CRL revocation list data. */ interface CrlData { /** CRL issuer distinguished name. */ issuer: string; /** When this CRL was issued. */ thisUpdate: Date; /** When the next CRL is expected. */ nextUpdate?: Date | undefined; /** Revoked certificate entries. */ entries: Array<{ serialNumber: Uint8Array; revocationDate: Date; reason?: string | undefined; }>; } /** * Cached OCSP response entry. */ interface OcspCacheEntry { /** The OCSP result. */ result: OcspResult; /** Timestamp when this entry was cached (ms since epoch). */ cachedAt: number; /** Timestamp when this entry expires (ms since epoch). */ expiresAt: number; } /** * Cached CRL data entry. */ interface CrlCacheEntry { /** The CRL data. */ data: CrlData; /** Timestamp when this entry was cached (ms since epoch). */ cachedAt: number; /** Timestamp when this entry expires (ms since epoch). */ expiresAt: number; } /** * Configuration options for the revocation cache. */ interface RevocationCacheOptions { /** Cache entry time-to-live in milliseconds. Default: 300000 (5 minutes). */ ttlMs?: number | undefined; /** Maximum number of entries before eviction. Default: 1000. */ maxEntries?: number | undefined; } /** * In-memory cache for OCSP and CRL revocation responses. * * Entries expire after a configurable TTL (default 5 minutes). When * the cache exceeds `maxEntries`, the oldest entries are evicted. * * @example * ```ts * const cache = new RevocationCache({ ttlMs: 10 * 60 * 1000 }); // 10 min * cache.cacheOcsp('abc123', { * result: { status: 'good', thisUpdate: new Date() }, * cachedAt: Date.now(), * expiresAt: Date.now() + 600_000, * }); * const entry = cache.getCachedOcsp('abc123'); * ``` */ declare class RevocationCache { private readonly _ttlMs; private readonly _maxEntries; private readonly _ocspMap; private readonly _crlMap; /** * Create a new revocation cache. * * @param options Cache configuration. */ constructor(options?: RevocationCacheOptions); /** * Retrieve a cached OCSP response by certificate identifier. * * Returns `null` if no entry exists or the entry has expired. * * @param certId The cache key (typically from `deriveCacheKey`). * @returns The cached entry, or `null`. */ getCachedOcsp(certId: string): OcspCacheEntry | null; /** * Store an OCSP response in the cache. * * If `expiresAt` is not set on the entry, it will be computed from * the configured TTL. * * @param certId The cache key. * @param entry The OCSP cache entry to store. */ cacheOcsp(certId: string, entry: OcspCacheEntry): void; /** * Retrieve a cached CRL by URL. * * Returns `null` if no entry exists or the entry has expired. * * @param url The CRL distribution point URL. * @returns The cached entry, or `null`. */ getCachedCrl(url: string): CrlCacheEntry | null; /** * Store a CRL in the cache. * * If `expiresAt` is not set on the entry, it will be computed from * the configured TTL. * * @param url The CRL distribution point URL. * @param entry The CRL cache entry to store. */ cacheCrl(url: string, entry: CrlCacheEntry): void; /** * Remove all expired entries from both OCSP and CRL caches. * * @returns The number of entries removed. */ clearExpired(): number; /** * Remove all entries from both caches. */ clear(): void; /** * Total number of entries across both OCSP and CRL caches. */ get size(): number; /** * Evict oldest entries when the total count exceeds `maxEntries`. * * Uses the `cachedAt` timestamp to determine eviction order. * @internal */ private _evictIfNeeded; } //#endregion //#region src/signature/detailedVerifier.d.ts /** * Information about a single certificate in a chain. */ interface CertificateInfo { /** Subject distinguished name (CN). */ subject: string; /** Issuer distinguished name (CN). */ issuer: string; /** Certificate validity start date. */ validFrom: Date; /** Certificate validity end date. */ validTo: Date; /** Certificate serial number as hex string. */ serialNumber: string; /** Key usage extensions, if present. */ keyUsage?: string[] | undefined; /** Whether this is a CA certificate. */ isCA?: boolean | undefined; } /** * Detailed result from verifying a single PDF signature. */ interface DetailedVerificationResult { /** The signature field name. */ fieldName: string; /** Subject CN of the signing certificate. */ signedBy: string; /** Overall validity (all checks passed). */ valid: boolean; /** Whether the ByteRange hash matches the signed hash. */ integrityValid: boolean; /** Whether the cryptographic signature is valid. */ cryptoValid: boolean; /** Certificate chain from signer to root. */ chain: CertificateInfo[]; /** Whether revocation status was checked. */ revocationChecked: boolean; /** Revocation status of the signing certificate. */ revocationStatus: "good" | "revoked" | "unknown" | "unchecked"; /** OCSP response details, if available. */ ocspResponse?: { status: string; thisUpdate: Date; nextUpdate?: Date; } | undefined; /** Whether CRL was checked. */ crlChecked: boolean; /** Timestamp information, if present. */ timestamp?: { time: Date; valid: boolean; } | undefined; /** Non-fatal warnings about the signature. */ warnings: string[]; /** Fatal errors encountered during verification. */ errors: string[]; } /** * Options for detailed signature verification. */ interface DetailedVerifyOptions { /** Whether to check certificate revocation status. Default: false. */ checkRevocation?: boolean | undefined; /** Trusted root certificates (DER-encoded) for chain validation. */ trustedCerts?: Uint8Array[] | undefined; /** Revocation cache for OCSP/CRL responses. */ revocationCache?: RevocationCache | undefined; /** Timeout in milliseconds for network operations. Default: 10000. */ timeout?: number | undefined; } /** * Verify all signatures in a PDF with detailed, structured results. * * For each signature found, returns comprehensive information about: * - Integrity verification (ByteRange hash) * - Cryptographic signature validity * - Certificate chain (all certificates in the PKCS#7 structure) * - Revocation status (if `checkRevocation` is enabled) * - Timestamp information * - Diagnostic warnings and errors * * @param pdf The PDF file bytes. * @param options Verification options. * @returns Array of detailed verification results. * * @example * ```ts * const results = await verifySignatureDetailed(pdfBytes, { * checkRevocation: true, * }); * for (const result of results) { * console.log(`${result.fieldName}: ${result.valid ? 'VALID' : 'INVALID'}`); * if (result.warnings.length > 0) { * console.log('Warnings:', result.warnings); * } * } * ``` */ declare function verifySignatureDetailed(pdf: Uint8Array, options?: DetailedVerifyOptions): 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 /** * 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 /** * 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): Promise; //#endregion //#region src/signature/counterSignature.d.ts /** * 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 /** * 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): 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. * * Two-pass serialization ensures all byte offsets in hint tables, * cross-reference streams, and the linearization parameter dictionary * are exact — not placeholders or approximations. * * 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) * * Uses two-pass serialization: * - Pass 1 produces a trial layout to determine exact byte sizes. * - Pass 2 re-serializes with the correct values, so all offsets * (/L, /O, /E, /T, /H, hint table entries, xref entries) are exact. * * @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 /** 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 /** * 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 /** * 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/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/compliance/pdfxCompliance.d.ts /** PDF/X conformance level. */ type PdfXLevel = "X-1a:2003" | "X-3:2003" | "X-4"; /** Result of a PDF/X validation check. */ interface PdfXValidationResult { valid: boolean; level: PdfXLevel; errors: PdfXIssue[]; warnings: PdfXIssue[]; } /** A single PDF/X compliance issue. */ interface PdfXIssue { code: string; message: string; clause?: string; } /** Options for PDF/X enforcement. */ interface PdfXOptions { level: PdfXLevel; outputIntent: OutputIntentConfig; trapped?: "True" | "False" | "Unknown"; } /** Configuration for an output intent. */ interface OutputIntentConfig { /** Output condition identifier, e.g. "CGATS TR 001". */ condition: string; /** Registry URL, e.g. "http://www.color.org". */ registryName?: string; /** ICC profile bytes. */ iccProfile?: Uint8Array; /** Human-readable description. */ info?: string; } /** * Validate a PDF against a specific PDF/X conformance level. * * Performs structural checks on the raw PDF bytes for: * - Output intent presence and subtype * - /Trapped key in Info dictionary * - Transparency restrictions (X-1a, X-3) * - Color space restrictions (X-1a: CMYK/Gray only) * - Font embedding * - No encryption * - TrimBox or BleedBox on every page * - No JavaScript or multimedia * - Page box nesting (MediaBox >= BleedBox >= TrimBox >= ArtBox) * - PDF version requirements (X-4 requires 1.6+) * * @param pdfBytes The raw PDF bytes. * @param level The target PDF/X conformance level. * @returns A validation result with errors and warnings. */ declare function validatePdfX(pdfBytes: Uint8Array, level: PdfXLevel): PdfXValidationResult; /** * Attempt to make a PDF conform to a PDF/X level. * * This adds or corrects: * - Output intent with the specified configuration * - /Trapped key in the Info dictionary * - TrimBox = CropBox (or MediaBox) if missing * - Flattens transparency for X-1a and X-3 * * **Limitations:** * - Cannot convert RGB to CMYK (for X-1a — validation will still fail) * - Cannot embed fonts that are not already embedded * - Cannot remove encryption (throws an error) * - Cannot remove JavaScript (throws an error) * * @param pdfBytes The raw PDF bytes. * @param options PDF/X enforcement options. * @returns The modified PDF bytes. */ declare function enforcePdfX(pdfBytes: Uint8Array, options: PdfXOptions): Uint8Array; /** * Build a PDF/X output intent dictionary. * * Creates the /OutputIntent dictionary and ICC profile stream * for use in the catalog's /OutputIntents array. * * @param registry The PDF object registry to register objects into. * @param config The output intent configuration. * @returns An indirect reference to the OutputIntent dictionary. */ declare function buildPdfXOutputIntent(registry: PdfObjectRegistry, config: OutputIntentConfig): PdfRef; //#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[]; } /** Horizontal alignment for overlay text. */ type OverlayAlignment = "left" | "center" | "right"; /** Extended options for building redaction operators. */ interface RedactionOperatorOptions { /** Font name for overlay text (default: 'Helvetica'). */ overlayFont?: string | undefined; /** Font size for overlay text. When omitted, auto-calculated from rect height. */ overlayFontSize?: number | undefined; /** Horizontal alignment for overlay text (default: 'left'). */ overlayAlignment?: OverlayAlignment | undefined; /** Border width for the redaction rectangle outline (default: 0). */ borderWidth?: number | undefined; /** Border colour (default: same as fill colour). */ borderColor?: { r: number; g: number; b: number; } | undefined; /** Opacity for the redaction overlay, 0–1 (default: 1). */ opacity?: number | undefined; } /** * 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 /** * 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): 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): 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 /** * 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): 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 /** 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): TiffImage; //#endregion //#region src/wasm/loader.d.ts /** 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/layout/headerFooter.d.ts type HeaderFooterPosition = "left" | "center" | "right"; interface HeaderFooterContent { /** Static text or template string with variables: {page}, {pages}, {date}, {title} */ text: string; position: HeaderFooterPosition; font?: FontRef | string; fontSize?: number; color?: Color; bold?: boolean; italic?: boolean; } interface HeaderFooterOptions { header?: HeaderFooterContent[]; footer?: HeaderFooterContent[]; /** Margins from page edge in points. Default: { top: 36, bottom: 36, left: 50, right: 50 } */ margins?: { top?: number; bottom?: number; left?: number; right?: number; }; /** Skip first page (e.g. for title page). Default: false */ skipFirstPage?: boolean; /** Page range to apply to. Default: all pages. */ pageRange?: { start?: number; end?: number; }; /** Separator line between header/footer and content. */ separatorLine?: { width?: number; color?: Color; dashPattern?: number[]; }; /** Date format string. Default: 'YYYY-MM-DD' */ dateFormat?: string; } /** Convert an integer to a lowercase Roman numeral string. */ declare function toRoman(num: number): string; /** Convert an integer to a lowercase alphabetic string (1=a, 2=b, ..., 27=aa). */ declare function toAlpha(num: number): string; /** Format a Date according to a simple format string. */ declare function formatDate(date: Date, format: string): string; /** Replace template variables in a text string. */ declare function replaceTemplateVariables(text: string, pageNumber: number, totalPages: number, date: Date, dateFormat: string, title: string): string; /** * Apply header/footer to a single page. * * @param page The page to draw on. * @param options Header/footer configuration. * @param pageNumber 1-based page number. * @param totalPages Total page count in the document. * @param title Optional document title for `{title}` replacement. */ declare function applyHeaderFooterToPage(page: PdfPage, options: HeaderFooterOptions, pageNumber: number, totalPages: number, title?: string): void; /** * Apply headers and footers to all pages in a document. * * Respects `skipFirstPage` and `pageRange` options. * * @param doc The PDF document. * @param options Header/footer configuration. */ declare function applyHeaderFooter(doc: PdfDocument, options: HeaderFooterOptions): void; //#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 { override 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 { override 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 { override 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 { override readonly name = "RemovePageFromEmptyDocumentError"; constructor(options?: ErrorOptions); } /** * Thrown when looking up a form field by name that does not exist. */ declare class NoSuchFieldError extends Error { override 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 { override 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 { override 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 { override 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 { override 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 { override 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 { override 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 { override 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 { override readonly name = "ExceededMaxLengthError"; constructor(textLength: number, maxLength: number, fieldName: string, options?: ErrorOptions); } /** * Thrown when an invalid page size is provided (e.g. zero or negative * dimensions, non-finite values). * * @example * ```ts * throw new InvalidPageSizeError(0, 842); * ``` */ declare class InvalidPageSizeError extends Error { override readonly name = "InvalidPageSizeError"; constructor(width: number, height: number, options?: ErrorOptions); } /** * Thrown when an invalid color value is provided (e.g. component values * outside the `[0, 1]` range, unknown color type). * * @example * ```ts * throw new InvalidColorError('RGB component out of range: r=1.5'); * ``` */ declare class InvalidColorError extends Error { override readonly name = "InvalidColorError"; constructor(message: string, options?: ErrorOptions); } /** * Thrown when a plugin encounters an error during initialization or * execution. Wraps the underlying cause for error-chain inspection. * * @example * ```ts * throw new PluginError('myPlugin', 'Failed to initialize WASM module'); * ``` */ declare class PluginError extends Error { override readonly name = "PluginError"; /** Name of the plugin that caused the error. */ readonly pluginName: string; constructor(pluginName: string, message: string, options?: ErrorOptions); } /** * Thrown when a streaming (incremental) parse operation encounters * corrupt or incomplete data that prevents further processing. * * @example * ```ts * throw new StreamingParseError('Unexpected EOF at byte offset 4096'); * ``` */ declare class StreamingParseError extends Error { override readonly name = "StreamingParseError"; /** Byte offset where the error occurred, if known. */ readonly offset?: number | undefined; constructor(message: string, offset?: number, options?: ErrorOptions); } /** * Thrown when a batch processing operation fails. Contains information * about which items succeeded and which failed. * * @example * ```ts * throw new BatchProcessingError('2 of 5 documents failed', failures); * ``` */ declare class BatchProcessingError extends Error { override readonly name = "BatchProcessingError"; /** Details of individual item failures. */ readonly failures: ReadonlyArray<{ readonly index: number; readonly error: Error; }>; constructor(message: string, failures: ReadonlyArray<{ readonly index: number; readonly error: Error; }>, 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; /** * If `true`, use /RV rich text value when available instead of /V. * Rich text (/RV) is an XHTML string containing formatting such as * bold, italic, font-size, color, and font-family. When enabled, * the flattener parses the XHTML and generates an appearance stream * that preserves the rich text styling. If parsing fails, the * flattener falls back to the plain text /V value. * * Default: `true`. */ preserveRichText?: 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; /** Page fit mode used by this bookmark's destination. */ readonly fit?: "Fit" | "FitH" | "FitV" | "FitB" | "FitBH" | "FitBV" | "XYZ" | undefined; /** Left coordinate (for FitV, FitBV, XYZ). */ readonly left?: number | undefined; /** Zoom factor (for XYZ). */ readonly zoom?: 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, FitBH, XYZ). */ y?: number | undefined; /** Page fit mode. Default: `'Fit'` (or `'FitH'` when only `y` is set). */ fit?: "Fit" | "FitH" | "FitV" | "FitB" | "FitBH" | "FitBV" | "XYZ" | undefined; /** Left coordinate (for FitV, FitBV, XYZ). */ left?: number | undefined; /** Zoom factor (for XYZ). 0 = keep current zoom. */ zoom?: 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; /** Strategy for handling errors during batch processing. */ type BatchErrorStrategy = "fail-fast" | "continue" | "collect"; /** 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; /** Maximum memory usage in MB before throttling concurrency. */ maxMemoryMB?: number | undefined; /** * Error handling strategy: * - `'fail-fast'` — stop on first error and reject immediately * - `'continue'` — skip failed items and continue (default) * - `'collect'` — collect all errors and throw an `AggregateError` at the end */ errorStrategy?: BatchErrorStrategy | undefined; /** Per-item timeout in milliseconds. Items exceeding this are treated as errors. */ timeout?: number | 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, progress, memory, error, and timeout 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 * with **lazy decoding** and **GC-friendly caching**. * * 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 functions that * decode 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**, base64 decoding is deferred until the module is * actually requested — no upfront cost. * - Decoded bytes are held via `WeakRef` so the GC can reclaim them * when memory pressure is high. A strong cache is also available * for performance-critical paths. * - {@link preloadInlineWasm} allows proactive decoding before first use. * - {@link getInlineWasmSize} returns the encoded size without triggering * any base64 decode. * * @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. If the strong cache has been cleared but a `WeakRef` still * holds the bytes, they are recovered without re-decoding. * * @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; /** * Get the encoded (base64) size of a WASM module **without** decoding it. * * This is useful for diagnostics, size budgeting, and bundle analysis. * The returned value is the number of characters in the base64 string; * the actual binary size is approximately `encodedSize * 3 / 4`. * * @param name The WASM module name. * @returns The base64 string length (in characters), or `0` if the * module is not available. * * @example * ```ts * const encoded = getInlineWasmSize('libdeflate'); * const binaryApprox = Math.floor(encoded * 3 / 4); * console.log(`libdeflate: ~${binaryApprox} bytes binary`); * ``` */ declare function getInlineWasmSize(name: string): number; /** * Proactively decode and cache WASM bytes for the specified modules. * * Call this during application initialization to avoid decoding latency * on the first actual use. If no names are provided, all available * modules are preloaded. * * @param names Optional list of module names to preload. Defaults to * all modules present in the generated data. * @returns The names of modules that were successfully preloaded. * * @example * ```ts * // Preload specific modules * preloadInlineWasm('libdeflate', 'png'); * * // Preload everything available * preloadInlineWasm(); * ``` */ declare function preloadInlineWasm(...names: string[]): string[]; //#endregion //#region src/core/pdfDocumentBuilder.d.ts /** * Fluent builder for creating PDF documents with a chainable API. * * Methods that don't require async return `this` for chaining. * Methods that require async operations (font/image embedding) use * a callback pattern so the builder chain can continue synchronously. * * Use {@link getDocument} as an escape hatch to access the underlying * {@link PdfDocument} directly when the builder API is insufficient. * * @example * ```ts * const bytes = await PdfDocumentBuilder.create() * .setTitle('Report') * .setAuthor('Acme Corp') * .addPage(PageSizes.A4, page => { * page.drawText('Hello, World!', { x: 50, y: 750, size: 24 }); * }) * .save(); * ``` */ declare class PdfDocumentBuilder { private readonly doc; /** Deferred async operations queued up during chaining. */ private readonly deferredOps; /** * @param doc The underlying document to wrap. Use the static * factory methods ({@link create}, {@link load}) instead. */ private constructor(); /** * Create a new, empty builder wrapping a fresh {@link PdfDocument}. * * @returns A new builder instance. */ static create(): PdfDocumentBuilder; /** * Load an existing PDF into the builder. * * @param data The PDF data as a `Uint8Array`, `ArrayBuffer`, or a * Base64-encoded string. * @param options Optional loading options (e.g. password). * @returns A promise that resolves to the builder wrapping the * loaded document. */ static load(data: Uint8Array | ArrayBuffer | string, options?: LoadPdfOptions): Promise; /** * Set the document title. * * @param title The title string. * @param options Optional display options (e.g. show in window title bar). */ setTitle(title: string, options?: SetTitleOptions): this; /** Set the document author. */ setAuthor(author: string): this; /** Set the document subject. */ setSubject(subject: string): this; /** Set the document keywords. */ setKeywords(keywords: string[]): this; /** Set the producer string. */ setProducer(producer: string): this; /** Set the creator application name. */ setCreator(creator: string): this; /** Set the document creation date. */ setCreationDate(date: Date): this; /** Set the document modification date. */ setModificationDate(date: Date): this; /** * Set the document's natural language (BCP 47 tag). * * @param lang BCP 47 language tag (e.g. `"en"`, `"en-US"`, `"de-DE"`). */ setLanguage(lang: string): this; /** * Add a page to the document. * * @param size Page size as a `[width, height]` tuple, `{ width, height }` * object, or one of the {@link PageSizes} constants. * Defaults to A4 when omitted. * @param setup Optional callback invoked with the newly created page. * Use this to draw content on the page inline. */ addPage(size?: PageSize, setup?: (page: PdfPage) => void): this; /** * Add multiple pages with the same size and optional per-page setup. * * @param count Number of pages to add. * @param size Page size (defaults to A4). * @param setup Optional callback invoked for each page with its * zero-based index within this batch. */ addPages(count: number, size?: PageSize, setup?: (page: PdfPage, index: number) => void): this; /** * Embed a font and use it in a callback. * * Because font embedding is async (for TrueType fonts), this method * defers the operation and executes it when {@link save} is called. * The callback receives the {@link FontRef} and the builder so that * further pages can reference the font. * * @param fontNameOrData Standard font name string or raw TTF/OTF bytes. * @param callback Invoked with the embedded font reference and * the builder instance for continued chaining. */ withFont(fontNameOrData: string | Uint8Array, callback: (font: FontRef, builder: PdfDocumentBuilder) => void): this; /** * Embed an image and use it in a callback. * * Because image embedding may be async (for JPEG, WebP, TIFF), this * method defers the operation and executes it when {@link save} is * called. The callback receives the {@link ImageRef} and the builder. * * @param imageData Raw image bytes (PNG, JPEG, WebP, or TIFF). * @param callback Invoked with the embedded image reference and * the builder instance. */ withImage(imageData: Uint8Array, callback: (image: ImageRef, builder: PdfDocumentBuilder) => void): this; /** * Configure encryption for this document. * * The encryption is applied when {@link save} serializes the document. * * @param options Encryption options (passwords, algorithm, permissions). */ encrypt(options: EncryptOptions): this; /** * Set page label ranges for the document. * * Page labels control how page numbers are displayed in the PDF * viewer's navigation controls and thumbnail panel. * * @param labels An array of label range definitions, sorted by * `startPage` in ascending order. */ setPageLabels(labels: PageLabelRange[]): this; /** * Add a bookmark (outline entry) to the document. * * @param options Bookmark configuration (title, page, nesting, style). * @returns The builder (for continued chaining). The * {@link BookmarkRef} is not returned — use * {@link getDocument} if you need nested bookmarks. */ addBookmark(options: AddBookmarkOptions): this; /** * Serialize the document to a `Uint8Array`. * * Executes all deferred async operations (font/image embedding, * encryption setup) before serializing. * * @param options Compression and serialization options. * @returns The complete PDF file as bytes. */ save(options?: PdfSaveOptions): Promise; /** * Escape hatch — return the underlying {@link PdfDocument}. * * Use this when you need access to APIs not exposed by the builder * (e.g. `copyPages`, `getPage`, `embedPage`, advanced outline * manipulation, etc.). * * **Note:** Deferred operations (from {@link withFont}, {@link withImage}, * {@link encrypt}) are NOT executed when calling this method. They * are only resolved when {@link save} is called. */ getDocument(): PdfDocument; } //#endregion //#region src/parser/streamingParser.d.ts /** * Options for the streaming PDF parser. */ interface StreamingParserOptions { /** Maximum bytes to buffer at once. Default: 64 MB. */ maxBufferSize?: number; /** Whether to parse content streams. Default: false. */ parseContentStreams?: boolean; /** Pages to parse (for selective loading). Default: all. */ pageRange?: { start?: number; end?: number; }; } /** * A page extracted from the streaming parse — contains structural * metadata (boxes, rotation) and the byte-range location of its * content stream within the PDF data, but *not* the content bytes * themselves. */ interface ParsedPage { /** Zero-based page index. */ index: number; /** The /MediaBox rectangle. */ mediaBox: [number, number, number, number]; /** The /CropBox rectangle (if present). */ cropBox?: [number, number, number, number]; /** Page rotation in degrees (0, 90, 180, 270). */ rotation?: number; /** Byte offset of the content stream within the PDF data. */ contentStreamOffset: number; /** Length of the content stream in bytes. */ contentStreamLength: number; /** Byte offset of the /Resources dictionary (if resolvable). */ resourcesOffset?: number; } /** * The result of a streaming parse operation. */ interface StreamingParseResult { /** PDF version string (e.g. "1.7", "2.0"). */ version: string; /** Total number of pages in the document. */ pageCount: number; /** Parsed page metadata. */ pages: ParsedPage[]; /** Document metadata from /Info dictionary. */ metadata?: Record; /** Whether the PDF is encrypted. */ isEncrypted: boolean; /** Whether the PDF is linearized (web-optimized). */ isLinearized: boolean; /** Byte offset of the cross-reference section. */ xrefOffset: number; } /** * Events emitted during streaming parsing. */ type StreamingParserEvent = { type: "header"; version: string; } | { type: "xref"; offset: number; entries: number; } | { type: "trailer"; dict: Record; } | { type: "page"; index: number; page: ParsedPage; } | { type: "object"; number: number; generation: number; offset: number; } | { type: "progress"; bytesRead: number; totalBytes: number; } | { type: "error"; message: string; offset: number; }; /** * Event handler type for streaming parser events. */ type EventHandler = (event: StreamingParserEvent) => void; /** * A streaming PDF parser that processes PDF data incrementally without * loading the entire file into memory. * * Useful for multi-GB PDFs where loading everything into memory is * impractical. * * @example * ```ts * // From a ReadableStream (e.g. fetch response) * const response = await fetch('/large.pdf'); * const result = await StreamingPdfParser.fromStream(response.body!); * console.log(`Pages: ${result.pageCount}`); * ``` * * @example * ```ts * // Chunk-by-chunk with events * const parser = new StreamingPdfParser(); * parser.on('page', (event) => { * if (event.type === 'page') console.log(`Page ${event.index}`); * }); * parser.feed(chunk1); * parser.feed(chunk2); * const result = parser.end(); * ``` */ declare class StreamingPdfParser { private readonly options; private buffer; private totalBytesRead; private readonly handlers; private version; private headerParsed; private xrefOffset; private isEncrypted; private isLinearized; private pages; private metadata; private xrefEntries; private trailerDict; private fullData; constructor(options?: StreamingParserOptions); /** * Register an event listener for a specific event type. */ on(event: StreamingParserEvent["type"], handler: EventHandler): void; private emit; /** * Feed a chunk of data to the parser. * * Chunks are buffered internally. The parser does not process data * until {@link end} is called (the PDF structure requires knowing * the full file to locate startxref). */ feed(chunk: Uint8Array): void; /** * Signal end of input and perform the full parse. * * @returns The streaming parse result. * @throws If the PDF is malformed or cannot be parsed. */ end(): StreamingParseResult; /** * Parse from a `ReadableStream`. * * Reads all chunks from the stream, then performs the structural * parse. For truly streaming random-access, the full data must be * available to seek to startxref and the xref table. */ static fromStream(stream: ReadableStream, options?: StreamingParserOptions): Promise; /** * Parse from a file path (Node.js / Deno / Bun only). * * Uses dynamic import of `node:fs` to avoid bundling issues in * browsers. Falls back to `Deno.readFile` if available. */ static fromFile(path: string, options?: StreamingParserOptions): Promise; /** * Get the raw content stream bytes for a specific page. * * Requires that the full data has been buffered (i.e. {@link end} * was called). Returns the raw (possibly compressed) bytes of the * page's content stream. * * @param pageIndex Zero-based page index. * @returns The raw content stream bytes. */ getPageContent(pageIndex: number): Promise; private parseHeader; private detectLinearization; private findStartXref; private parseXref; private parseTraditionalXref; private parseXrefStream; /** * Rebuild xref by scanning the file for "N G obj" patterns. * Used as a fallback for xref streams (which require decompression). */ private rebuildXrefFromScan; private detectEncryption; private buildPageTree; /** * Parse the dictionary of an indirect object at `offset`. * Returns the dictionary entries or undefined if parsing fails. */ private parseObjectDict; /** * Traverse the page tree recursively, collecting page metadata. */ private traversePageTree; /** * Parse the /Kids array from a /Pages node dictionary. * Returns an array of object numbers. */ private parseKidsArray; private makeEmptyPage; /** * Find the stream data (between "stream\n" and "endstream") within * an indirect object at `offset`. */ private findStreamData; private extractMetadata; } //#endregion //#region src/plugins/builtins/timestampPlugin.d.ts /** Options for the timestamp plugin. */ interface TimestampPluginOptions { /** * When `true`, set the creation date on register (if not already set). * Default: `true`. */ setCreationDate?: boolean | undefined; /** * When `true`, update the modification date before each save. * Default: `true`. */ setModificationDate?: boolean | undefined; } /** * Create a timestamp plugin instance. * * @param options Optional configuration. * @returns A {@link PdfPlugin} that manages document timestamps. */ declare function timestampPlugin(options?: TimestampPluginOptions): PdfPlugin; //#endregion //#region src/plugins/builtins/metadataPlugin.d.ts /** Options for the metadata plugin. */ interface MetadataPluginOptions { /** * Producer string to set on the document. * Default: `'modern-pdf-lib'`. */ producer?: string | undefined; /** Optional creator string (e.g. application name). */ creator?: string | undefined; /** Optional default title. Only set if the document has no title. */ defaultTitle?: string | undefined; /** Optional default author. Only set if the document has no author. */ defaultAuthor?: string | undefined; } /** * Create a metadata plugin instance. * * @param options Optional configuration. * @returns A {@link PdfPlugin} that manages document metadata. */ declare function metadataPlugin(options?: MetadataPluginOptions): PdfPlugin; //#endregion //#region src/plugins/builtins/accessibilityPlugin.d.ts /** Options for the accessibility plugin. */ interface AccessibilityPluginOptions { /** * BCP 47 language tag for the document (e.g. `'en-US'`, `'de-DE'`). * Default: `'en'`. */ language?: string | undefined; /** * When `true`, add a `/MarkInfo` dictionary with `/Marked true` * to the catalog, signaling tagged PDF. * Default: `true`. */ markAsTagged?: boolean | undefined; } /** * Create an accessibility plugin instance. * * @param options Optional configuration. * @returns A {@link PdfPlugin} that adds accessibility features. */ declare function accessibilityPlugin(options?: AccessibilityPluginOptions): PdfPlugin; //#endregion //#region src/parser/tableExtract.d.ts /** * A reconstructed table: a rectangular grid of trimmed cell strings. * Missing cells are represented by the empty string. */ interface ExtractedTable { /** The grid of rows, each row being an array of column cell strings. */ readonly rows: readonly (readonly string[])[]; } /** * Options controlling the clustering tolerances used during extraction. */ interface TableExtractOptions { /** * Maximum vertical distance (user-space units) between item baselines * for them to be considered part of the same row. * Default: roughly half the median item height. */ readonly rowTolerance?: number; /** * Maximum horizontal distance (user-space units) between item x-starts * for them to be considered part of the same column. * Default: `3`. */ readonly colTolerance?: number; } /** * Extract tables from a list of positioned text items. * * @param items - Positioned text items (e.g. from `extractTextWithPositions`). * @param options - Optional clustering tolerances. * @returns One {@link ExtractedTable} per contiguous run of >= 2 rows that * share a consistent column structure. Returns an empty array * when no table-like block is found. */ declare function extractTables(items: readonly TextItem$1[], options?: TableExtractOptions): ExtractedTable[]; /** * Serialise a table to RFC 4180 CSV. Fields containing a comma, a double * quote or a newline are wrapped in double quotes, with embedded quotes * doubled. Rows are joined with `\r\n`. * * @param table - The table to serialise. * @returns The CSV text. */ declare function tableToCsv(table: ExtractedTable): string; /** * Convert a table to an array of plain objects, using the first row as the * header keys. Returns an empty array when the table has fewer than two * rows (i.e. no data rows beneath the header). * * @param table - The table to convert. * @returns One record per data row, mapping each header to its cell value. */ declare function tableToJson(table: ExtractedTable): Record[]; //#endregion //#region src/core/documentParts.d.ts /** * A single document part: a contiguous, inclusive range of page indices plus * optional Document Part Metadata. */ interface DocumentPart { /** Zero-based index of the first page in this part (inclusive). */ readonly startPage: number; /** Zero-based index of the last page in this part (inclusive). */ readonly endPage: number; /** * Optional Document Part Metadata. Each key/value pair is emitted as a * PDF name → literal-string entry inside the part's `/DPM` dictionary. */ readonly metadata?: Readonly> | undefined; } /** * Build a PDF 2.0 `/DPartRoot` dictionary from a flat list of document parts. * * The returned dictionary has: * - `/Type /DPartRoot` * - `/DPartRootNode` → a top `/DPart` node whose `/DParts` array holds one * child `/DPart` node per supplied {@link DocumentPart}. * * Each child node records its `/Start` and `/End` page indices and, when * present, its `/DPM` metadata dictionary. The structure is self-contained: * page positions are stored as plain numbers rather than resolved page * references. * * @param parts - The document parts, in page order. * @returns A spec-shaped `/DPartRoot` {@link PdfDict}. */ declare function buildDPartRoot(parts: readonly DocumentPart[]): PdfDict; //#endregion //#region src/core/requirements.d.ts /** * A standard requirement type, used as the `/S` (subtype) value of a * requirement dictionary. Each value names a feature the reader must * support to fully process the document. * * | Value | Meaning | * |-----------------------|----------------------------------------------------| * | `EnableJavaScripts` | Document-level JavaScript must be executable. | * | `Attachment` | Embedded file attachments must be supported. | * | `AcroForm` | Interactive (AcroForm) form fields are present. | * | `Navigation` | Presentation / navigation nodes must be supported. | * | `Markup` | Markup annotations must be supported. | * | `Encryption` | The encryption scheme must be supported. | * | `DigSigValidation` | Digital signatures must be validatable. | */ type RequirementType = "EnableJavaScripts" | "Attachment" | "AcroForm" | "Navigation" | "Markup" | "Encryption" | "DigSigValidation"; /** * Build a single requirement dictionary for the given requirement type. * * The returned dictionary has the form: * ``` * << /Type /Reqs /S / >> * ``` * * @param type - The requirement type used as the `/S` name. * @returns A {@link PdfDict} representing one requirement dictionary. */ declare function buildRequirement(type: RequirementType): PdfDict; /** * Build the document catalog `/Requirements` array from a list of * requirement types. * * Each element of the returned array is a requirement dictionary * (see {@link buildRequirement}). Duplicate types are preserved in the * order supplied; callers that want a de-duplicated set should filter the * input first. * * @param types - The requirement types, in the desired order. * @returns A {@link PdfArray} suitable for the catalog `/Requirements` key. */ declare function buildRequirements(types: readonly RequirementType[]): PdfArray; //#endregion //#region src/core/pieceInfo.d.ts /** * Build a `/PieceInfo` dictionary containing a single application data * dictionary. * * @param appName The producing application's name; becomes the key of * the data dictionary inside `/PieceInfo` (the leading * `/` is optional and added if missing). * @param privateData The application-private data dictionary stored under * `/Private`. * @param lastModified Modification timestamp for `/LastModified`; defaults * to the current time. * @returns A `/PieceInfo` dictionary with one entry keyed by * `appName`. */ declare function buildPieceInfo(appName: string, privateData: PdfDict, lastModified?: Date): PdfDict; //#endregion //#region src/accessibility/namespaces.d.ts /** * The standard structure namespace introduced by PDF 2.0 * (ISO 32000-2). Structure elements with no explicit namespace are * considered to belong to this namespace. */ declare const PDF2_NAMESPACE: string; /** The MathML namespace identifier (W3C MathML vocabulary). */ declare const MATHML_NAMESPACE: string; /** * A plain, serializable description of a single PDF 2.0 structure * namespace. */ interface NamespaceDef { /** The namespace identifier (`/NS`) — typically a URI. */ readonly ns: string; /** * Optional schema locator (`/Schema`). Serialized as a PDF string; * usually a URI or file name pointing at the namespace's schema. */ readonly schema?: string | undefined; /** * Optional role map (`/RoleMapNS`). Maps namespace-specific structure * type names onto standard (or other-namespace) structure type names. */ readonly roleMap?: Readonly> | undefined; } /** * Build a `/Namespace` dictionary from a {@link NamespaceDef}. * * The result always carries `/Type /Namespace` and `/NS` (a PDF string). * `/Schema` and `/RoleMapNS` are added only when supplied. * * @param def - the namespace descriptor. * @returns a freshly allocated {@link PdfDict} for the namespace. */ declare function buildNamespace(def: NamespaceDef): PdfDict; /** * Build the `/Namespaces` array (as found in `/StructTreeRoot`) from a * list of {@link NamespaceDef} descriptors. * * @param defs - the namespace descriptors, in order. * @returns a {@link PdfArray} of `/Namespace` dictionaries. */ declare function buildNamespacesArray(defs: readonly NamespaceDef[]): PdfArray; //#endregion //#region src/compliance/validationReport.d.ts /** * @module compliance/validationReport * * Structured validation report generation for compliance findings. * * Transforms a flat list of {@link ValidationFinding} objects (produced by * PDF/A, PDF/X, PDF/UA, XMP or any other validator in this library) into two * standardized, machine-readable report formats: * * - **JSON report** ({@link toJsonReport}) — a compact summary with conformance * status and error/warning counts, suitable for programmatic consumption or * simple CI gates. * - **SARIF 2.1.0** ({@link toSarif}) — the OASIS Static Analysis Results * Interchange Format, consumable by GitHub code scanning, Azure DevOps, * VS Code SARIF viewers and many other tools. * * This module is a pure data transform: it has no dependency on PDF objects and * performs no I/O. Validators emit {@link ValidationFinding}s; this module * serializes them. * * Reference: SARIF 2.1.0 — OASIS Standard, March 2020. */ /** Severity level of a validation finding. */ type ValidationLevel = "error" | "warning"; /** * A single validation finding produced by a compliance validator. * * `ruleId` identifies the rule that was violated (e.g. an ISO clause id or an * internal validator code). `clause`, `page` and `objectRef` are optional * location hints that are mapped into the corresponding report formats. */ interface ValidationFinding { readonly ruleId: string; readonly message: string; readonly level: ValidationLevel; readonly clause?: string | undefined; readonly page?: number | undefined; readonly objectRef?: string | undefined; } /** Compact JSON validation report with conformance status and counts. */ interface JsonReport { readonly conformant: boolean; readonly errorCount: number; readonly warningCount: number; readonly findings: readonly ValidationFinding[]; } /** SARIF message object — carries human-readable text. */ interface SarifMessage { readonly text: string; } /** SARIF rule descriptor referenced by results via its `id`. */ interface SarifReportingDescriptor { readonly id: string; } /** SARIF tool driver — the analysis tool that produced the run. */ interface SarifToolDriver { readonly name: string; readonly rules: readonly SarifReportingDescriptor[]; } /** SARIF tool wrapper. */ interface SarifTool { readonly driver: SarifToolDriver; } /** SARIF artifact location — a logical reference to the scanned artifact. */ interface SarifArtifactLocation { readonly uri: string; } /** SARIF region — a 1-based location hint inside an artifact (page number). */ interface SarifRegion { readonly startLine: number; } /** SARIF physical location — where a result was found. */ interface SarifPhysicalLocation { readonly artifactLocation: SarifArtifactLocation; readonly region?: SarifRegion | undefined; } /** SARIF location wrapper. */ interface SarifLocation { readonly physicalLocation: SarifPhysicalLocation; } /** Free-form property bag attached to a SARIF result. */ interface SarifResultProperties { readonly clause?: string | undefined; readonly objectRef?: string | undefined; } /** A single SARIF result — one validation finding. */ interface SarifResult { readonly ruleId: string; readonly level: ValidationLevel; readonly message: SarifMessage; readonly locations?: readonly SarifLocation[] | undefined; readonly properties?: SarifResultProperties | undefined; } /** A single SARIF run — one invocation of one tool. */ interface SarifRun { readonly tool: SarifTool; readonly results: readonly SarifResult[]; } /** A complete SARIF 2.1.0 log. */ interface SarifLog { readonly version: "2.1.0"; readonly $schema: string; readonly runs: readonly [SarifRun]; } /** Canonical SARIF 2.1.0 JSON schema URI. */ declare const SARIF_SCHEMA_URI: string; /** Default tool name reported in SARIF runs. */ declare const DEFAULT_SARIF_TOOL_NAME: string; /** * Build a compact {@link JsonReport} from a list of findings. * * Counts errors and warnings; the document is considered conformant when there * are zero errors (warnings do not affect conformance). * * @param findings - The validation findings to summarize. * @returns A structured JSON report. */ declare function toJsonReport(findings: readonly ValidationFinding[]): JsonReport; /** * Build a SARIF 2.1.0 log from a list of findings. * * Produces exactly one run. Each finding maps to one SARIF result with its * level mapped directly (`error`/`warning`). The run's rule descriptor list is * de-duplicated by `ruleId`, preserving first-seen order. `page` is mapped onto * a physical-location region; `clause` and `objectRef` are surfaced via the * result property bag. * * @param findings - The validation findings to serialize. * @param toolName - Optional tool name; defaults to {@link DEFAULT_SARIF_TOOL_NAME}. * @returns A SARIF 2.1.0 log. */ declare function toSarif(findings: readonly ValidationFinding[], toolName?: string): SarifLog; //#endregion //#region src/core/colorSpacesCIE.d.ts /** Parameters for a CalGray colour space (ISO 32000-2 §8.6.5.2). */ interface CalGrayParams { /** Diffuse white point `[Xw Yw Zw]`; `Yw` shall equal 1.0. */ readonly whitePoint: readonly [number, number, number]; /** Diffuse black point `[Xb Yb Zb]`; defaults to `[0 0 0]`. */ readonly blackPoint?: readonly [number, number, number] | undefined; /** Gamma exponent for the single grey component; defaults to 1.0. */ readonly gamma?: number | undefined; } /** Parameters for a CalRGB colour space (ISO 32000-2 §8.6.5.3). */ interface CalRGBParams { /** Diffuse white point `[Xw Yw Zw]`; `Yw` shall equal 1.0. */ readonly whitePoint: readonly [number, number, number]; /** Diffuse black point `[Xb Yb Zb]`; defaults to `[0 0 0]`. */ readonly blackPoint?: readonly [number, number, number] | undefined; /** Per-component gamma `[GR GG GB]`; defaults to `[1 1 1]`. */ readonly gamma?: readonly [number, number, number] | undefined; /** 3×3 linear transform (9 numbers, column-major); defaults to identity. */ readonly matrix?: readonly number[] | undefined; } /** Parameters for a Lab colour space (ISO 32000-2 §8.6.5.4). */ interface LabParams { /** Diffuse white point `[Xw Yw Zw]`; `Yw` shall equal 1.0. */ readonly whitePoint: readonly [number, number, number]; /** Diffuse black point `[Xb Yb Zb]`; defaults to `[0 0 0]`. */ readonly blackPoint?: readonly [number, number, number] | undefined; /** `[amin amax bmin bmax]` ranges for the a* and b* components. */ readonly range?: readonly [number, number, number, number] | undefined; } /** * Build a CalGray colour-space array. * * @returns `[/CalGray << /WhitePoint … [/BlackPoint …] [/Gamma …] >>]`. */ declare function buildCalGray(p: CalGrayParams): PdfArray; /** * Build a CalRGB colour-space array. * * @returns `[/CalRGB << /WhitePoint … [/BlackPoint …] [/Gamma …] [/Matrix …] >>]`. */ declare function buildCalRGB(p: CalRGBParams): PdfArray; /** * Build a Lab colour-space array. * * @returns `[/Lab << /WhitePoint … [/BlackPoint …] [/Range …] >>]`. */ declare function buildLab(p: LabParams): PdfArray; /** * Convert a CIE L*a*b* colour to sRGB (0..1 per channel). * * The pipeline is the standard L*a*b* → XYZ → linear-sRGB → gamma-companded * sRGB transform. XYZ is Bradford-free (a plain scaling by the white point), * matching the ICC `Lab` PCS convention. The default white point is CIE D50, * which is the white point used by ICC profile connection space and PDF Lab * colour data. * * @param L Lightness, 0..100. * @param a Green–red component (typically −128..127). * @param b Blue–yellow component (typically −128..127). * @param whitePoint Reference white `[Xn Yn Zn]` (Y = 1); defaults to D50. * @returns `[r, g, b]` each in the range 0..1. */ declare function labToRgb(L: number, a: number, b: number, whitePoint?: readonly [number, number, number]): [number, number, number]; //#endregion //#region src/signature/docTimeStamp.d.ts /** * Default size, in bytes, of the `/Contents` placeholder. * * An RFC 3161 TimeStampToken (including the TSA certificate chain) is * typically a few kilobytes; 8192 bytes (16384 hex digits) leaves ample * room for most TSAs while keeping the placeholder modest. */ declare const DEFAULT_DOC_TIMESTAMP_CONTENTS_SIZE: number; /** * Options controlling how the Document Timestamp dictionary is built. */ interface DocTimeStampOptions { /** * Number of bytes reserved for the `/Contents` placeholder. This must * be large enough to hold the DER-encoded TimeStampToken returned by * the TSA. Defaults to {@link DEFAULT_DOC_TIMESTAMP_CONTENTS_SIZE}. */ readonly contentsSize?: number | undefined; /** * Optional human-readable reason recorded in the signature dictionary's * `/Reason` field. Purely informational for a timestamp. */ readonly reason?: string | undefined; } /** * Build a standalone Document Timestamp signature dictionary. * * The returned {@link PdfDict} contains: * - `/Type` `/DocTimeStamp` * - `/Filter` `/Adobe.PPKLite` * - `/SubFilter` `/ETSI.RFC3161` * - `/ByteRange` `[0 0 0 0]` — a placeholder to be patched during save * - `/Contents` a zero-filled hex string of `contentsSize` bytes * - `/Reason` (only when {@link DocTimeStampOptions.reason} is given) * * The `/Contents` value is serialized as a hexadecimal string * (`<0000…>`); it occupies `contentsSize` bytes ⇒ `2 × contentsSize` * hex digits. The real RFC 3161 TimeStampToken is injected over this * placeholder later, during incremental save. * * @param options Optional configuration. * @returns The Document Timestamp signature dictionary. * @throws {RangeError} when `contentsSize` is not a positive * integer. * * @example * ```ts * const dts = buildDocTimeStampDict({ contentsSize: 16384 }); * const ref = registry.register(dts); * // …later, during incremental save, patch /ByteRange and /Contents * // with the offsets and the TSA token from requestTimestamp(). * ``` */ declare function buildDocTimeStampDict(options?: DocTimeStampOptions): PdfDict; //#endregion //#region src/parser/textReconstruct.d.ts /** * A single reconstructed line of text. */ interface Line { /** The joined text content of the line, in reading order. */ readonly text: string; /** The representative baseline `y` coordinate of the line. */ readonly y: number; /** The source items that make up this line, sorted left-to-right. */ readonly items: readonly TextItem$1[]; } /** * A reconstructed paragraph: a run of vertically-adjacent lines. */ interface Paragraph { /** The joined text content of the paragraph (lines joined with `"\n"`). */ readonly text: string; /** The lines that make up this paragraph, in top-to-bottom reading order. */ readonly lines: readonly Line[]; } /** * Options controlling line and paragraph reconstruction. */ interface ReconstructOptions { /** * Maximum vertical distance (in user-space units) between two items for * them to be considered part of the same line. * Default: roughly half the median item height. */ readonly lineTolerance?: number | undefined; /** * A new paragraph starts when the vertical gap between two consecutive * lines exceeds this factor times the typical line height. * Default: `1.5`. */ readonly paragraphGapFactor?: number | undefined; } /** * Group positioned text items into lines. * * Items are bucketed by baseline `y` (within `lineTolerance`), sorted * left-to-right within each line, and returned in top-to-bottom reading order. * * @param items The positioned text items (e.g. from `extractText` with * positions enabled). Order is irrelevant; they are re-sorted. * @param options Reconstruction options. * @returns The reconstructed lines, in reading order. */ declare function reconstructLines(items: readonly TextItem$1[], options?: ReconstructOptions): Line[]; /** * Group positioned text items into paragraphs. * * First reconstructs lines (see {@link reconstructLines}), then starts a new * paragraph whenever the vertical gap between two consecutive lines exceeds * `paragraphGapFactor` times the typical (median) line height. * * @param items The positioned text items. * @param options Reconstruction options. * @returns The reconstructed paragraphs, in reading order. */ declare function reconstructParagraphs(items: readonly TextItem$1[], options?: ReconstructOptions): Paragraph[]; //#endregion //#region src/core/collections.d.ts /** * Collection view mode (ISO 32000-2, Table 43, `/View`): * * - `'D'` — Details: a multi-column list with the schema fields as columns. * - `'T'` — Tile: a tiled icon view. * - `'H'` — Hidden: the collection UI is initially hidden. */ type CollectionView = "D" | "T" | "H"; /** * One field of a collection schema (ISO 32000-2, Table 44 "Entries in a * collection field dictionary"). */ interface CollectionSchemaField { /** Schema key — the name under which the subfield dict is stored in `/Schema`. */ readonly key: string; /** Human-readable column label (`/N`). */ readonly label: string; /** * Field data type (`/Subtype`): * * - `'S'` — text string. * - `'D'` — date. * - `'N'` — number. */ readonly fieldType: "S" | "D" | "N"; /** Optional relative column order (`/O`); lower sorts first. */ readonly order?: number | undefined; } /** Options controlling the generated `/Collection` dictionary. */ interface CollectionOptions { /** Initial view mode; defaults to `'D'` (Details). */ readonly view?: CollectionView | undefined; /** Schema fields describing the columns / metadata of each embedded file. */ readonly schema?: readonly CollectionSchemaField[] | undefined; /** * One or more schema keys used to sort the file list initially. * A single key serializes `/S` as a name; multiple keys as an array. */ readonly sortKeys?: readonly string[] | undefined; /** * Name (in the `EmbeddedFiles` name tree) of the file to present first * (`/D`). */ readonly initialDocument?: string | undefined; } /** * Build a `/Collection` dictionary (ISO 32000-2 §7.11.6) suitable for * placing in the document catalog under `/Collection`. * * @param options - Collection configuration; all fields are optional. An * empty/omitted options object yields a minimal collection with * `/Type /Collection` and `/View /D`. * @returns The populated collection dictionary. */ declare function buildCollection(options?: CollectionOptions): PdfDict; //#endregion //#region src/assets/markdown/markdownToPdf.d.ts /** * Options controlling {@link markdownToPdf} layout. */ interface MarkdownToPdfOptions { /** Base body font size in points. Defaults to `12`. */ readonly fontSize?: number | undefined; /** Page margin in points applied to all four sides. Defaults to `50`. */ readonly margin?: number | undefined; /** * Line-height multiplier applied to the font size of each rendered line. * Defaults to `1.4`. */ readonly lineHeight?: number | undefined; } /** * Convert a CommonMark **subset** string into PDF bytes. * * @param markdown The Markdown source text. * @param options Optional layout options ({@link MarkdownToPdfOptions}). * @returns A promise resolving to the saved PDF as a `Uint8Array`. */ declare function markdownToPdf(markdown: string, options?: MarkdownToPdfOptions): Promise; //#endregion //#region src/core/pdfFunctions.d.ts /** * @module core/pdfFunctions * * PDF function objects and their evaluator (ISO 32000-2 §7.10). * * PDF functions are reusable, pure mathematical mappings from an * `m`-dimensional input domain to an `n`-dimensional output range. They are * the shared building block for shadings (§8.7.4.5), transfer functions * (§8.4.5), halftones, Separation/DeviceN tint transforms (§8.6.6.4) and * soft-mask transfer functions. * * Four function types are defined by the spec, all supported here: * * - **Type 0** — sampled functions. A regularly spaced multidimensional table * of samples; output is obtained by (multi-)linear interpolation. * - **Type 2** — exponential interpolation between two value vectors `C0` and * `C1` with exponent `N`. * - **Type 3** — stitching functions. A 1-input function that partitions its * domain by `Bounds` and dispatches to a list of sub-functions. * - **Type 4** — PostScript calculator functions: a restricted, stack-based * PostScript-like language with no I/O or general control flow beyond * `if` / `ifelse`. * * This module is intentionally free of {@link PdfObject} dependencies: the * evaluator works purely on plain numeric definitions so it can be reused by * higher-level builders and by rasterisers without coupling to the document * object model. */ /** * Type 0 — sampled function (ISO 32000-2 §7.10.2). * * Samples are stored row-major with the first input dimension varying * fastest, each sample component packed into `bitsPerSample` bits and already * decoded into the `[0, 2^bitsPerSample − 1]` integer range as numbers. */ interface SampledFunction { readonly functionType: 0; /** Input domain `[min0 max0 min1 max1 …]`, two entries per input. */ readonly domain: readonly number[]; /** Output range `[min0 max0 …]`, two entries per output component. */ readonly range: readonly number[]; /** Number of samples in each input dimension. */ readonly size: readonly number[]; /** Bits used to represent each sample component (1,2,4,8,12,16,24,32). */ readonly bitsPerSample: number; /** * Flat list of sample component values, row-major, first input dimension * varying fastest, output components grouped per grid point. */ readonly samples: readonly number[]; /** Per-input encode pairs mapping domain → sample-grid coordinates. */ readonly encode?: readonly number[] | undefined; /** Per-output decode pairs mapping raw samples → range. */ readonly decode?: readonly number[] | undefined; } /** * Type 2 — exponential interpolation function (ISO 32000-2 §7.10.3). * * Defines `out[i] = C0[i] + x^N · (C1[i] − C0[i])` for a single clamped * input `x`. */ interface ExponentialFunction { readonly functionType: 2; /** Input domain `[min max]` for the single input. */ readonly domain: readonly number[]; /** Output values at `x = 0`; defaults to `[0]`. */ readonly c0?: readonly number[] | undefined; /** Output values at `x = 1`; defaults to `[1]`. */ readonly c1?: readonly number[] | undefined; /** Interpolation exponent `N`. */ readonly n: number; } /** * Type 3 — stitching function (ISO 32000-2 §7.10.4). * * A 1-input function whose domain is split into `k` subdomains by `bounds`; * each subdomain dispatches to one of `functions`, after re-encoding the * input into that sub-function's domain via `encode`. */ interface StitchingFunction { readonly functionType: 3; /** Input domain `[min max]`. */ readonly domain: readonly number[]; /** The `k` sub-functions. */ readonly functions: readonly PdfFunctionDef[]; /** The `k − 1` interior boundary values, strictly increasing. */ readonly bounds: readonly number[]; /** `2k` encode values mapping each subdomain to its sub-function domain. */ readonly encode: readonly number[]; } /** * Type 4 — PostScript calculator function (ISO 32000-2 §7.10.5). * * `source` is the PostScript program including its enclosing `{ … }`. */ interface PostScriptFunction { readonly functionType: 4; /** Input domain `[min0 max0 …]`, two entries per input. */ readonly domain: readonly number[]; /** Output range `[min0 max0 …]`, two entries per output component. */ readonly range: readonly number[]; /** The PostScript calculator source, including the outer braces. */ readonly source: string; } /** Any of the four supported PDF function definitions. */ type PdfFunctionDef = SampledFunction | ExponentialFunction | StitchingFunction | PostScriptFunction; /** * Evaluate a PDF function definition at the given input vector. * * Inputs are clamped to the function's `Domain` and outputs are clamped to its * `Range` (when defined), per ISO 32000-2 §7.10. Returns a freshly allocated * numeric array of output components. * * @param fn - the function definition. * @param inputs - the `m`-dimensional input vector. * @returns the `n`-dimensional output vector. */ declare function evaluateFunction(fn: PdfFunctionDef, inputs: readonly number[]): number[]; //#endregion //#region src/core/halftone.d.ts /** * The predefined spot-function names recognised by conforming readers * (ISO 32000-2, Table 75). Any of these may be used as the * `spotFunction` of a {@link Type1Halftone}. */ declare const STANDARD_SPOT_FUNCTIONS: readonly string[]; /** * Parameters for a Type 1 (spot-function) halftone. */ interface Type1Halftone { /** Screen frequency in halftone cells per inch. */ readonly frequency: number; /** Screen angle in degrees, measured counter-clockwise. */ readonly angle: number; /** * The spot function — typically one of {@link STANDARD_SPOT_FUNCTIONS}. * Emitted as a PDF name `/SpotFunction`. */ readonly spotFunction: string; /** * When `true`, request the more accurate (but slower) screening * algorithm via `/AccurateScreens true`. */ readonly accurateScreens?: boolean | undefined; } /** * Build a Type 1 halftone dictionary. * * Emits `/Type /Halftone /HalftoneType 1` with numeric `/Frequency` and * `/Angle`, a `/SpotFunction` name, and an optional `/AccurateScreens` * boolean. */ declare function buildType1Halftone(p: Type1Halftone): PdfDict; /** * Build a threshold-array halftone stream (Type 6, 10, or 16). * * Emits a stream whose dictionary carries `/Type /Halftone`, * `/HalftoneType` (6, 10, or 16), `/Width`, and `/Height`, and whose body * is the raw threshold data. * * For Type 16 the threshold samples are 16-bit; callers must supply two * bytes per sample in big-endian order inside `thresholds`. */ declare function buildThresholdHalftone(halftoneType: 6 | 10 | 16, width: number, height: number, thresholds: Uint8Array): PdfStream; /** * Build a Type 5 halftone dictionary. * * A Type 5 halftone maps each named colorant to its own halftone * dictionary and supplies a `/Default` halftone for any colorant not * explicitly listed. Emits `/Type /Halftone /HalftoneType 5`, one entry * per colorant (keyed by colorant name), and `/Default`. * * @param colorants Map of colorant name → halftone dictionary (each a * Type 1/6/10/16 halftone). The reserved key `Default` is ignored here * in favour of `defaultHalftone`. * @param defaultHalftone The fallback halftone for unlisted colorants. */ declare function buildType5Halftone(colorants: Readonly>, defaultHalftone: PdfDict): PdfDict; /** * Build an `Identity` transfer-function name object (`/Identity`). * * The value of a transfer function entry may be the name `Identity`, in * which case no adjustment is applied to component values. */ declare function identityTransferFunction(): PdfName; /** * Build a sampled (Type 0) transfer-function stream from a lookup table. * * Emits a stream with `/FunctionType 0`, `/Domain [0 1]`, `/Range [0 1]`, * `/Size [n]`, and `/BitsPerSample 8`; the body is the raw `samples` * array (one byte per sample, mapping input 0..1 to output 0..1). * * @param samples 8-bit output samples spanning the input domain `[0, 1]`. */ declare function buildSampledTransferFunction(samples: Uint8Array): PdfStream; /** * Build a graphics-state-ready halftone reference dictionary fragment * pairing a halftone with an optional `/HalftoneName`. * * Emits the supplied halftone unchanged when `name` is omitted; otherwise * sets `/HalftoneName` (a literal string) on it and returns it. This is a * convenience for naming a halftone for caching by conforming readers. */ declare function nameHalftone(halftone: PdfDict, name?: string): PdfDict; //#endregion //#region src/compliance/pdfX6.d.ts /** The supported PDF/X-6 conformance variants. */ type PdfX6Variant = "PDF/X-6" | "PDF/X-6p" | "PDF/X-6n"; /** Options describing the PDF/X-6 output intent and conformance. */ interface PdfX6Options { /** Conformance variant. Defaults to `'PDF/X-6'`. */ readonly variant?: PdfX6Variant | undefined; /** * Output condition identifier — a registered name (e.g. a registry * reference such as `'FOGRA51'`) or `'Custom'` for an embedded profile. */ readonly outputConditionIdentifier: string; /** Human-readable description of the intended printing condition. */ readonly outputCondition?: string | undefined; /** Name of the registry the identifier belongs to (e.g. a URL). */ readonly registryName?: string | undefined; } /** A rectangle expressed as `[llx, lly, urx, ury]` in default user space. */ type PdfRect = readonly [number, number, number, number]; /** Page-geometry boxes relevant to PDF/X conformance. */ interface BoxGeometry { /** The media box — the physical medium bounds. Required. */ readonly mediaBox: PdfRect; /** The trim box — the intended finished page bounds. */ readonly trimBox?: PdfRect | undefined; /** The bleed box — the region painted then trimmed away. */ readonly bleedBox?: PdfRect | undefined; } /** * Build a PDF/X-6 output-intent dictionary. * * The returned dictionary uses the `/GTS_PDFX` output-intent subtype required * by all PDF/X families. The caller is responsible for attaching an embedded * ICC profile stream under `/DestOutputProfile` (for `PDF/X-6` / `PDF/X-6n`) * and adding the dictionary to the catalog `/OutputIntents` array. * * @param options - Output-intent identification. * @returns A freshly-built `/Type /OutputIntent` dictionary. */ declare function buildPdfX6OutputIntent(options: PdfX6Options): PdfDict; /** * Return the `GTS_PDFXVersion` Info-dictionary value for a variant. * * @param variant - The conformance variant. Defaults to `'PDF/X-6'`. * @returns The string to store under the Info-dict `/GTS_PDFXVersion` key. */ declare function buildGtsPdfxVersion(variant?: PdfX6Variant): string; /** * Validate page-geometry boxes against PDF/X-6 requirements. * * Rules enforced (ISO 15930-9, PDF 2.0 §14.11.2): * - A valid MediaBox with positive area is required. * - A TrimBox (or ArtBox; this helper models the TrimBox path) is required. * - The TrimBox must lie within the MediaBox. * - If present, the BleedBox must lie within the MediaBox, and the TrimBox * must lie within the BleedBox. * * @param box - The geometry to validate. * @returns An array of human-readable error messages; empty when valid. */ declare function validateBoxGeometry(box: BoxGeometry): string[]; /** * Build the page-box entries (`/MediaBox`, `/TrimBox`, `/BleedBox`) as a * dictionary fragment that can be merged into a page dictionary. * * @param box - The geometry to encode. * @returns A dictionary holding the box arrays. */ declare function buildBoxDict(box: BoxGeometry): PdfDict; //#endregion //#region src/compliance/facturX.d.ts /** * @module compliance/facturX * * Factur-X / ZUGFeRD CrossIndustryInvoice (CII) XML generator. * * Produces a well-formed UN/CEFACT Cross Industry Invoice (CII) XML * document that can be embedded into a PDF/A-3 file to create a * hybrid Factur-X / ZUGFeRD electronic invoice. * * The generator is pure TypeScript string generation — it does not * rely on a DOM implementation, so it runs identically across Node, * Deno, Bun, Cloudflare Workers and browsers. * * Supported profiles (conformance levels) and their * `GuidelineSpecifiedDocumentContextParameter` URNs: * - MINIMUM — urn:factur-x.eu:1p0:minimum * - BASIC-WL — urn:factur-x.eu:1p0:basicwl * - BASIC — urn:cen.eu:en16931:2017#compliant#urn:factur-x.eu:1p0:basic * - EN16931 — urn:cen.eu:en16931:2017 * - EXTENDED — urn:cen.eu:en16931:2017#conformant#urn:factur-x.eu:1p0:extended * * References: * - UN/CEFACT Cross Industry Invoice (CII) D16B * - EN 16931-1:2017 (European semantic invoice standard) * - Factur-X 1.0 / ZUGFeRD 2.x specification */ /** Factur-X / ZUGFeRD conformance profile. */ type FacturXProfile = "MINIMUM" | "BASIC-WL" | "BASIC" | "EN16931" | "EXTENDED"; /** A trading party (seller or buyer) on the invoice. */ interface InvoiceParty { /** Legal/trading name of the party. */ readonly name: string; /** ISO 3166-1 alpha-2 country code (e.g. 'DE', 'FR'). */ readonly countryCode: string; /** VAT registration identifier, if any (e.g. 'DE123456789'). */ readonly vatId?: string | undefined; } /** A single invoice line item. */ interface InvoiceLine { /** Free-text description of the goods or services. */ readonly description: string; /** Billed quantity. */ readonly quantity: number; /** Net unit price (excluding tax) in the invoice currency. */ readonly unitPrice: number; /** VAT rate applied to this line, in percent (e.g. 19 for 19%). */ readonly taxPercent: number; } /** A complete invoice ready to be rendered as CII XML. */ interface Invoice { /** Invoice document number (BT-1). */ readonly invoiceNumber: string; /** Issue date as an ISO date string ('YYYY-MM-DD'). */ readonly issueDate: string; /** ISO 4217 currency code (e.g. 'EUR'). */ readonly currency: string; /** Seller trade party. */ readonly seller: InvoiceParty; /** Buyer trade party. */ readonly buyer: InvoiceParty; /** Invoice line items. */ readonly lines: readonly InvoiceLine[]; } /** * Generate a UN/CEFACT Cross Industry Invoice (CII) XML document for * the given invoice and Factur-X / ZUGFeRD profile. * * The returned string is a well-formed XML document beginning with an * XML declaration and a `` root element using * the standard `rsm`, `ram` and `udt` namespaces. All text values are * XML-escaped. * * @param invoice - The invoice data. * @param profile - The Factur-X / ZUGFeRD profile. Default: 'EN16931'. * @returns The CII XML document as a string. */ declare function generateCiiXml(invoice: Invoice, profile?: FacturXProfile): string; //#endregion //#region src/utils/codeframe.d.ts /** * @module utils/codeframe * * Developer-experience helpers for producing friendly diagnostics: * * - {@link renderCodeFrame} renders a source excerpt with line-number gutters * and a caret pointing at an offending column (in the style of Babel / * TypeScript error frames). * - {@link levenshtein} computes the classic edit distance between two strings. * - {@link didYouMean} suggests the closest candidate to a misspelled input, * used to power "did you mean …?" hints on unknown identifiers. * * Pure TypeScript with no runtime dependencies; safe in every supported * runtime (Node 25+, Deno, Bun, Cloudflare Workers, browsers). */ /** * Options for {@link renderCodeFrame}. */ interface CodeFrameOptions { /** * Number of context lines to show before and after the target line. * Defaults to `2`. */ readonly contextLines?: number | undefined; } /** * Render a code frame: an excerpt of `source` centered on a 1-based * `line`/`column`, with a line-number gutter and a caret (`^`) underneath the * target column. * * Lines outside the available source range are clamped. A non-positive * `contextLines` shows only the target line itself. * * @param source The full source text. * @param line The 1-based line number to highlight. * @param column The 1-based column number to point the caret at. * @param options Optional rendering options. * @returns A multi-line string ready to print in a diagnostic. */ declare function renderCodeFrame(source: string, line: number, column: number, options?: CodeFrameOptions): string; /** * Compute the Levenshtein edit distance between two strings: the minimum * number of single-character insertions, deletions, or substitutions required * to transform `a` into `b`. * * @param a The first string. * @param b The second string. * @returns The edit distance (`>= 0`). */ declare function levenshtein(a: string, b: string): number; /** * Suggest the closest candidate to `input` from a list of `candidates`, * useful for "did you mean …?" hints. * * The accepted distance is the smaller of `maxDistance` and a value scaled to * the length of `input` (roughly one third of its length, with a minimum of * one), so short identifiers do not match wildly different strings. * * @param input The (possibly misspelled) string. * @param candidates The known valid strings. * @param maxDistance The hard upper bound on edit distance. Defaults to `3`. * @returns The closest candidate within range, or `undefined`. */ declare function didYouMean(input: string, candidates: readonly string[], maxDistance?: number): string | undefined; //#endregion //#region src/core/shadingFunction.d.ts /** * Options describing a function-based (type 1) shading. */ interface FunctionShadingOptions { /** * The rectangular domain `[xmin xmax ymin ymax]` of the shading's * coordinate space. Defaults to `[0 1 0 1]` per the spec. */ readonly domain?: readonly [number, number, number, number] | undefined; /** * The `/Matrix` mapping the domain into the target (pattern/user) space, * as `[a b c d e f]`. Defaults to the identity matrix. */ readonly matrix?: readonly [number, number, number, number, number, number] | undefined; /** * The shading colour space name (e.g. `DeviceRGB`, `DeviceGray`, * `DeviceCMYK`). Defaults to `DeviceRGB`. */ readonly colorSpace?: string | undefined; /** * The colour-producing function. Its input is the 2-D domain coordinate and * its output is one colour value in {@link FunctionShadingOptions.colorSpace}. */ readonly fn: PdfFunctionDef; } /** * Build a function-based (type 1) `/Shading` dictionary. * * The returned dict carries `/ShadingType 1`, the (defaulted) `/Domain`, * `/Matrix` and `/ColorSpace`, and an inline `/Function` dictionary built from * `options.fn`. * * @param options - the shading definition. * @returns a `PdfDict` ready to be referenced from a pattern or resource dict. */ declare function buildFunctionShading(options: FunctionShadingOptions): PdfDict; /** * Sample the shading's colour at domain coordinate `(x, y)`. * * Evaluates `options.fn` at the 2-D input vector and returns the resulting * colour components (clamped to the function's range by * {@link evaluateFunction}). * * @param options - the shading definition. * @param x - the first domain coordinate. * @param y - the second domain coordinate. * @returns the evaluated colour components. */ declare function sampleShadingColor(options: FunctionShadingOptions, x: number, y: number): number[]; //#endregion //#region src/compliance/pdfA4.d.ts /** * @module compliance/pdfA4 * * PDF/A-4 conformance metadata generator (ISO 19005-4:2020). * * PDF/A-4 is the fourth part of the PDF/A standard, based on PDF 2.0 * (ISO 32000-2). Unlike earlier parts, PDF/A-4 drops the A/B/U * conformance levels of its core profile and instead introduces two * named conformance variants: * * - **PDF/A-4** — the base conformance level (no `pdfaid:conformance`). * - **PDF/A-4e** — engineering variant, permits embedded 3D/RichMedia * content (`pdfaid:conformance = 'E'`). * - **PDF/A-4f** — variant that explicitly permits embedded files of * arbitrary type (`pdfaid:conformance = 'F'`). * * All PDF/A-4 documents declare `pdfaid:part = 4` and the revision year * `pdfaid:rev = 2020`. * * This module performs pure string / XMP packet generation — it does not * mutate any PDF document object. * * Reference: ISO 19005-4:2020 §5 (file format), §6.1 (metadata). */ /** Supported PDF/A-4 conformance variants. */ type PdfA4Level = "PDF/A-4" | "PDF/A-4e" | "PDF/A-4f"; /** A single property within a PDF/A extension schema. */ interface PdfA4ExtensionProperty { /** Property name. */ readonly name: string; /** XMP value type (e.g. 'Text', 'Integer', 'Boolean'). */ readonly valueType: string; /** Whether the property is internally or externally derived. */ readonly category: "internal" | "external"; /** Human-readable description of the property. */ readonly description: string; } /** Describes a PDF/A extension schema for non-standard XMP namespaces. */ interface PdfA4ExtensionSchema { /** Namespace URI of the extended schema. */ readonly namespaceUri: string; /** Preferred namespace prefix. */ readonly prefix: string; /** Human-readable schema name. */ readonly schema: string; /** Properties defined by this schema. */ readonly properties: readonly PdfA4ExtensionProperty[]; } /** Options for generating PDF/A-4 XMP metadata. */ interface PdfA4Options { /** Conformance variant. Default: `'PDF/A-4'`. */ readonly level?: PdfA4Level | undefined; /** Document title (Dublin Core `dc:title`). */ readonly title?: string | undefined; /** Extension schemas to declare under `pdfaExtension:schemas`. */ readonly extensionSchemas?: readonly PdfA4ExtensionSchema[] | undefined; } /** * Build a complete XMP metadata packet for a PDF/A-4 document. * * The packet declares the mandatory PDF/A identification fields * (`pdfaid:part = 4`, `pdfaid:rev = 2020`, and `pdfaid:conformance` * for the `e`/`f` variants), an optional `dc:title`, and a * `pdfaExtension:schemas` bag describing any supplied extension schemas. * * @param options - PDF/A-4 metadata options. * @returns A well-formed XMP packet as a string. */ declare function buildPdfA4Xmp(options?: PdfA4Options): string; /** * Return the human-readable conformance requirements for a PDF/A-4 * variant. * * @param level - Conformance variant. Default: `'PDF/A-4'`. * @returns An ordered list of requirement strings. */ declare function pdfA4Rules(level?: PdfA4Level): readonly string[]; //#endregion //#region src/compliance/xRechnung.d.ts /** Additional XRechnung-specific options layered on top of {@link Invoice}. */ interface XRechnungOptions { /** * Leitweg-ID (BT-DE-15 BuyerReference): the German routing identifier * addressing the public-sector buyer. Mandatory for XRechnung in * practice; emitted as the CII BuyerReference when provided. */ readonly leitwegId?: string | undefined; /** * Buyer reference (BT-10). Falls back to {@link XRechnungOptions.leitwegId} * when omitted, since XRechnung carries the Leitweg-ID as BuyerReference. */ readonly buyerReference?: string | undefined; } /** Order-X document kind, mapped to a UNTDID 1001 document type code. */ type OrderXType = "Order" | "OrderChange" | "OrderResponse"; /** * Generate an XRechnung 3.x CII (Cross Industry Invoice) XML document. * * The document carries the KoSIT XRechnung guideline URN * (`urn:cen.eu:en16931:2017#compliant#urn:xeinkauf.de:kosit:xrechnung_3.0`) * and, when a Leitweg-ID is supplied, the mandatory BT-DE-15 BuyerReference. * * @param invoice - The invoice data (shared {@link Invoice} model). * @param options - XRechnung-specific options (Leitweg-ID, buyer reference). * @returns A well-formed CII XML document string. */ declare function generateXRechnungCii(invoice: Invoice, options?: XRechnungOptions): string; /** * Generate an Order-X CII order document (Order, OrderChange or * OrderResponse) from the shared {@link Invoice} data model. * * The document is built on the UN/CEFACT SCRDMCCBDACIOMessageStructure * (Cross Industry Order) schema, carries the Order-X guideline URN * (`urn:order-x.eu:1p0:basic`) and the UNTDID 1001 document type code * appropriate for the requested {@link OrderXType} (220 Order / 230 * OrderChange / 231 OrderResponse). * * @param invoice - The order data (reusing the shared {@link Invoice} model). * @param orderType - The kind of Order-X document to produce. * @returns A well-formed Order-X CII XML document string. */ declare function generateOrderX(invoice: Invoice, orderType: OrderXType): string; //#endregion //#region src/assets/font/fontFallback.d.ts /** * @module assets/font/fontFallback * * Font fallback chains with per-glyph script splitting. * * When a single font cannot cover every code point in a string (for example * mixed Latin + CJK text), a fallback chain resolves each code point to the * first font in an ordered list that can render it. Consecutive code points * resolving to the same font are coalesced into a single run so callers can * emit one text-showing operation per run instead of per glyph. * * A complementary {@link splitByScript} helper segments text into runs of a * single Unicode script using simple range checks. This is enough to drive * bidi-agnostic shaping decisions and to choose script-appropriate fonts. * * Pure logic — no font binaries are required. Coverage is expressed through * the caller-supplied {@link FallbackFont.covers} predicate. * * No Buffer, no fs, no require() — ESM only. */ /** * A candidate font in a fallback chain. The {@link covers} predicate reports * whether the font can render a given Unicode code point. */ interface FallbackFont { /** Human-readable font identifier returned in {@link FallbackRun.font}. */ readonly name: string; /** Returns `true` if this font can render the given Unicode code point. */ readonly covers: (codepoint: number) => boolean; } /** * A contiguous slice of the input text that resolves to a single font. */ interface FallbackRun { /** Name of the font chosen for every code point in this run. */ readonly font: string; /** The text covered by this run (may include astral characters). */ readonly text: string; /** Code-point index (not UTF-16 index) where this run starts. */ readonly start: number; } /** * A contiguous slice of the input text belonging to a single Unicode script. */ interface ScriptRun { /** Script name (e.g. `'Latin'`, `'Han'`, `'Common'`). */ readonly script: string; /** The text covered by this run. */ readonly text: string; /** Code-point index (not UTF-16 index) where this run starts. */ readonly start: number; } /** * Resolve a fallback chain over `text`, code point by code point. * * For each code point the FIRST font in `fonts` whose `covers()` returns true * is selected. The final font in the list is treated as the ultimate fallback * and is used even when its `covers()` returns false, guaranteeing every code * point is assigned. Consecutive code points using the same font are coalesced * into a single {@link FallbackRun}. * * @param text The string to resolve (iterated by Unicode code point). * @param fonts Ordered fallback chain; the last entry is the ultimate fallback. * @returns One run per maximal same-font slice, in document order. */ declare function resolveFallback(text: string, fonts: readonly FallbackFont[]): FallbackRun[]; /** * Segment `text` into runs of a single Unicode script using simple range * checks. Supported scripts: Latin, Greek, Cyrillic, Arabic, Hebrew, Han, * Hiragana, Katakana, Hangul, and Common (everything else, including spaces, * digits, and punctuation). * * Consecutive code points of the same script are coalesced into one run. * * @param text The string to segment (iterated by Unicode code point). * @returns One {@link ScriptRun} per maximal same-script slice, in order. */ declare function splitByScript(text: string): ScriptRun[]; //#endregion //#region src/runtime/rangeFetch.d.ts /** * @module runtime/rangeFetch * * HTTP Range-request lazy fetch — progressively open a remote PDF by * fetching only the byte ranges that are actually needed instead of * downloading the whole file up front. * * The implementation is pure logic: the underlying transport is injected * via a {@link FetchLike} function so it can be unit-tested without * touching the network. By default it uses `globalThis.fetch`. * * Range semantics follow RFC 7233: * * - A range request carries a `Range: bytes=-` header where * `` is **inclusive**. * - A server that honours the range replies with `206 Partial Content` * and a `Content-Range: bytes -/` header. * - A server that ignores the range replies with `200 OK` and the full * body. */ /** * Minimal response shape consumed by the range fetcher. A subset of the * standard `Response` interface, declared explicitly so non-`fetch` * transports can be injected. */ interface FetchLikeResponse { /** HTTP status code (e.g. `200`, `206`). */ readonly status: number; /** Response headers accessor. */ readonly headers: { get(name: string): string | null; }; /** Resolve the body as an {@link ArrayBuffer}. */ arrayBuffer(): Promise; } /** * The injectable transport. Compatible with the global `fetch` function * for the subset of features the range fetcher relies on. */ type FetchLike = (url: string, init?: { headers?: Record; }) => Promise; /** * A lazy, range-aware reader over a single remote resource. */ interface RangeFetcher { /** * Fetch the half-open... actually inclusive byte range `[start, end]`. * * @param start - First byte offset (inclusive, >= 0). * @param end - Last byte offset (inclusive, >= start). * @returns The requested bytes as a {@link Uint8Array}. */ fetchRange(start: number, end: number): Promise; /** * Resolve the total length of the resource in bytes. The result is * cached after the first successful probe. */ getLength(): Promise; /** * Determine whether the server supports byte-range requests. The * result is cached after the first probe. */ supportsRanges(): Promise; } /** * Options for {@link createRangeFetcher}. */ interface RangeFetchOptions { /** * Transport used to issue requests. Defaults to `globalThis.fetch` * bound to the global object. */ readonly fetchImpl?: FetchLike | undefined; } /** * Create a {@link RangeFetcher} for the given URL. * * The returned fetcher is stateful: it lazily caches the resource length * and the range-support flag after the first successful probe. * * @param url - Absolute URL of the remote resource. * @param options - Optional {@link RangeFetchOptions}. * @returns A {@link RangeFetcher}. */ declare function createRangeFetcher(url: string, options?: RangeFetchOptions): RangeFetcher; //#endregion //#region src/assets/vdom/reconciler.d.ts /** * A node in the declarative document tree. * * - `document` — the root; contains `page` children (or loose flow * children that are auto-wrapped into a single page). * - `page` — a single physical page; contains flow children. * - `heading` — a bold, larger run of text sized by `level` (1 = largest). * - `text` — a paragraph of body text, wrapped to the content width. * - `spacer` — vertical whitespace of the given `height` in points. */ type VNode = { readonly type: "document"; readonly children: readonly VNode[]; } | { readonly type: "page"; readonly children: readonly VNode[]; } | { readonly type: "heading"; readonly level: number; readonly text: string; } | { readonly type: "text"; readonly text: string; } | { readonly type: "spacer"; readonly height: number; }; /** * Options controlling how a {@link VNode} tree is rendered to PDF. */ interface RenderOptions$1 { /** Base body font size in points. Default: 12. */ readonly fontSize?: number | undefined; /** Page margin in points applied on all four sides. Default: 50. */ readonly margin?: number | undefined; } /** * Construct a well-formed {@link VNode} from a type, a props bag, and * child nodes — a hyperscript-style helper. * * `props` supplies the leaf attributes (`text`, `level`, `height`); the * variadic `children` become the node's children for container types. * Unknown or missing props fall back to sensible defaults. * * @param type The node type to create. * @param props Attribute bag (e.g. `{ text: 'hi', level: 2 }`). * @param children Child nodes for `document` / `page` containers. * @returns A frozen-shaped {@link VNode}. */ declare function h$1(type: VNode["type"], props: Record, ...children: VNode[]): VNode; /** * Reconcile a {@link VNode} tree into a saved PDF document. * * The root is normalized to a list of pages: a `document` contributes its * `page` children directly, while any loose flow children (or a non-page * root) are auto-wrapped into a single page. Within each page, children * flow downward from the top margin; `text` wraps at word boundaries to * the content width and `heading` text is rendered larger and bold. * * @param root The root node to render. * @param options Optional layout overrides. * @returns A promise resolving to the saved PDF bytes (starting `%PDF-`). */ declare function renderToPdf$1(root: VNode, options?: RenderOptions$1): Promise; //#endregion //#region src/compliance/pdfVT.d.ts /** * PDF/VT conformance level (ISO 16612-2). * * - `PDF/VT-1` — self-contained single file (built on PDF/X-4). * - `PDF/VT-2` — may reference external content via PDF/X-5 / external graphics. * - `PDF/VT-3` — streamed variant (PDF/VT-1s) for incremental production. */ type PdfVtConformance = "PDF/VT-1" | "PDF/VT-2" | "PDF/VT-3"; /** * Metadata describing a single variable-data *record*. * * A record spans a contiguous, inclusive range of zero-based page indices and * carries a stable identifier plus optional production fields. */ interface RecordMetadata { /** Zero-based index of the first page in this record (inclusive). */ readonly startPage: number; /** Zero-based index of the last page in this record (inclusive). */ readonly endPage: number; /** Stable record identifier (emitted as `/RecordID`). */ readonly recordId: string; /** * Optional per-record production fields. Each key/value pair is emitted as * a PDF name → literal-string entry inside the record's `/DPM` dictionary. */ readonly fields?: Readonly> | undefined; } /** * Build the VT *Document Part Metadata* (`/DPM`) dictionary for a single record. * * The dictionary carries: * - `/Type /DPM` * - `/S /VT` — selects the VT (variable / transactional) metadata namespace * - `/RecordID` — the record's stable identifier (literal string) * - one literal-string entry per {@link RecordMetadata.fields} pair * * @param record - The record whose metadata to encode. * @returns A spec-shaped VT `/DPM` {@link PdfDict}. */ declare function buildVtDpm(record: RecordMetadata): PdfDict; /** * Build a PDF/VT `/DPartRoot` dictionary from a flat list of records. * * Each record becomes one child `/DPart` node (via {@link buildDPartRoot}), * and that child is augmented with a VT `/DPM` dictionary produced by * {@link buildVtDpm}. The returned structure mirrors {@link buildDPartRoot}: * - `/Type /DPartRoot` * - `/DPartRootNode` → a top `/DPart` node whose `/DParts` array holds one * child `/DPart` per record, each carrying `/Start`, `/End`, and a VT `/DPM`. * * The structure is self-contained: page positions are stored as plain numbers * rather than resolved page references. * * @param records - The variable-data records, in page order. * @returns A spec-shaped PDF/VT `/DPartRoot` {@link PdfDict}. */ declare function buildPdfVtDParts(records: readonly RecordMetadata[]): PdfDict; /** * Map a {@link PdfVtConformance} level to its `GTS_PDFVTVersion` string, the * value placed in the document's XMP / output-intent VT version field. * * @param conformance - The conformance level (defaults to `PDF/VT-1`). * @returns The `GTS_PDFVTVersion` string (e.g. `PDF/VT-1`). */ declare function gtsPdfVtVersion(conformance?: PdfVtConformance): string; //#endregion //#region src/runtime/workerPool.d.ts /** * @module runtime/workerPool * * A small, dependency-free task orchestrator that bounds the number of * concurrently in-flight tasks. It is the scheduling core that would sit * in front of a real `Worker` (or any other async executor) without being * coupled to one: the unit of work is supplied as an injectable * {@link TaskRunner}, so the pool can be exercised in tests with plain * promises and no actual threads. * * Behaviour: * * - At most `concurrency` tasks run at any instant; the remainder wait in * a FIFO queue and start as running slots free up. * - {@link WorkerPool.runAll} preserves input order in its output array * regardless of the order in which individual tasks settle. * - A task that rejects rejects only its own promise. The pool keeps * draining its queue, and sibling tasks continue to resolve normally. */ /** * The unit of work executed by a {@link WorkerPool}. Maps a single input * to a promise of its output. */ type TaskRunner = (input: I) => Promise; /** * Options for {@link createWorkerPool}. */ interface WorkerPoolOptions { /** * Maximum number of tasks allowed to run simultaneously. Defaults to * `globalThis.navigator?.hardwareConcurrency ?? 4`. Must be a positive * integer. */ readonly concurrency?: number | undefined; } /** * A bounded-concurrency task pool. */ interface WorkerPool { /** * Schedule a single input. Resolves with the runner's output, or * rejects with the runner's error. Honours the pool's concurrency * limit, queueing if all slots are busy. */ run(input: I): Promise; /** * Schedule every input, returning the outputs in the **same order** as * the inputs. Rejects if any task rejects, but every task is still * scheduled and the pool stays usable afterwards. */ runAll(inputs: readonly I[]): Promise; /** Number of tasks currently executing (excludes queued tasks). */ readonly activeCount: number; } /** * Create a {@link WorkerPool} backed by the given {@link TaskRunner}. * * @param runner - The async function invoked once per scheduled input. * @param options - Optional {@link WorkerPoolOptions}. * @returns A {@link WorkerPool}. * @throws If `options.concurrency` is provided but is not a positive * integer. */ declare function createWorkerPool(runner: TaskRunner, options?: WorkerPoolOptions): WorkerPool; //#endregion //#region src/signature/externalSigner.d.ts /** * @module signature/externalSigner * * External (HSM / KMS / WebCrypto) deferred-hash signer abstraction. * * This module enables signing flows where the private key never leaves the * signing backend — a Hardware Security Module, a cloud Key Management * Service, or a WebCrypto key handle. The library computes the message * digest, hands that digest to an injected {@link ExternalSigner}, and * receives back the raw signature bytes plus the certificate chain. * * The library itself never sees, holds, or transmits the private key. The * {@link signDeferred} function is pure logic over an injected backend, so it * can be exercised in tests with a mock signer and no real HSM or network. * * @packageDocumentation */ /** * Signature algorithm advertised by an {@link ExternalSigner}. * * This describes the key/signature family used by the backend so callers can * select the appropriate certificate and packaging (e.g. PKCS#7 SignerInfo * algorithm identifiers) downstream. */ type SignatureAlgorithm = "RSA" | "ECDSA" | "Ed25519"; /** * A signing backend whose private key is held externally (HSM / KMS / * WebCrypto). Implementations receive only a message digest and return the * raw signature bytes; the private key never crosses this boundary. */ interface ExternalSigner { /** The signature algorithm family this backend uses. */ readonly algorithm: SignatureAlgorithm; /** * Sign a pre-computed message digest. * * @param digest - The hash of the data to be signed. * @returns The raw signature bytes produced by the backend. */ sign(digest: Uint8Array): Promise; /** * Retrieve the certificate chain associated with the signing key. * * @returns The certificate chain, leaf-first, as DER-encoded byte arrays. */ getCertificateChain(): Promise; } /** * Options controlling a {@link signDeferred} operation. */ interface DeferredSignOptions { /** * The hash algorithm used to digest the data before signing. * * Defaults to `'SHA-256'` when omitted. */ readonly hashAlgorithm?: "SHA-256" | "SHA-384" | "SHA-512" | undefined; } /** * The result of a {@link signDeferred} operation. */ interface DeferredSignResult { /** The digest of the input data that was handed to the signer. */ readonly digest: Uint8Array; /** The raw signature bytes returned by the external signer. */ readonly signature: Uint8Array; /** The certificate chain returned by the external signer, leaf-first. */ readonly certificateChain: Uint8Array[]; } /** * Perform a deferred-hash signing operation against an external signer. * * The data is digested locally with {@link crypto.subtle.digest}; the * resulting digest is handed to {@link ExternalSigner.sign}, and the * certificate chain is collected from {@link ExternalSigner.getCertificateChain}. * The library never has access to the private key. * * @param data - The bytes to be signed. * @param signer - The external signing backend. * @param options - Optional configuration; see {@link DeferredSignOptions}. * @returns The digest, the raw signature, and the certificate chain. */ declare function signDeferred(data: Uint8Array, signer: ExternalSigner, options?: DeferredSignOptions): Promise; //#endregion //#region src/assets/font/woff.d.ts /** * Parsed summary of a WOFF / WOFF2 file header. */ interface WoffInfo { /** The container signature: `'wOFF'` (WOFF1) or `'wOF2'` (WOFF2). */ readonly signature: "wOFF" | "wOF2"; /** The wrapped sfnt flavor (e.g. `0x00010000` for TrueType, `OTTO`). */ readonly flavor: number; /** Number of font tables contained in the file. */ readonly numTables: number; /** Size in bytes of the reconstructed (uncompressed) sfnt font. */ readonly totalSfntSize: number; } /** * Test whether `data` begins with the WOFF1 signature `wOFF`. */ declare const isWoff: (data: Uint8Array) => boolean; /** * Test whether `data` begins with the WOFF2 signature `wOF2`. */ declare const isWoff2: (data: Uint8Array) => boolean; /** * Parse the header of a WOFF1 or WOFF2 file. * * @param data - The font container bytes. * @returns A {@link WoffInfo} describing the container. * @throws If the data is too small or carries an unrecognised signature. */ declare function readWoffHeader(data: Uint8Array): WoffInfo; /** * Decode a WOFF1 container into the raw sfnt (TrueType / OpenType) font. * * Each table's data is zlib-inflated when its compressed length differs * from its original length, or copied verbatim otherwise. The output is a * standard sfnt: a 12-byte offset table, 16-byte table records sorted by * tag, and 4-byte-aligned table data. * * @param data - The WOFF1 (or WOFF2) container bytes. * @returns The reconstructed raw sfnt bytes. * @throws `'WOFF2 decode not yet supported'` for WOFF2 input, or a * descriptive error when a WOFF1 container is malformed. */ declare function decodeWoff(data: Uint8Array): Uint8Array; //#endregion //#region src/parser/jpeg2000Tiles.d.ts /** * @module parser/jpeg2000Tiles * * Tiled decoding for JPEG2000 (JP2 / J2K) images. * * JPEG2000 supports partitioning an image into rectangular tiles that can * be independently decoded. This is critical for: * * - Large images (satellite, medical) where decoding the entire image is * impractical or unnecessary. * - Region-of-interest access — decode only the tiles that intersect the * requested viewport. * - Parallel / streaming decode — tiles are independent units. * * The tile grid is defined by the SIZ marker (ITU-T T.800, Annex A.5.1), * and individual tiles are delimited by SOT (Start of Tile-Part) markers * within the codestream. * * Reference: ITU-T T.800 (ISO/IEC 15444-1), Annexes A and B. * * @packageDocumentation */ /** * Tile grid geometry extracted from the SIZ marker. */ interface TileGridInfo { /** Full image width in pixels. */ imageWidth: number; /** Full image height in pixels. */ imageHeight: number; /** Nominal tile width. */ tileWidth: number; /** Nominal tile height. */ tileHeight: number; /** Number of tiles in the horizontal direction. */ tilesX: number; /** Number of tiles in the vertical direction. */ tilesY: number; /** Tile grid origin X offset. */ originX: number; /** Tile grid origin Y offset. */ originY: number; /** Number of image components. */ components: number; /** Bits per component (from the first component's Ssiz entry). */ bitsPerComponent: number; } /** * Decoded data for a single tile. */ interface TileData { /** Zero-based tile index (row-major order). */ index: number; /** Pixel X coordinate of the tile's top-left corner in the image. */ x: number; /** Pixel Y coordinate of the tile's top-left corner in the image. */ y: number; /** Tile width in pixels (may be smaller for rightmost / bottom tiles). */ width: number; /** Tile height in pixels (may be smaller for rightmost / bottom tiles). */ height: number; /** Decoded pixel data for this tile (interleaved components, row-major). */ data: Uint8Array; /** Number of components in the tile data. */ components: number; } /** * A rectangular region used for region-of-interest decoding. */ interface Region { x: number; y: number; width: number; height: number; } /** * Parse the SIZ marker to extract tile grid geometry. * * @param data - A JPEG2000 codestream (raw J2K) or JP2 file. * @returns The tile grid information. * @throws If the SIZ marker cannot be found or is truncated. */ declare function parseTileInfo(data: Uint8Array): TileGridInfo; /** * Decode a single tile from a JPEG2000 codestream. * * This extracts the tile data for the given tile index by locating its * SOT marker(s) in the codestream. The actual decoding produces * uncompressed pixel data for that tile. * * Note: Full wavelet / entropy decoding of JPEG2000 tile data is * extremely complex. This implementation provides the tile extraction * and framing layer. For production use, the WASM bridge should be * used for the actual decompression. When WASM is not available, this * returns a zero-filled buffer matching the tile dimensions (useful for * layout / testing purposes). * * @param data - Full JPEG2000 codestream or JP2 file bytes. * @param tileIndex - Zero-based tile index (row-major order). * @returns Decoded tile data. * @throws If the tile index is out of range or the codestream is invalid. */ declare function decodeTile(data: Uint8Array, tileIndex: number): TileData; /** * Decode only the tiles that intersect the given rectangular region. * * This is the key API for efficient region-of-interest decoding — only * tiles overlapping the requested region are decoded, which can save * significant time for large tiled images. * * The returned data covers exactly the requested region, cropped from * the relevant tiles. * * @param data - Full JPEG2000 codestream or JP2 file bytes. * @param region - The rectangular region to decode. * @returns Decoded pixel data covering the requested region. * @throws If the region is entirely outside the image bounds. */ declare function decodeTileRegion(data: Uint8Array, region: Region): Uint8Array; /** * Assemble an array of decoded tiles into a full (or partial) image. * * The tiles are placed onto a canvas matching the full image dimensions * described by `gridInfo`. Missing tiles result in zero-filled regions. * * @param tiles - Array of decoded tile data. * @param gridInfo - The tile grid geometry from {@link parseTileInfo}. * @returns A `Uint8Array` containing the assembled image pixels * (interleaved components, row-major order). */ declare function assembleTiles(tiles: TileData[], gridInfo: TileGridInfo): Uint8Array; //#endregion //#region src/parser/jpeg2000BitDepth.d.ts /** * @module parser/jpeg2000BitDepth * * 16-bit and variable bit depth support for JPEG2000 (JP2 / J2K) images. * * JPEG2000 supports per-component bit depths from 1 to 38 bits, with both * signed and unsigned representations. Medical imaging (DICOM), satellite * imagery, and scientific data frequently use 12-bit or 16-bit components. * * This module provides utilities to: * - Parse the SIZ marker to extract per-component bit depth information * - Convert between different bit depths (e.g. 16-bit to 8-bit) * - Handle signed components by offsetting to unsigned range * * Reference: ITU-T T.800 (ISO/IEC 15444-1), Annex A — SIZ marker segment. * * @packageDocumentation */ /** * Per-component bit depth information extracted from a JPEG2000 SIZ marker. */ interface BitDepthInfo { /** Number of bits per component sample. */ bitsPerComponent: number; /** Whether the component values are signed (two's complement). */ isSigned: boolean; /** Total number of image components. */ components: number; } /** * Detailed per-component depth descriptor returned by * {@link getComponentDepths}. */ interface ComponentDepth { /** Bit depth for this component (1–38). */ bits: number; /** Whether the component is signed. */ isSigned: boolean; } /** * Parse the SIZ marker to extract per-component bit depth information. * * The SIZ marker segment stores the component count followed by one byte * per component describing its bit depth and signedness: * * - Bits 0–6: depth minus one (i.e. value 7 means 8 bits) * - Bit 7: 1 = signed, 0 = unsigned * * @param sizMarker - A `Uint8Array` containing at least the SIZ marker * segment. May be a full JP2/J2K codestream — the SIZ is located * automatically. * @returns An array of per-component depth descriptors. * @throws If the SIZ marker cannot be found or is truncated. */ declare function getComponentDepths(sizMarker: Uint8Array): ComponentDepth[]; /** * Downscale component data from a higher bit depth (>8) to 8-bit. * * Uses linear scaling: `out = round(value * 255 / maxValue)`. * For signed components, the values are first offset by `2^(bits-1)` to * produce unsigned values in the range `[0, 2^bits - 1]`. * * @param data - Source samples. For depths <= 8, each sample occupies * one byte. For depths 9–16, each sample occupies two bytes (big-endian). * @param bitsPerComponent - The source bit depth (must be > 8, up to 16). * @returns A new `Uint8Array` with one byte per sample, scaled to [0, 255]. */ declare function downscale16To8(data: Uint8Array, bitsPerComponent: number): Uint8Array; /** * Upscale 8-bit component data to 16-bit. * * Each 8-bit sample is expanded to a 16-bit value using the formula * `out = value * 257` (which maps 0→0 and 255→65535 exactly) and * stored as big-endian two-byte pairs. * * @param data - Source 8-bit samples. * @returns A new `Uint8Array` of length `data.length * 2`, big-endian 16-bit. */ declare function upscale8To16(data: Uint8Array): Uint8Array; /** * Generic bit-depth normalizer. Converts component sample data from an * arbitrary source depth to an arbitrary target depth. * * Handles signed source data by offsetting before scaling. The output is * always unsigned. * * Supports depths from 1 to 16. Source data is expected in big-endian * byte order when the depth exceeds 8 bits (2 bytes per sample). Output * follows the same convention. * * @param data - Source sample bytes. * @param fromBits - Source bit depth (1–16). * @param toBits - Target bit depth (1–16). * @returns A new `Uint8Array` with samples at the target depth. */ declare function normalizeComponentDepth(data: Uint8Array, fromBits: number, toBits: number): Uint8Array; /** * Offset signed component samples to unsigned range. * * For signed data with `N` bits, the offset is `2^(N-1)`. For example, * a signed 16-bit value of −32768 becomes 0 and +32767 becomes 65535. * * @param data - Source sample bytes (big-endian for >8 bits). * @param bitsPerComponent - Component bit depth. * @returns A new `Uint8Array` with the offset applied. */ declare function offsetSignedToUnsigned(data: Uint8Array, bitsPerComponent: number): Uint8Array; /** * Create a {@link BitDepthInfo} summary from component depth descriptors. * * If all components share the same bit depth and signedness, the result * uses those values. Otherwise, the maximum bit depth and the logical * OR of all signed flags are used. * * @param depths - Per-component depth descriptors from * {@link getComponentDepths}. * @returns A summary object. */ declare function summarizeBitDepth(depths: ComponentDepth[]): BitDepthInfo; //#endregion //#region src/layout/textLayout.d.ts /** A rectangular region within which text can be laid out. */ interface TextFrame { x: number; y: number; width: number; height: number; } /** Text alignment mode. */ type TextAlignment = "left" | "right" | "center" | "justify"; /** A span of text with optional styling overrides. */ interface TextSpan { text: string; font?: FontRef | string; fontSize?: number; color?: Color; bold?: boolean; italic?: boolean; underline?: boolean; strikethrough?: boolean; superscript?: boolean; subscript?: boolean; } /** Options controlling paragraph layout. */ interface ParagraphOptions { alignment?: TextAlignment; lineHeight?: number; paragraphSpacing?: number; firstLineIndent?: number; hangingIndent?: number; hyphenation?: boolean; hyphenChar?: string; locale?: string; orphanLines?: number; widowLines?: number; } /** Options for multi-column layout. */ interface MultiColumnOptions { columns: number; columnGap?: number; columnRule?: { width: number; color: Color; style: "solid" | "dashed"; }; balanceColumns?: boolean; } /** Result of a text layout operation. */ interface TextLayoutResult { /** Content stream operators for the laid-out text. */ operators: string; /** Number of lines rendered. */ lineCount: number; /** Remaining text that didn't fit in the frame(s). */ overflow: string; /** Y position after the last line (for continuation). */ lastY: number; /** Actual height used. */ usedHeight: number; } /** * Find possible hyphenation points for a word. * Returns an array of split positions (character indices where a hyphen * could be inserted *before* the character at that index). */ declare function findHyphenationPoints(word: string, _locale?: string): number[]; /** * Lay out a paragraph of text in a frame with full typographic control. * * Accepts plain text or an array of styled {@link TextSpan} objects. * Performs word wrapping, alignment, optional hyphenation, and * widow/orphan control. * * @param spans The text content, as a plain string or styled spans. * @param frame The rectangular frame to lay text into. * @param options Paragraph layout options (alignment, hyphenation, etc.). * @param measureFn Optional text measurement function. If omitted, a * character-count heuristic is used. * @returns A {@link TextLayoutResult} with operators and overflow. */ declare function layoutParagraph(spans: TextSpan[] | string, frame: TextFrame, options?: ParagraphOptions, measureFn?: (text: string, font: string, size: number) => number): TextLayoutResult; /** * Lay out text across multiple columns within a frame. * * Divides the frame into equal-width columns separated by gaps, * then flows text sequentially through each column. Optionally * draws column rules (vertical lines between columns) and balances * column heights. * * @param spans The text content. * @param frame The outer frame containing all columns. * @param columnOptions Number of columns, gap, rule, balancing. * @param paragraphOptions Paragraph-level options. * @param measureFn Optional text measurement function. * @returns A combined {@link TextLayoutResult}. */ declare function layoutColumns(spans: TextSpan[] | string, frame: TextFrame, columnOptions: MultiColumnOptions, paragraphOptions?: ParagraphOptions, measureFn?: (text: string, font: string, size: number) => number): TextLayoutResult; /** * Lay out text across multiple frames (for multi-page flow). * * Text flows from one frame to the next, with each frame producing * its own {@link TextLayoutResult}. Useful for flowing a long body of * text across multiple pages. * * @param spans The text content. * @param frames Array of frames to fill in order. * @param options Paragraph-level options. * @param measureFn Optional text measurement function. * @returns An array of results, one per frame used. */ declare function layoutTextFlow(spans: TextSpan[] | string, frames: TextFrame[], options?: ParagraphOptions, measureFn?: (text: string, font: string, size: number) => number): TextLayoutResult[]; //#endregion //#region src/signature/cadesAttributes.d.ts /** * Build the ESS `signing-certificate-v2` signed attribute (RFC 5035). * * The returned bytes are a complete DER-encoded `Attribute` SEQUENCE * suitable for insertion into the CMS `SignedAttributes` SET. * * Encoding rules applied (verified against RFC 5035): * - `hashAlgorithm` is OMITTED when `hashAlgorithm === 'SHA-256'` (the * `DEFAULT {algorithm id-sha256}`), and INCLUDED for SHA-384/SHA-512. * - `certHash` is `subtle.digest(hashAlgorithm, )`. * - `issuerSerial` and `policies` are OPTIONAL and omitted. * * @param certDer The DER-encoded X.509 signer certificate. * @param hashAlgorithm The digest used for `certHash`. * @returns DER-encoded `Attribute` SEQUENCE. */ declare function buildSigningCertificateV2Attribute(certDer: Uint8Array, hashAlgorithm: "SHA-256" | "SHA-384" | "SHA-512"): Promise; /** * Best-effort DER scan for the `signing-certificate-v2` attribute inside * an encoded `SignedAttributes` SET (or any SET/SEQUENCE OF Attribute). * * When found, the embedded `certHash` OCTET STRING is returned so callers * can compare it against the signer certificate's digest. * * This walks: SET -> Attribute SEQUENCE { OID, SET { SigningCertificateV2 * SEQUENCE { certs SEQUENCE OF { ESSCertIDv2 SEQUENCE { [algId], certHash } } } } }. * * @param signedAttrsDer DER bytes of a SET (or constructed container) of Attributes. * @returns `{ present, certHash? }`. */ declare function extractSigningCertificateV2(signedAttrsDer: Uint8Array): { present: boolean; certHash?: Uint8Array | undefined; }; //#endregion //#region src/signature/certPathBuilder.d.ts /** * Result of building a certification path. */ interface CertPathResult { /** * The ordered certificates, leaf-first, **excluding** the trust anchor. * For a self-signed leaf that is itself an anchor, this is `[leaf]`. */ path: Uint8Array[]; /** * `true` when the path terminates at a member of `anchors`; * `false` when no issuer could be found (partial path). */ complete: boolean; /** * The DER-encoded trust anchor the path terminates at, when `complete`. * Reported separately from `path`. `undefined` for incomplete paths. */ anchor?: Uint8Array | undefined; } /** * Build an ordered certification path from a leaf certificate to a trust * anchor per RFC 5280 §6.1. * * @param leafCertDer DER-encoded end-entity (leaf) certificate. * @param intermediates DER-encoded intermediate CA certificates (any order). * @param anchors DER-encoded trust anchors (root or directly-trusted CAs). * @returns {@link CertPathResult} — `path` is leaf-first and * excludes the anchor; `anchor` is reported separately * when the path is `complete`. * * @example * ```ts * const { path, complete, anchor } = buildCertPath(leaf, [intermediate], [root]); * // path = [leaf, intermediate], complete = true, anchor = root * ``` */ declare function buildCertPath(leafCertDer: Uint8Array, intermediates: readonly Uint8Array[], anchors: readonly Uint8Array[]): CertPathResult; //#endregion //#region src/security/threatScanner.d.ts /** Relative severity of a detected construct. */ type ThreatSeverity = "low" | "medium" | "high"; /** A single detected hostile/dangerous construct. */ interface ThreatFinding { /** Stable category label (e.g. `"OpenAction"`, `"JavaScript"`). */ category: string; /** Justified severity for this construct. */ severity: ThreatSeverity; /** Human-readable description of what was found and why it matters. */ detail: string; /** Indirect-object reference (`"12 0 R"`) when the finding is object-scoped. */ objectRef?: string | undefined; } /** Aggregated scan result. */ interface ThreatReport { /** All findings, in discovery order. */ findings: ThreatFinding[]; /** Maximum severity across {@link findings}, or `'none'` when empty. */ riskLevel: ThreatSeverity | "none"; } /** * Scan a PDF for hostile constructs and return a {@link ThreatReport}. * * The scan never executes any document content. It parses the PDF and walks * the parsed object graph (see the module header for the precise method and * ISO 32000 references). When parsing fails, a guarded raw-byte fallback runs. * * @param pdf Raw PDF bytes. * @returns A report of findings plus the aggregate `riskLevel`. */ declare function scanPdfThreats(pdf: Uint8Array): Promise; //#endregion //#region src/security/sanitize.d.ts /** * Options controlling which classes of content the sanitizer removes. * * Every flag defaults to `true` — i.e. by default all four classes are * stripped. Set a flag to `false` to preserve that class. */ interface SanitizeOptions { /** Remove document JavaScript (`/Names /JavaScript` + `/AA`). Default `true`. */ javascript?: boolean | undefined; /** Remove the auto-run `/OpenAction`. Default `true`. */ openActions?: boolean | undefined; /** Remove embedded files (`/Names /EmbeddedFiles` + `/AF`). Default `true`. */ embeddedFiles?: boolean | undefined; /** Strip the XMP `/Metadata` stream + the `/Info` dictionary. Default `true`. */ metadata?: boolean | undefined; } /** Identifies a class of content that the sanitizer can remove. */ type SanitizeClass = "javascript" | "openActions" | "embeddedFiles" | "metadata"; /** A human-readable summary of what {@link sanitizePdf} actually removed. */ interface SanitizeReport { /** * The classes of content that were present in the source PDF and have * been removed. Only classes that were actually present (and enabled) * appear here — a clean document yields an empty array. */ removed: SanitizeClass[]; } /** * Produce a cleaned copy of a PDF with active / hidden content neutralised. * * Loads the PDF, removes each enabled class of content from the parsed * object graph, prunes the orphaned objects, re-serializes the cleaned * document, and returns the new bytes alongside a report listing the * classes that were actually present and removed. * * @param pdf The source PDF bytes. * @param options Which classes to remove (each defaults to `true`). * @returns The cleaned PDF bytes and a {@link SanitizeReport}. * * @example * ```ts * const { pdf, report } = await sanitizePdf(bytes); * // report.removed === ['javascript', 'embeddedFiles', 'metadata'] * ``` */ declare function sanitizePdf(pdf: Uint8Array, options?: SanitizeOptions): Promise<{ pdf: Uint8Array; report: SanitizeReport; }>; //#endregion //#region src/security/redactionVerifier.d.ts /** * A rectangular region to check for redaction leaks. * * Coordinates are in PDF user space: origin bottom-left, y-up, units in PDF * points. `(x, y)` is the **lower-left** corner; `width` and `height` extend * in the +x and +y directions. This is the same convention as `RedactRect` * in `../render/redactContent.js`. */ interface RedactionRegion { /** Zero-based page index this region applies to. */ page: number; /** X coordinate of the lower-left corner, in PDF points. */ x: number; /** Y coordinate of the lower-left corner, in PDF points. */ y: number; /** Width of the region in PDF points (must be > 0 to match anything). */ width: number; /** Height of the region in PDF points (must be > 0 to match anything). */ height: number; } /** * A single piece of text found still present under a redaction region — i.e. a * redaction that did not actually remove the underlying content. */ interface RedactionLeak { /** Zero-based page index where the leak was found. */ page: number; /** The still-extractable text (decoded to Unicode). */ text: string; /** Text-origin X of the leaking run (bottom-left, y-up), in PDF points. */ x: number; /** Text-origin Y of the leaking run (bottom-left, y-up), in PDF points. */ y: number; } /** The outcome of a {@link verifyRedactions} call. */ interface RedactionVerificationReport { /** Every text run found still present under a region. */ leaks: RedactionLeak[]; /** True iff {@link leaks} is empty (no failed redactions detected). */ clean: boolean; /** Number of regions that were checked. */ regionsChecked: number; } /** * Verify that the given regions of a PDF contain no still-extractable text, * detecting fake / failed redactions. * * For each region, the corresponding page's text is extracted with positions * and any text run whose bounding box intersects the region is reported as a * {@link RedactionLeak}. A clean result means no text was found under any * region (the redactions truly removed the content, or there was none to begin * with). * * @param pdf The PDF file bytes to inspect. * @param regions The regions to check (REQUIRED — see the module docs for why * automatic region detection is not performed). Coordinates are * in PDF user space: origin bottom-left, y-up, units in points; * `(x, y)` is the lower-left corner. * @returns A report listing every leak; `clean` is true iff there are * none. * @throws `TypeError` if `regions` is omitted or empty. * * @example * ```ts * const report = await verifyRedactions(pdfBytes, [ * { page: 0, x: 45, y: 545, width: 120, height: 25 }, * ]); * if (!report.clean) { * for (const leak of report.leaks) { * console.warn(`Leak on page ${leak.page}: "${leak.text}"`); * } * } * ``` */ declare function verifyRedactions(pdf: Uint8Array, regions?: readonly RedactionRegion[]): Promise; //#endregion //#region src/security/encryptionInspector.d.ts /** * Decoded `/P` permission flags (ISO 32000-1:2008 Table 22). * * Each flag is `true` when the corresponding capability is **granted** * by the document's permission integer. */ interface PermissionFlags { /** Bit 3: print the document (possibly only low resolution). */ print: boolean; /** Bit 4: modify the contents of the document. */ modify: boolean; /** Bit 5: copy or otherwise extract text and graphics. */ copy: boolean; /** Bit 6: add or modify text annotations / fill in form fields. */ annotate: boolean; /** Bit 9: fill in existing interactive form fields. */ fillForms: boolean; /** Bit 5: extract text and graphics (alias of {@link copy}, Table 22). */ extract: boolean; /** Bit 11: assemble the document (insert/rotate/delete pages). */ assemble: boolean; /** Bit 12: print to a high-resolution representation. */ printHighRes: boolean; } /** * A report describing a PDF's encryption + permission posture. * * When `encrypted` is `false` all other fields are absent. */ interface EncryptionReport { /** Whether the trailer references an `/Encrypt` dictionary. */ encrypted: boolean; /** The bulk cipher: `'rc4'` or `'aes'` (omitted if undeterminable). */ method?: "rc4" | "aes" | undefined; /** Key length in bits (40, 128, or 256). */ keyBits?: number | undefined; /** The `/V` algorithm version. */ version?: number | undefined; /** The `/R` standard-security-handler revision. */ revision?: number | undefined; /** The security handler: `'password'` (/Standard) or `'publicKey'`. */ handler?: "password" | "publicKey" | undefined; /** * Best-effort: whether the document opens with an **empty** user * password (the common "owner-only protection" case). Only set for * the standard password handler; omitted when it cannot be tested. */ emptyUserPassword?: boolean | undefined; /** Decoded `/P` permission flags (standard handler only). */ permissions?: PermissionFlags | undefined; } /** * Inspect a PDF's encryption + permission posture. * * @param pdf The raw PDF file bytes. * @returns A {@link EncryptionReport}. If the trailer has no * `/Encrypt` entry (or the file is unparseable) the report is * `{ encrypted: false }`. */ declare function inspectEncryption(pdf: Uint8Array): Promise; //#endregion //#region src/text/bidi.d.ts /** * @module text/bidi * * The Unicode Bidirectional Algorithm (UAX #9) for laying out mixed * left-to-right / right-to-left text. * * Reference: Unicode Standard Annex #9, "Unicode Bidirectional Algorithm", * revision 49 (Unicode 16.0.0). The rule labels referenced throughout this * file (P2/P3, X1–X10, W1–W7, N0–N2, I1/I2, L1/L2) are the rule numbers from * that document: https://www.unicode.org/reports/tr9/ * * ## Scope and conformance * * This implements the full structural pipeline of UAX #9: * - P2/P3 paragraph base level (or an explicit / first-strong base), * - X1–X8 explicit embeddings & overrides (LRE/RLE/LRO/RLO/PDF), * - X5a–X6a directional isolates (LRI/RLI/FSI/PDI), * - X9/X10 removal of formatting characters and isolating run sequences, * - W1–W7 weak-type resolution, * - N0 paired brackets, N1/N2 neutral resolution, * - I1/I2 implicit level resolution, * - L1 reset of trailing/segment whitespace to the paragraph level, * - L2 reordering of the resolved levels into visual order. * * The one deliberate simplification is the **Bidi_Class lookup table**: rather * than embedding the entire ~150 KB Unicode Character Database, this module * uses a COMPACT, RANGE-BASED classifier (see {@link bidiClass}) covering the * code points that matter in practice for PDF text layout — Latin, Hebrew * (U+0590–05FF), Arabic (U+0600–06FF, U+0750–077F), the Arabic-Indic and * European digit groups, common neutrals/weaks, and every explicit-format and * isolate-format character. Code points outside the covered ranges default to * the rule-conformant fallbacks Unicode assigns to unassigned blocks (`R`/`AL` * for the Hebrew/Arabic/Thaana/Syriac default-RTL ranges, otherwise `L`). The * paired-bracket data for N0 likewise covers the ASCII and common typographic * bracket pairs rather than the full BidiBrackets.txt file. * * Because the class table is a curated subset (not the full UCD), this module * does NOT claim blanket UBA conformance for arbitrary Unicode input; it is * correct for the covered scripts and degrades to the standard default classes * elsewhere. The algorithm itself is the complete UAX #9 procedure. * * Pure logic — no Buffer, no fs, no require(); ESM only. */ /** Requested or resolved base direction for a paragraph. */ type BidiDirection = "ltr" | "rtl" | "auto"; /** * A maximal contiguous slice of the input that shares a single resolved * embedding level (and therefore a single visual direction). */ interface BidiRun { /** The logical-order substring covered by this run. */ text: string; /** Resolved embedding level (even = LTR, odd = RTL). */ level: number; /** Visual direction implied by the level's parity. */ direction: "ltr" | "rtl"; /** UTF-16 index into the original string where this run starts. */ start: number; /** Length of this run in UTF-16 code units. */ length: number; } /** Result of {@link resolveBidi}. */ interface BidiResult { /** Same-level runs in logical order, partitioning the whole string. */ runs: BidiRun[]; /** Resolved embedding level for every UTF-16 code unit of the input. */ levels: number[]; /** * Visual order: `visualOrder[v]` is the logical index of the code unit that * should be painted at visual position `v` (left to right). */ visualOrder: number[]; /** Resolved paragraph embedding level (0 = LTR, 1 = RTL). */ baseLevel: number; } /** * Run the Unicode Bidirectional Algorithm (UAX #9) over `text`. * * Indices in the result refer to UTF-16 code units of the input string (the * same units JavaScript's `string[i]` and `.length` use). Astral characters * (surrogate pairs) are classified by their scalar value but occupy two code * units, both assigned the same level. * * @param text The logical-order input string. * @param base Paragraph direction: `'ltr'` / `'rtl'` force the base level; * `'auto'` (the default) derives it from the first strong character (P2/P3). * @returns The resolved levels, same-level runs, visual order and base level. */ declare function resolveBidi(text: string, base?: BidiDirection): BidiResult; /** * Convenience wrapper that returns `text` reordered into visual (left-to-right) * order via {@link resolveBidi}'s L2 result. * * Note: this performs pure reordering of code units. It does not apply Arabic * cursive shaping or mirror neutral glyphs; callers that need shaped glyphs * should pass the resolved runs to a shaping engine. * * @param text The logical-order input string. * @param base Paragraph direction (see {@link resolveBidi}). * @returns The visually reordered string. */ declare function reorderVisual(text: string, base?: BidiDirection): string; //#endregion //#region src/assets/font/variableFont.d.ts /** * @module assets/font/variableFont * * OpenType variable-font axis/instance model parsing — the 'fvar' (font * variations) and 'avar' (axis variations) tables. * * This module exposes the *variation model* of an OpenType variable font: * - the design-variation axes ('fvar' VariationAxisRecord array), * - the named instances ('fvar' InstanceRecord array), * - coordinate normalization from user scale to the normalized [-1, 0, +1] * scale, optionally refined by an 'avar' segment map. * * SCOPE NOTE — explicitly OUT OF SCOPE for this module: * Actual glyph-outline instancing (baking 'gvar'/'cvar' deltas into a static * font at a chosen coordinate, or interpolating 'glyf' outlines) is NOT * performed here. This module only models axes/instances and normalizes * coordinates, which is the foundation those operations build on. * * NAME RESOLUTION NOTE: * The human-readable axis/instance names live in the 'name' table. Decoding * them is optional per the task; this module does NOT resolve them and leaves * `name` undefined, preserving the numeric name IDs (`axisNameID` / * `subfamilyNameID` / `postScriptNameID`) so a caller can resolve them later. * * Spec references (OpenType 1.9.1, Microsoft Typography): * - 'fvar': https://learn.microsoft.com/en-us/typography/opentype/spec/fvar * - 'avar': https://learn.microsoft.com/en-us/typography/opentype/spec/avar * - Data types (Fixed, F2DOT14, Tag, Offset16): * https://learn.microsoft.com/en-us/typography/opentype/spec/otff#data-types * - Normalization pseudocode: * https://learn.microsoft.com/en-us/typography/opentype/spec/otvaroverview#coordinate-scales-and-normalization * * No external dependencies. No Buffer — Uint8Array + DataView only. Big-endian. */ /** * A single design-variation axis from the 'fvar' VariationAxisRecord. * * Coordinate values (`minValue`, `defaultValue`, `maxValue`) are in *user * scale* (the scale specific to the axis tag, e.g. 100..900 for 'wght'). */ interface VariationAxis { /** Four-character axis tag, e.g. 'wght', 'wdth', 'ital', 'opsz', 'slnt'. */ tag: string; /** Minimum user-scale coordinate value. */ minValue: number; /** Default user-scale coordinate value (the default instance). */ defaultValue: number; /** Maximum user-scale coordinate value. */ maxValue: number; /** * Human-readable axis name resolved from the 'name' table via `axisNameID`. * Not resolved by this module — always `undefined` here. */ name?: string | undefined; /** Axis qualifier flags. Bit 0 (0x0001) = HIDDEN_AXIS; others reserved. */ flags: number; } /** * A named instance (named design position) from an 'fvar' InstanceRecord. */ interface NamedInstance { /** * Human-readable subfamily name resolved from the 'name' table via `nameId`. * Not resolved by this module — always `undefined` here. */ name?: string | undefined; /** Axis tag → user-scale coordinate for this instance. */ coordinates: Record; /** The 'name' table name ID for this instance's subfamily name. */ nameId: number; /** * Optional 'name' table name ID for this instance's PostScript name. * Present only when the font's InstanceRecord size includes it * (instanceSize == axisCount*4 + 6). A value of 0xFFFF means "ignore" * and is normalized to `undefined`. */ postScriptNameId?: number | undefined; } /** * A single 'avar' segment map for one axis: an ordered list of * (fromCoordinate, toCoordinate) pairs in normalized [-1, 1] space. */ type AvarSegmentMap = ReadonlyArray<{ /** Default-normalized input coordinate (F2DOT14, in [-1, 1]). */fromCoordinate: number; /** Modified normalized output coordinate (F2DOT14, in [-1, 1]). */ toCoordinate: number; }>; /** * The parsed variable-font model. */ interface VariableFontInfo { /** True iff the font has an 'fvar' table with at least one axis. */ isVariable: boolean; /** The design-variation axes, in 'fvar' order. */ axes: VariationAxis[]; /** The named instances, in 'fvar' order. */ namedInstances: NamedInstance[]; /** * Parsed 'avar' segment maps, one per axis in 'fvar' order, if an 'avar' * table is present and well-formed. Undefined when there is no 'avar' table. */ avar?: AvarSegmentMap[] | undefined; } /** * Parse the variable-font model from raw OpenType/TrueType font bytes. * * If the font has no 'fvar' table (or it is malformed / has zero axes), the * font is treated as non-variable and * `{ isVariable: false, axes: [], namedInstances: [] }` is returned. * * @param fontData Raw font file bytes (sfnt: TrueType 0x00010000 or 'OTTO' CFF). * @returns The parsed {@link VariableFontInfo}. */ declare function parseVariableFont(fontData: Uint8Array): VariableFontInfo; /** * Normalize a user-scale coordinate for an axis to the normalized [-1, 0, +1] * scale, per the OpenType default-normalization algorithm. * * Steps: * 1. Clamp `userValue` to the axis's [minValue, maxValue]. * 2. Map to normalized space: minValue→-1, defaultValue→0, maxValue→+1, with * linear interpolation on each side of the default (note: the slopes on the * two sides differ unless the default is exactly centered). * 3. If an 'avar' `segmentMap` is supplied, apply it to the result; otherwise * no avar adjustment is made (the caller can pass `info.avar[axisIndex]`). * * @param axis The axis whose user-scale bounds define the normalization. * @param userValue The user-scale coordinate (e.g. 250 for a 'wght' axis). * @param avar Optional 'avar' segment map for this axis. * @returns The normalized coordinate in [-1, 1]. */ declare function normalizeAxisCoordinate(axis: VariationAxis, userValue: number, avar?: AvarSegmentMap | undefined): number; /** * Resolve a named instance's coordinates against the font's axes. * * Produces a complete axis-tag → user-scale-coordinate map covering every axis * in the font: any axis the instance does not specify is filled with that * axis's `defaultValue`, and any specified coordinate is clamped to the axis's * [minValue, maxValue] range (per the fvar "Variation Instance Selection" * rules). Coordinates for tags not present on any axis are ignored. * * @param info The parsed variable-font model. * @param instance The named instance to resolve. * @returns A validated axis-tag → user-scale coordinate map. */ declare function resolveInstanceCoordinates(info: VariableFontInfo, instance: NamedInstance): Record; //#endregion //#region src/assets/font/colorFont.d.ts /** * A resolved COLR layer: the outline glyph id, the CPAL palette-entry index, * and the RGBA color (0..255 per channel) that index resolves to in the * selected palette. */ interface ColorGlyphLayer { /** The glyph id of the outline drawn for this layer. */ glyphId: number; /** The CPAL palette-entry index used to color this layer. */ paletteIndex: number; /** Resolved color as [r, g, b, a], each 0..255. */ rgba: [number, number, number, number]; } /** A single CPAL palette: an ordered list of RGBA colors (0..255 per channel). */ interface CpalPalette { /** Palette entries as [r, g, b, a], each 0..255. */ colors: [number, number, number, number][]; } /** Summary of a font's color capability and its CPAL palettes. */ interface ColorFontInfo { /** True if the font contains a 'COLR' table (i.e. has color glyphs). */ hasColor: boolean; /** Number of palettes in the 'CPAL' table (0 if no CPAL table). */ numPalettes: number; /** The parsed CPAL palettes (empty if no CPAL table). */ palettes: CpalPalette[]; } /** * Parse a font's color capability and CPAL palettes. * * `hasColor` is true iff the font contains a 'COLR' table. The palettes come * from the 'CPAL' table (which is required whenever 'COLR' is present, per the * OpenType spec). Color records are returned as RGBA (converted from the on-disk * BGRA layout). * * @param fontData - Raw sfnt font bytes (TrueType 0x00010000 or 'OTTO'). * @returns Color info; `{ hasColor: false, numPalettes: 0, palettes: [] }` if * the font has no COLR/CPAL tables or cannot be parsed. */ declare function parseColorFont(fontData: Uint8Array): ColorFontInfo; /** * Resolve the COLR v0 layers of a base glyph into colored layers. * * For each layer of the requested base glyph, the layer's outline glyph id is * returned together with its CPAL palette-entry index and the RGBA color that * index resolves to in the selected palette. * * A glyph that is **not** a COLR base glyph (or a font with no COLR/CPAL table) * returns `[]` — such a glyph is drawn as a normal monochrome glyph. * * The special palette index `0xFFFF` ("foreground color") is preserved on the * layer's `paletteIndex` but, having no palette entry, resolves to the neutral * fallback `[0, 0, 0, 255]`; a renderer should substitute the active text color. * * @param fontData - Raw sfnt font bytes. * @param glyphId - The base glyph id to expand. * @param paletteIndex - Which CPAL palette to resolve colors from. Defaults to * palette 0 (the default palette). Out-of-range values fall back to palette 0. * @returns The ordered (bottom-first) list of colored layers, or `[]`. */ declare function getColorGlyphLayers(fontData: Uint8Array, glyphId: number, paletteIndex?: number): ColorGlyphLayer[]; //#endregion //#region src/core/meshShading.d.ts /** Allowed widths for /BitsPerCoordinate (ISO 32000-2 §8.7.4.5.5, Table 84). */ type BitsPerCoordinate = 8 | 16 | 24 | 32; /** Allowed widths for /BitsPerComponent (ISO 32000-2 §8.7.4.5.5, Table 84). */ type BitsPerComponent = 8 | 16; /** Allowed widths for /BitsPerFlag (ISO 32000-2 §8.7.4.5.5, Table 84). */ type BitsPerFlag = 2 | 8; /** * A single mesh vertex. * * `color` holds the **decoded** colour: either `n` components in the shading's * /ColorSpace, or a single parametric value `t` when the shading carries a * /Function. Coordinates are decoded user-space values, mapped through /Decode * at pack time. */ interface MeshVertex { /** Decoded x coordinate (mapped through /Decode `[xmin xmax]`). */ x: number; /** Decoded y coordinate (mapped through /Decode `[ymin ymax]`). */ y: number; /** Decoded colour: `n` components, or one parametric value `t`. */ color: number[]; } /** * A free-form (type 4) triangle: an ordered list of flagged vertices. * * Each vertex carries an edge flag (ISO 32000-2 §8.7.4.5.5, Table 85): * - `0` — starts a new (independent) triangle; must be followed by two more * flag-0 vertices. * - `1` — shares the (vb, vc) edge of the previous triangle. * - `2` — shares the (va, vc) edge of the previous triangle. * * A `triangles` entry need not literally be three vertices: callers may emit a * run of flagged vertices that the consumer assembles into triangles. The * builder simply packs the vertices in order. */ interface FreeFormTriangle { /** One or more flagged vertices, packed in order. */ vertices: [FlaggedVertex, ...FlaggedVertex[]]; } /** A {@link MeshVertex} carrying a type-4 edge flag (0, 1 or 2). */ type FlaggedVertex = MeshVertex & { flag: number; }; /** * A Coons patch (type 6) record (ISO 32000-2 §8.7.4.5.7). * * `flag` selects the record shape: * - `0` — new patch: `points` = 12 control points, `colors` = 4 corner colours. * - `1`–`3` — shared edge: `points` = 8 control points, `colors` = 2 colours. */ interface CoonsPatch { /** Edge flag 0–3. */ flag: number; /** Control points as `[x, y]` pairs (12 for flag 0, 8 for flags 1–3). */ points: [number, number][]; /** Corner colours (4 for flag 0, 2 for flags 1–3). */ colors: number[][]; } /** * A tensor-product patch (type 7) record (ISO 32000-2 §8.7.4.5.8). * * `flag` selects the record shape: * - `0` — new patch: `points` = 16 control points, `colors` = 4 corner colours. * - `1`–`3` — shared edge: `points` = 12 control points, `colors` = 2 colours. */ interface TensorPatch { /** Edge flag 0–3. */ flag: number; /** Control points as `[x, y]` pairs (16 for flag 0, 12 for flags 1–3). */ points: [number, number][]; /** Corner colours (4 for flag 0, 2 for flags 1–3). */ colors: number[][]; } /** * Keys common to every mesh shading dictionary * (ISO 32000-2 §8.7.4.5.5, Table 84). */ interface MeshShadingCommon { /** The shading colour space (name or array, e.g. an ICCBased ref array). */ colorSpace: PdfName | PdfArray; /** Bits used per coordinate value: 8, 16, 24 or 32. */ bitsPerCoordinate: BitsPerCoordinate; /** Bits used per colour component: 8 or 16. */ bitsPerComponent: BitsPerComponent; /** * Bits used per edge flag: 2 or 8. Required for types 4, 6 and 7; ignored for * type 5 (which has no flags). */ bitsPerFlag: BitsPerFlag; /** * The /Decode array `[xmin xmax ymin ymax c1min c1max …]`, or * `[xmin xmax ymin ymax tmin tmax]` when {@link MeshShadingCommon.function} * is present. */ decode: number[]; /** * Optional colour /Function. When present, each vertex/corner colour is a * single parametric value `t`; otherwise it is `n` components. */ function?: PdfDict | PdfArray | undefined; } /** Options for {@link buildFreeFormGouraudShading}. */ interface FreeFormGouraudOptions extends MeshShadingCommon { /** Triangle runs whose flagged vertices are packed in order. */ triangles: FreeFormTriangle[]; } /** * Build a free-form Gouraud-shaded triangle mesh shading * (ISO 32000-2 §8.7.4.5.5, /ShadingType 4). * * Each vertex is packed as `flag · x · y · colour[n]`, MSB-first, with the flag * `bitsPerFlag` wide. * * @param options - the common mesh keys plus the triangle/vertex data. * @returns a {@link PdfStream} whose dict has /ShadingType 4 and whose body is * the packed vertex stream. */ declare function buildFreeFormGouraudShading(options: FreeFormGouraudOptions): PdfStream; /** Options for {@link buildLatticeFormGouraudShading}. */ interface LatticeFormGouraudOptions extends Omit { /** Number of vertices in each row of the lattice (≥ 2). */ verticesPerRow: number; /** All vertices in row-major order (no flags). */ vertices: MeshVertex[]; } /** * Build a lattice-form Gouraud-shaded triangle mesh shading * (ISO 32000-2 §8.7.4.5.6, /ShadingType 5). * * Vertices carry **no** flag; the mesh topology is implied by /VerticesPerRow. * Each vertex is packed as `x · y · colour[n]`, MSB-first. * * @param options - the common mesh keys (sans /BitsPerFlag) plus * /VerticesPerRow and the row-major vertex list. * @returns a {@link PdfStream} with /ShadingType 5 and /VerticesPerRow. */ declare function buildLatticeFormGouraudShading(options: LatticeFormGouraudOptions): PdfStream; /** Options for {@link buildCoonsPatchShading}. */ interface CoonsPatchOptions extends MeshShadingCommon { /** Coons patches packed in order. */ patches: CoonsPatch[]; } /** * Build a Coons patch mesh shading * (ISO 32000-2 §8.7.4.5.7, /ShadingType 6). * * Each patch is packed as `flag · points · colours`. A flag-0 patch carries 12 * control points and 4 corner colours; flags 1–3 carry 8 control points and 2 * colours (the rest are inherited from the shared edge of the previous patch). * * @param options - the common mesh keys plus the patch list. * @returns a {@link PdfStream} with /ShadingType 6. */ declare function buildCoonsPatchShading(options: CoonsPatchOptions): PdfStream; /** Options for {@link buildTensorPatchShading}. */ interface TensorPatchOptions extends MeshShadingCommon { /** Tensor-product patches packed in order. */ patches: TensorPatch[]; } /** * Build a tensor-product patch mesh shading * (ISO 32000-2 §8.7.4.5.8, /ShadingType 7). * * Identical packing to type 6 but a flag-0 patch carries 16 control points (the * 4 internal tensor points in addition to the 12 boundary points) plus 4 corner * colours; flags 1–3 carry 12 control points and 2 colours. * * @param options - the common mesh keys plus the patch list. * @returns a {@link PdfStream} with /ShadingType 7. */ declare function buildTensorPatchShading(options: TensorPatchOptions): PdfStream; //#endregion //#region src/color/iccTransform.d.ts /** * @module color/iccTransform * * Apply an ICC profile's **matrix/TRC** colour model to transform device * colour into the Profile Connection Space (PCS), for the common * RGB-display and grayscale cases, plus the CIE L\*a\*b\* conversion. * * Two ICC profile shapes can describe a display/input transform: * * - **Matrix/TRC** — three (RGB) or one (gray) one-dimensional tone-response * curves followed by a 3×3 colorant matrix. This is what virtually every * monitor (`mntr`) RGB profile and most gray profiles use. This module * implements exactly this model. * - **LUT-based** — `mft1`/`mft2` (`lut8`/`lut16`) or `mAB `/`mBA ` * (`lutAtoBType`/`lutBtoAType`) multidimensional tables (A2B0/B2A0 …). These * cannot be evaluated as a matrix/TRC and are explicitly **rejected** rather * than silently mis-computed. * * For a matrix/TRC RGB profile the forward device→PCS transform is * (ICC.1:2010 §E.1.1, "RGB Device to PCS"): * * ``` * [ X ] [ rX gX bX ] [ TRC_r(r) ] * [ Y ] = [ rY gY bY ] [ TRC_g(g) ] * [ Z ] [ rZ gZ bZ ] [ TRC_b(b) ] * ``` * * where the matrix columns are the `rXYZ`/`gXYZ`/`bXYZ` colorant tags and each * `TRC_*` is the linearising tone-response curve from `rTRC`/`gTRC`/`bTRC` * (`kTRC` for gray). The resulting XYZ is **D50-relative**, matching the ICC * PCS reference illuminant (ICC.1:2010 §6.3.4.3, PCS = CIEXYZ relative to D50 = * `[0.9642, 1.0000, 0.8249]`). * * Spec references (ICC.1:2010-12, "Image technology colour management — * Architecture, profile format and data structure"): * - §7.2 profile header layout (version o8, deviceClass o12, colour space * o16, PCS o20). * - §7.3 tag table (o128: u32 count, then 12-byte records {sig, offset, size}). * - §4.2 s15Fixed16Number = signed int32 / 65536. * - §10.6 curveType ('curv': u32 count; 0 = identity, 1 = u8Fixed8 gamma, * n≥2 = uInt16 sampled curve over the domain [0,1]). * - §10.18 parametricCurveType ('para': u16 function type + s15Fixed16 params). * - §10.31 XYZType ('XYZ ': reserved + n × (3 × s15Fixed16)). * * No Buffer — uses `Uint8Array` / `DataView` exclusively. */ /** * Summary of an ICC profile header plus whether it carries a usable * matrix/TRC model. */ interface IccTransformInfo { /** * Raw profile version word from header offset 8 (big-endian u32). For * example `0x02100000` = v2.1, `0x04300000` = v4.3. */ readonly version: number; /** Device class signature from offset 12 (e.g. `'mntr'`, `'prtr'`, `'scnr'`). */ readonly deviceClass: string; /** Data colour space signature from offset 16 (e.g. `'RGB '`, `'GRAY'`, `'CMYK'`). */ readonly colorSpace: string; /** Profile Connection Space signature from offset 20 (`'XYZ '` or `'Lab '`). */ readonly pcs: string; /** * `true` when the profile carries a complete matrix/TRC model: * - RGB: `rXYZ` + `gXYZ` + `bXYZ` and `rTRC` + `gTRC` + `bTRC` all present. * - GRAY: `kTRC` present (the gray-colorant matrix degenerates to the * white point). */ readonly hasMatrixTrc: boolean; } /** * Parse the matrix/TRC-relevant header fields and detect whether the profile * carries a complete matrix/TRC model. * * Reads the 128-byte ICC header (ICC.1:2010 §7.2): version (offset 8), * deviceClass (offset 12), data colour space (offset 16) and PCS (offset 20), * then inspects the tag table (§7.3) for the colorant + TRC tags. * * @param profile - Raw ICC profile bytes. * @returns Parsed {@link IccTransformInfo}. * @throws if the profile is too short to contain a header and tag table. * * @example * ```ts * import { parseIccTransform } from 'modern-pdf-lib'; * * const info = parseIccTransform(profileBytes); * if (info.hasMatrixTrc && info.colorSpace === 'RGB ') { * // safe to call deviceRgbToXyz * } * ``` */ declare function parseIccTransform(profile: Uint8Array): IccTransformInfo; /** * Transform a device colour through a **matrix/TRC** ICC profile into the * D50-relative PCS XYZ. * * For RGB (`colorSpace === 'RGB '`): each channel is linearised through its * `rTRC`/`gTRC`/`bTRC` curve, then multiplied by the colorant matrix whose * columns are the `rXYZ`/`gXYZ`/`bXYZ` tags (ICC.1:2010 §E.1.1). * * For GRAY (`colorSpace === 'GRAY'`): the single value is linearised through * `kTRC` and scaled by the media white point (`wtpt`, defaulting to D50). * * The result is **D50-relative XYZ**, matching the ICC PCS reference * illuminant; feed it directly to {@link xyzToLab} (whose default white point * is D50). * * @param profile - Raw ICC profile bytes. * @param rgb - Device colour in `[0,1]`. For gray profiles only the first * component is used. * @returns PCS XYZ `[X, Y, Z]`, D50-relative. * @throws if the profile is **not** matrix/TRC (i.e. it is LUT-based — * `mft1`/`mft2`/`mAB `/`mBA `), or its colour space is unsupported. * * @example * ```ts * import { deviceRgbToXyz } from 'modern-pdf-lib'; * * const xyz = deviceRgbToXyz(srgbProfileBytes, [1, 1, 1]); * // ~ [0.9642, 1.0, 0.8249] (D50 white) * ``` */ declare function deviceRgbToXyz(profile: Uint8Array, rgb: [number, number, number]): [number, number, number]; /** * Convert PCS XYZ to CIE L\*a\*b\* (CIE 15:2004 §8.2.1 / ICC PCS): * * ``` * L* = 116·f(Y/Yn) − 16 * a* = 500·(f(X/Xn) − f(Y/Yn)) * b* = 200·(f(Y/Yn) − f(Z/Zn)) * ``` * * with f as in {@link labF}. The default reference white is **D50** * `[0.9642, 1.0000, 0.8249]`, matching the ICC PCS (ICC.1:2010 §6.3.4.3), so * XYZ produced by {@link deviceRgbToXyz} maps straight through. * * @param xyz - XYZ tristimulus, relative to `whitePoint`. * @param whitePoint - Reference white `[Xn, Yn, Zn]`. Defaults to D50. * @returns `[L*, a*, b*]`. * * @example * ```ts * import { xyzToLab } from 'modern-pdf-lib'; * * xyzToLab([0.9642, 1.0, 0.8249]); // ~ [100, 0, 0] (D50 white) * ``` */ declare function xyzToLab(xyz: [number, number, number], whitePoint?: [number, number, number]): [number, number, number]; //#endregion //#region src/color/colorConvert.d.ts /** * Convert device RGB to HSL. * * @param r - Red, 0..1. * @param g - Green, 0..1. * @param b - Blue, 0..1. * @returns `[h, s, l]` with `h` in `[0, 360)`, `s`/`l` in `0..1`. */ declare function rgbToHsl(r: number, g: number, b: number): [number, number, number]; /** * Convert HSL to device RGB. * * @param h - Hue in degrees (any real; wrapped into `[0, 360)`). * @param s - Saturation, 0..1. * @param l - Lightness, 0..1. * @returns `[r, g, b]`, each 0..1. */ declare function hslToRgb(h: number, s: number, l: number): [number, number, number]; /** * Convert device RGB to HSV. * * @param r - Red, 0..1. * @param g - Green, 0..1. * @param b - Blue, 0..1. * @returns `[h, s, v]` with `h` in `[0, 360)`, `s`/`v` in `0..1`. */ declare function rgbToHsv(r: number, g: number, b: number): [number, number, number]; /** * Convert HSV to device RGB. * * @param h - Hue in degrees (any real; wrapped into `[0, 360)`). * @param s - Saturation, 0..1. * @param v - Value, 0..1. * @returns `[r, g, b]`, each 0..1. */ declare function hsvToRgb(h: number, s: number, v: number): [number, number, number]; /** * Convert device (sRGB) RGB to CIE XYZ relative to the D65 white point. * * Gamma-expands each channel, then applies the IEC 61966-2-1 sRGB→XYZ D65 * matrix. The returned `Y` is `1.0` for input white `(1, 1, 1)`. * * @param r - Red, 0..1. * @param g - Green, 0..1. * @param b - Blue, 0..1. * @returns `[X, Y, Z]` (D65, `Y = 1` for white). */ declare function rgbToXyz(r: number, g: number, b: number): [number, number, number]; /** * Convert CIE XYZ (D65) to device (sRGB) RGB. * * Applies the inverse sRGB matrix, then gamma-companding. Results are clamped * to `0..1` to keep them in the displayable device gamut. * * @param x - CIE X (D65). * @param y - CIE Y (D65). * @param z - CIE Z (D65). * @returns `[r, g, b]`, each clamped to 0..1. */ declare function xyzToRgb(x: number, y: number, z: number): [number, number, number]; /** * Convert device (sRGB) RGB to CIE L\*a\*b\* via XYZ, using the D65 white * point. * * @param r - Red, 0..1. * @param g - Green, 0..1. * @param b - Blue, 0..1. * @returns `[L, a, b]` with `L ∈ [0, 100]`, `a`/`b` in their natural ranges. */ declare function rgbToLab(r: number, g: number, b: number): [number, number, number]; //#endregion //#region src/assets/image/nextGenImageDetect.d.ts /** * @module assets/image/nextGenImageDetect * * DETECT and probe next-generation image formats: AVIF, HEIC/HEIF, and JPEG XL. * * This module does **NOT** decode pixels. Pure-JS AV1 (AVIF), HEVC (HEIC), and * JPEG XL decoders are intentionally not bundled, so {@link probeNextGenImage} * always reports `decodable: false`. It only reads container metadata * (dimensions, bit depth) so callers can make a decision (reject, convert * upstream to PNG/JPEG, or register an external WASM decoder). * * Spec references (verified against the cited sections): * * - **ISO Base Media File Format** — ISO/IEC 14496-12. * - §4.2 Object Structure: every box starts with `size` (u32, big-endian) * then `type` (4 bytes / FourCC). If `size == 1`, an 8-byte * `largesize` (u64) follows `type`; if `size == 0`, the box runs to EOF. * - §4.3 FileTypeBox ('ftyp'): `major_brand` (4) + `minor_version` (u32) + * an array of `compatible_brands` (4 bytes each) filling the box. * - §4.2 FullBox: `version` (u8) + `flags` (u24) precede the body. * - §8.11.1 MetaBox ('meta') is a FullBox; its child boxes follow the * version+flags word. * - **HEIF** — ISO/IEC 23008-12. * - §9.3.1 ItemPropertiesBox ('iprp') containing ItemPropertyContainerBox * ('ipco'). * - §6.5.3 ImageSpatialExtentsProperty ('ispe') — a FullBox: * version+flags (u32) + `image_width` (u32) + `image_height` (u32). * - §6.5.6 PixelInformationProperty ('pixi') — a FullBox: * version+flags (u32) + `num_channels` (u8) + `bits_per_channel` (u8) * repeated `num_channels` times. * - Annex B brands: 'mif1' (image), 'msf1' (sequence) generic; 'heic', * 'heix', 'heim', 'heis', 'hevc', 'hevx' for HEVC-coded HEIF. * - **AVIF** — AV1 Image File Format (Alliance for Open Media). * - §4 File-level brands: 'avif' (still image), 'avis' (image sequence). * - **JPEG XL** — ISO/IEC 18181-1. * - The bare codestream begins with the signature `FF 0A`. * - The ISOBMFF-style container begins with the 12-byte signature box * `00 00 00 0C 'JXL ' 0D 0A 87 0A`. * * No Buffer — uses Uint8Array / DataView exclusively. No fs. ESM only. */ /** Identifier for a recognized next-generation image format, or `null`. */ type NextGenFormat = "avif" | "heic" | "heif" | "jpegxl" | null; /** * Metadata probed from a next-generation image container. * * `decodable` is always `false`: this library probes but never decodes these * formats' pixels. Dimensions / bit depth are best-effort and may be * `undefined` when the relevant property box is absent or unparseable. */ interface NextGenImageInfo { /** The detected format. */ format: NextGenFormat; /** Image width in pixels, if discoverable from an 'ispe' box. */ width?: number | undefined; /** Image height in pixels, if discoverable from an 'ispe' box. */ height?: number | undefined; /** Bits per channel, if a 'pixi' box is present. */ bitDepth?: number | undefined; /** Whether this library has alpha; reserved — currently always `undefined`. */ hasAlpha?: boolean | undefined; /** Always `false`: pixel decoding for these formats is not bundled. */ decodable: false; /** Human-readable explanation of why the image is not decodable here. */ reason: string; } /** * Detect a next-generation image format from raw bytes. * * Recognizes AVIF / HEIC / HEIF via the ISOBMFF `ftyp` brand set, and JPEG XL * via either the bare codestream signature (`FF 0A`) or the container * signature box (`00 00 00 0C 'JXL ' 0D 0A 87 0A`). * * @param bytes Raw image file bytes. * @returns The detected {@link NextGenFormat}, or `null` if unrecognized. */ declare function detectNextGenFormat(bytes: Uint8Array): NextGenFormat; /** * Probe a next-generation image for container metadata WITHOUT decoding pixels. * * For AVIF / HEIC / HEIF, walks the ISOBMFF box tree * (`meta` > `iprp` > `ipco` > `ispe`/`pixi`) to recover width, height, and * bit depth when present. For JPEG XL, the format is identified but dimensions * are not parsed (the `SizeHeader` is a packed-bit codestream field and is * intentionally scoped out here); only `format` is returned. * * The returned {@link NextGenImageInfo} **always** has `decodable: false`. * No pixel data is ever produced. * * @param bytes Raw image file bytes. * @returns A {@link NextGenImageInfo}, or `null` if not a next-gen image. */ declare function probeNextGenImage(bytes: Uint8Array): NextGenImageInfo | null; //#endregion //#region src/assets/image/imageDecoderRegistry.d.ts /** * @module assets/image/imageDecoderRegistry * * Pluggable image-decoder registry + dispatch. * * The library bundles decoders for PNG, JPEG, WebP, and TIFF * (see {@link module:assets/image/formatDetect}). It deliberately does **not** * bundle decoders for the modern next-generation codecs — AVIF, HEIC/HEIF, and * JPEG XL — because each requires a substantial, separately-maintained codec * (AV1 / HEVC intra / the JPEG XL reference codec) that is out of scope for a * pure-JS PDF library. * * This module provides the **honest integration path**: it lets a consumer * register a decoder they supply (typically a WASM build of `libaom`/`dav1d`, * `libheif`, or `libjxl`, or the browser's `ImageDecoder` Web API) under a * format key, and then dispatch raw bytes to it. * * IMPORTANT — this module performs **NO image decoding whatsoever**. It does not * parse AVIF/HEIC/JXL containers, it does not understand any bitstream, and it * makes no claim about any pixel data. It is *purely* a registry (a `Map`) plus * a dispatch function that validates the **shape** of whatever a registered * decoder returns. All real decoding is the responsibility of the * consumer-supplied {@link ImageDecoder}. * * Format keys are normalized (trimmed + lowercased), so `'AVIF'`, `' avif '`, * and `'avif'` all refer to the same decoder. Suggested keys: `'avif'`, * `'heic'`, `'jpegxl'`. * * No Buffer — uses Uint8Array exclusively. * No fs — no file system access. * No require() — ESM import only. */ /** * A decoded raster image in tightly-packed, top-to-bottom, left-to-right * RGBA8888 form. * * - `width` — image width in pixels (a positive integer). * - `height` — image height in pixels (a positive integer). * - `rgba` — pixel data; exactly `width * height * 4` bytes, four bytes * (red, green, blue, alpha) per pixel, each in the range `0..255`. */ interface DecodedRasterImage { width: number; height: number; rgba: Uint8Array; } /** * A consumer-supplied decoder: it takes the raw, encoded image bytes and * returns (synchronously or asynchronously) a {@link DecodedRasterImage}. * * The registry never inspects the input bytes; it forwards them verbatim to the * decoder. The decoder is solely responsible for parsing the container/bitstream * and producing valid RGBA8888 output. */ type ImageDecoder = (bytes: Uint8Array) => DecodedRasterImage | Promise; /** * Register a decoder for a given image format. * * If a decoder is already registered for the (normalized) format, it is * replaced. * * @param format Format key, e.g. `'avif'`, `'heic'`, `'jpegxl'`. The key is * normalized (trimmed + lowercased) before storage. * @param decoder The {@link ImageDecoder} that turns encoded bytes into RGBA. */ declare function registerImageDecoder(format: string, decoder: ImageDecoder): void; /** * Remove the decoder registered for a given format, if any. * * This is a no-op when no decoder is registered for the (normalized) format. * * @param format Format key; normalized (trimmed + lowercased) before lookup. */ declare function unregisterImageDecoder(format: string): void; /** * Report whether a decoder is currently registered for a given format. * * @param format Format key; normalized (trimmed + lowercased) before lookup. * @returns `true` if a decoder is registered, otherwise `false`. */ declare function hasImageDecoder(format: string): boolean; /** * Get the decoder registered for a given format, if any. * * @param format Format key; normalized (trimmed + lowercased) before lookup. * @returns The registered {@link ImageDecoder}, or `undefined` if none. */ declare function getImageDecoder(format: string): ImageDecoder | undefined; /** * Decode raw image bytes using a previously-registered decoder for `format`. * * Looks up the decoder by (normalized) format key, awaits its result, validates * the result shape (`rgba.length === width * height * 4`, positive-integer * dimensions, `Uint8Array` pixel buffer), and returns it. * * This function does **not** decode anything itself — it dispatches to the * consumer-supplied {@link ImageDecoder}. If no decoder is registered for the * format, it throws an error naming the format and explaining how to register * one via {@link registerImageDecoder}. * * @param format Format key, e.g. `'avif'`; normalized before lookup. * @param bytes Raw, encoded image bytes, forwarded verbatim to the decoder. * @returns A validated {@link DecodedRasterImage}. * @throws If no decoder is registered for the format, or if the * registered decoder returns a malformed result. */ declare function decodeRegisteredImage(format: string, bytes: Uint8Array): Promise; //#endregion //#region src/assets/image/svgFilters.d.ts /** * @module assets/image/svgFilters * * SVG filter primitive evaluators operating on **8-bit RGBA8888** raster * buffers, so an SVG / raster pipeline can apply filter effects without a * full SVG engine. * * ## Colour model / premultiplication contract * * The public {@link RasterBuffer} carries **straight (non-premultiplied)** * RGBA8888 — i.e. the colour channels are the un-multiplied colour and the * 4th channel is the alpha, both 0..255. This matches the byte layout * produced by the PNG/WebP/TIFF decoders in this package and consumed by the * rasteriser. * * Individual primitives convert to whatever working space the maths require: * * - {@link feColorMatrix} / {@link feColorMatrixSaturate} operate on * **straight** colour normalised to 0..1, per SVG 1.1 §15.10 (the matrix is * applied to the un-premultiplied `[R G B A 1]` vector). * - {@link feGaussianBlur} blurs in **premultiplied** space (the * mathematically correct space for averaging colours with varying alpha, * SVG 1.1 §15.17) and un-premultiplies on the way out. * - {@link feComposite} (Porter-Duff) and {@link feBlend} composite in * **premultiplied** space and return straight RGBA. * * All outputs are rounded and clamped to the [0, 255] integer range. * * ## Specifications verified * * - SVG 1.1 (Second Edition) §15.10 `feColorMatrix` — 4×5 (20-value) matrix * applied per pixel over the normalised `[R, G, B, A, 1]` column vector; * `saturate` shorthand coefficients 0.213 / 0.715 / 0.072. * - SVG 1.1 §15.17 `feGaussianBlur` — "three successive box-blurs" Gaussian * approximation with box size `d = floor(s · 3 · √(2π) / 4 + 0.5)` and the * odd/even centring rule. * - Porter & Duff, *"Compositing Digital Images"* (Computer Graphics 18(3), * SIGGRAPH 1984) / SVG 1.1 §15.13 `feComposite` — over / in / out / atop / * xor with `Fa`, `Fb` coefficients on premultiplied colour. * * No Buffer — Uint8Array exclusively. No fs. ESM only. */ /** * A raster image buffer of straight (non-premultiplied) RGBA8888 pixels. * * `rgba` length MUST equal `width * height * 4`. Channel order is * `R, G, B, A` with each value in `0..255`. */ interface RasterBuffer { /** Width in pixels (> 0). */ width: number; /** Height in pixels (> 0). */ height: number; /** Pixel data, length = `width * height * 4`, channel order R,G,B,A. */ rgba: Uint8Array; } /** * Produce a buffer filled with a single constant colour. * * Implements `feFlood` (SVG 1.1 §15.12): every pixel is set to the given * straight RGBA8888 colour. * * @param width Output width in pixels (must be > 0). * @param height Output height in pixels (must be > 0). * @param rgba The fill colour as `[R, G, B, A]`, each 0..255. * @returns A new buffer of `width × height` filled with `rgba`. */ declare function feFlood(width: number, height: number, rgba: [number, number, number, number]): RasterBuffer; /** * Apply a 4×5 colour matrix to every pixel. * * Implements `feColorMatrix` with `type="matrix"` (SVG 1.1 §15.10). The 20 * values are row-major: * * ``` * | R' | | m0 m1 m2 m3 m4 | | R | * | G' | | m5 m6 m7 m8 m9 | | G | * | B' | = | m10 m11 m12 m13 m14 | · | B | * | A' | | m15 m16 m17 m18 m19 | | A | * | 1 | ( the implicit identity row ) | 1 | * ``` * * Channels are normalised to 0..1, the matrix is applied to the **straight** * (un-premultiplied) `[R, G, B, A, 1]` vector, then the result is scaled back * to 0..255 with clamping. * * @param src Source buffer. * @param matrix Exactly 20 numbers (4 rows × 5 columns). * @returns A new buffer with the matrix applied. * @throws If `matrix` does not contain exactly 20 values. */ declare function feColorMatrix(src: RasterBuffer, matrix: number[]): RasterBuffer; /** * Apply the `saturate` shorthand colour matrix. * * Implements `feColorMatrix type="saturate"` (SVG 1.1 §15.10). The luma * coefficients are the spec's exact constants 0.213 (R), 0.715 (G), * 0.072 (B). `s = 1` is the identity; `s = 0` fully desaturates each pixel to * its luma (so R = G = B); `s > 1` over-saturates. * * The spec saturate matrix (rows R, G, B; alpha untouched): * ``` * | 0.213+0.787s 0.715-0.715s 0.072-0.072s 0 0 | * | 0.213-0.213s 0.715+0.285s 0.072-0.072s 0 0 | * | 0.213-0.213s 0.715-0.715s 0.072+0.928s 0 0 | * | 0 0 0 1 0 | * ``` * * @param src Source buffer. * @param s Saturation factor (0 = greyscale, 1 = identity, >1 = boosted). * @returns A new buffer with the saturate matrix applied. */ declare function feColorMatrixSaturate(src: RasterBuffer, s: number): RasterBuffer; /** * Shift the image by an integer offset, leaving exposed edges transparent. * * Implements `feOffset` (SVG 1.1 §15.15). Pixels are copied to * `(x + dx, y + dy)`; destinations that fall outside the buffer are dropped * and exposed areas remain transparent black. `dx` / `dy` are rounded to the * nearest integer pixel. * * @param src Source buffer. * @param dx Horizontal offset in pixels (positive = right). * @param dy Vertical offset in pixels (positive = down). * @returns A new buffer of the same size with the shifted content. */ declare function feOffset(src: RasterBuffer, dx: number, dy: number): RasterBuffer; /** * Approximate a Gaussian blur via three successive box blurs. * * Implements `feGaussianBlur` (SVG 1.1 §15.17). The blur is performed in * **premultiplied** colour space (the correct space for averaging colours * with varying alpha) and un-premultiplied on output. A standard deviation of * 0 on an axis is a no-op for that axis. * * The per-axis box size is `d = floor(s · 3 · √(2π) / 4 + 0.5)` with the * spec's odd/even centring rule. * * @param src Source buffer. * @param stdDevX Standard deviation along X (>= 0). * @param stdDevY Standard deviation along Y; defaults to `stdDevX`. * @returns A new, blurred buffer of the same size. * @throws If either standard deviation is negative. */ declare function feGaussianBlur(src: RasterBuffer, stdDevX: number, stdDevY?: number): RasterBuffer; /** Porter-Duff compositing operators supported by {@link feComposite}. */ type CompositeOp = "over" | "in" | "out" | "atop" | "xor"; /** * Composite two buffers with a Porter-Duff operator. * * Implements `feComposite` with operators `over`, `in`, `out`, `atop`, `xor` * (SVG 1.1 §15.13; Porter & Duff, SIGGRAPH 1984). The general form on * premultiplied colour is: * * ``` * cr = ca · Fa + cb · Fb * ar = aa · Fa + ab · Fb * ``` * * with coefficients (`aa`, `ab` = source/destination alpha): * * | op | Fa | Fb | * | ---- | --------- | --------- | * | over | 1 | 1 − aa | * | in | ab | 0 | * | out | 1 − ab | 0 | * | atop | ab | 1 − aa | * | xor | 1 − ab | 1 − aa | * * Here `a` is the source (foreground) and `b` is the destination * (background). Both buffers must be the same size. * * @param a Source (foreground) buffer. * @param b Destination (background) buffer. * @param op Porter-Duff operator. * @returns A new composited buffer of the same size. * @throws If the buffers differ in size. */ declare function feComposite(a: RasterBuffer, b: RasterBuffer, op: CompositeOp): RasterBuffer; /** Blend modes supported by {@link feBlend}. */ type BlendMode = "normal" | "multiply" | "screen" | "darken" | "lighten"; /** * Blend two buffers with one of the basic SVG 1.1 blend modes. * * Implements `feBlend` (SVG 1.1 §15.11). The spec defines the result on * **premultiplied** colour with `qa` = source alpha, `qb` = destination * alpha: * * - normal: `cr = (1 − qa)·cb + ca` * - multiply: `cr = (1 − qa)·cb + (1 − qb)·ca + ca·cb` * - screen: `cr = cb + ca − ca·cb` * - darken: `cr = min((1 − qa)·cb + ca, (1 − qb)·ca + cb)` * - lighten: `cr = max((1 − qa)·cb + ca, (1 − qb)·ca + cb)` * * with the common result alpha `ar = 1 − (1 − qa)·(1 − qb)`. Inputs `a` * (source) and `b` (destination) must be the same size. * * @param a Source (top) buffer. * @param b Destination (bottom) buffer. * @param mode Blend mode. * @returns A new blended buffer of the same size. * @throws If the buffers differ in size. */ declare function feBlend(a: RasterBuffer, b: RasterBuffer, mode: BlendMode): RasterBuffer; //#endregion //#region src/runtime/sharedConcurrency.d.ts /** * Report whether shared-memory concurrency is usable in this runtime. * * Returns `true` only when **both** `SharedArrayBuffer` and `Atomics` * exist, and — in a browser context that exposes `crossOriginIsolated` — * that flag is not `false`. The check is fully defensive: it performs only * `typeof` probes and never throws, so it is safe to call as a guard before * touching any other export here. * * Note: `crossOriginIsolated` is only consulted when it is a boolean. On * Node / Deno / Bun / Workers (where it is typically `undefined`) we do not * treat its absence as a failure, since those runtimes allow shared memory * without the browser's COOP/COEP isolation requirement. * * @returns `true` iff shared-memory primitives can be constructed and used. */ declare function isSharedMemoryAvailable(): boolean; /** * An atomic 32-bit integer counter backed by a single slot of an * `Int32Array` view over a `SharedArrayBuffer`. Multiple `SharedCounter` * instances constructed over the **same** buffer and index observe each * other's writes, so the counter can be shared across workers by passing * its {@link SharedCounter.buffer} through `postMessage`. * * All mutations use `Atomics`, so increments from concurrent agents never * lose updates. */ declare class SharedCounter { #private; /** The `SharedArrayBuffer` backing this counter. */ readonly buffer: SharedArrayBuffer; /** * @param buffer - Existing shared buffer to attach to. When omitted, a * fresh single-slot (`4`-byte) `SharedArrayBuffer` is * allocated and zero-initialised. * @param index - Element index (in `Int32` units) of the counter slot. * Defaults to `0`. Must be a non-negative integer that * fits within `buffer`. * @throws If shared memory is unavailable (when allocating), or if * `index` is out of range for the supplied `buffer`. */ constructor(buffer?: SharedArrayBuffer, index?: number); /** * The current counter value, read atomically via `Atomics.load`. */ get value(): number; /** * Atomically add `n` to the counter. * * Per `Atomics.add` semantics this returns the **previous** value — the * value the slot held *before* `n` was added — not the new total. Read * {@link SharedCounter.value} afterwards for the updated total. * * @param n - Integer addend (may be negative to subtract). * @returns The value that was stored before the addition. */ add(n: number): number; /** * Atomically increment the counter by one. * * As with {@link SharedCounter.add}, the returned number is the * **pre-increment** value. * * @returns The value that was stored before incrementing. */ increment(): number; /** * Atomically set the counter to `next` iff it currently equals * `expected`, via `Atomics.compareExchange`. * * @param expected - The value the swap is conditional on. * @param next - The value to store when `expected` matches. * @returns The value that was at the slot **before** the call. The swap * succeeded iff this equals `expected`. */ compareExchange(expected: number, next: number): number; } /** * The result of a blocking {@link SharedFlag.wait}, mirroring the return * values of `Atomics.wait`. */ type SharedFlagWaitResult = "ok" | "timed-out" | "not-equal"; /** * A one-bit synchronisation gate over a single `Int32Array` slot * (`0` = unset, `1` = set), supporting `Atomics.wait` / `Atomics.notify`. * * Producers call {@link SharedFlag.set} then {@link SharedFlag.notify} to * release agents blocked in {@link SharedFlag.wait}. * * IMPORTANT — `Atomics.wait` may only block on a *non-main* agent. On the * main browser thread it throws `TypeError`, and on any main thread it * would freeze the event loop. {@link SharedFlag.wait} feature-detects * blocking support and, when blocking is not permitted, degrades to a * single non-blocking check (returning `'ok'` if already set, otherwise * `'not-equal'`) instead of throwing. {@link SharedFlag.notify} is always * safe to call from any thread. */ declare class SharedFlag { #private; /** The `SharedArrayBuffer` backing this flag. */ readonly buffer: SharedArrayBuffer; /** * @param buffer - Existing shared buffer to attach to (its first `Int32` * slot is used). When omitted, a fresh `4`-byte * `SharedArrayBuffer` is allocated, starting cleared. * @throws If shared memory is unavailable when allocating, or `buffer` * is too small to hold one `Int32`. */ constructor(buffer?: SharedArrayBuffer); /** * Atomically set the flag. Does not itself wake waiters — call * {@link SharedFlag.notify} afterwards to release any blocked agents. */ set(): void; /** * Atomically clear the flag back to its unset state. */ clear(): void; /** * @returns `true` iff the flag is currently set, read via `Atomics.load`. */ isSet(): boolean; /** * Block until the flag becomes set, or until `timeoutMs` elapses. * * Implemented with `Atomics.wait` on the unset value: while the slot * still reads `0` (unset) the agent sleeps; a {@link SharedFlag.set} + * {@link SharedFlag.notify} from another agent wakes it. * * Blocking is only legal off the main thread. When `Atomics.wait` is not * allowed here (e.g. the main browser thread), this method does **not** * throw: it performs a single non-blocking check and returns `'ok'` if * the flag is already set, or `'not-equal'` otherwise. Callers that need * to truly block must run on a dedicated worker. * * @param timeoutMs - Optional timeout in milliseconds. Omit (or pass * `Infinity`) to wait indefinitely. * @returns `'ok'` when woken with the flag still unset at entry, * `'timed-out'` if the timeout expired, or `'not-equal'` if the * flag was already set on entry (nothing to wait for). */ wait(timeoutMs?: number): SharedFlagWaitResult; /** * Wake up to `count` agents blocked in {@link SharedFlag.wait} on this * flag, via `Atomics.notify`. Safe to call from any thread. * * @param count - Maximum number of waiters to wake. Defaults to * `Infinity` (wake all). * @returns The number of agents actually woken — `0` when none were * waiting. */ notify(count?: number): number; } /** * A lock-free **single-producer / single-consumer** (SPSC) byte ring buffer * over a `SharedArrayBuffer`, suitable for streaming chunks between exactly * one producing worker and one consuming worker. * * ## Contract * * - **SPSC only.** Correctness relies on there being at most one concurrent * {@link SharedRingBuffer.push} caller (the producer) and at most one * concurrent {@link SharedRingBuffer.pop} caller (the consumer). Multiple * producers or multiple consumers are **not** supported and will corrupt * the cursors. (The producer and consumer may be different agents.) * - {@link SharedRingBuffer.push} returns `false` (writing nothing) when the * frame would not fit in the currently free space. * - {@link SharedRingBuffer.pop} returns `null` when the ring is empty, or * when the next frame is larger than the caller's `maxBytes` budget (the * frame is left intact for a later, larger pop). * * ## SAB layout * * `[ head:int32 | tail:int32 | ...dataBytes ]` * * The `head`/`tail` cursors are published with `Atomics.store` and read with * `Atomics.load`, which establishes the happens-before edge that makes the * non-atomic byte writes into the data region visible to the consumer. Each * frame is encoded as a 4-byte little-endian length header followed by that * many payload bytes; both header and payload wrap around the data region. */ declare class SharedRingBuffer { #private; /** The `SharedArrayBuffer` backing this ring. */ readonly buffer: SharedArrayBuffer; /** * Allocate a new ring whose data region holds `capacityBytes` bytes * (the backing `SharedArrayBuffer` is `capacityBytes` + control overhead). * * @param capacityBytes - Size of the data region in bytes. Must be a * positive integer. * @param existingBuffer - Internal: when supplied, the ring attaches to * this already-allocated buffer instead of creating * a fresh one (used by {@link SharedRingBuffer.fromBuffer}). * Its data region must equal `capacityBytes`. * @throws If `capacityBytes` is not a positive integer, or shared memory * is unavailable. */ constructor(capacityBytes: number, existingBuffer?: SharedArrayBuffer); /** * Attach a second `SharedRingBuffer` view to an existing buffer — e.g. * the consumer side wrapping a buffer received from the producer via * `postMessage`. No cursors are reset; the view observes whatever the * other side has already published. * * @param buffer - A `SharedArrayBuffer` previously created by a * `SharedRingBuffer` constructor. * @returns A `SharedRingBuffer` sharing `buffer`'s cursors and data. * @throws If `buffer` is too small to contain the control region. */ static fromBuffer(buffer: SharedArrayBuffer): SharedRingBuffer; /** * Push a single byte frame onto the ring (producer side). * * The frame is stored as a length-prefixed record. Returns `false` * without modifying the ring if there is not enough free space for the * header plus payload. * * @param bytes - Payload to enqueue (may be empty). * @returns `true` if enqueued, `false` if the ring was too full. */ push(bytes: Uint8Array): boolean; /** * Pop the next byte frame from the ring (consumer side). * * @param maxBytes - Maximum payload size the caller is willing to receive. * If the next frame's payload exceeds this, the frame is * left in place and `null` is returned. * @returns The dequeued payload as a fresh `Uint8Array`, or `null` when * the ring is empty or the next frame exceeds `maxBytes`. */ pop(maxBytes: number): Uint8Array | null; } //#endregion //#region src/runtime/memoryBudget.d.ts /** * @module runtime/memoryBudget * * A memory budget / cap used to bound the processing of *untrusted* PDFs as a * defence against decompression bombs and out-of-memory (OOM) attacks. * * ## What this is — and what it is NOT * * {@link MemoryBudget} is a **pure accounting guard**. It is a plain integer * counter with a ceiling. It does **NOT** measure real process memory (RSS), * heap usage, `performance.memory`, or anything reported by the host. It makes * **no** claim of measuring actual memory and performs **no** acceleration of * any kind — there are no workers, SIMD, threads, `Atomics`, or * `SharedArrayBuffer` involved. * * The intended usage pattern is *predictive*: before a caller allocates a * large buffer (for example, the expected output length of an inflated / * decoded stream, which a malicious PDF can declare as enormous), it reports * that size to the budget via {@link MemoryBudget.allocate} (or * {@link MemoryBudget.tryAllocate}). If the reported size would push total * tracked usage past the configured limit, the allocation is rejected * **before** the real memory is ever requested — so a bomb is stopped early * instead of being materialised and crashing the runtime. * * Because it is pure accounting, its accuracy is exactly as good as the sizes * callers report. It is a budget, not a profiler. * * ## Runtime * * This module uses only ECMAScript primitives (numbers, classes, closures). * It assumes no Node-only globals and runs unchanged on Node, Deno, Bun, * Cloudflare Workers, and browsers. */ /** * Thrown by {@link MemoryBudget.allocate} (and {@link MemoryBudget.withAllocation}) * when a requested allocation would exceed the configured limit. * * Carries the numbers involved so callers can surface a precise diagnostic: * * - {@link requested} — the size that was being allocated. * - {@link used} — the tracked usage *before* the rejected allocation. * - {@link limit} — the configured ceiling. */ declare class MemoryBudgetExceededError extends Error { /** The allocation size, in bytes, that was rejected. */ readonly requested: number; /** The configured budget ceiling, in bytes. */ readonly limit: number; /** The tracked usage, in bytes, at the moment of rejection. */ readonly used: number; /** * @param requested - The size, in bytes, that was being allocated. * @param used - The tracked usage, in bytes, before the allocation. * @param limit - The configured ceiling, in bytes. */ constructor(requested: number, used: number, limit: number); } /** * Options for the {@link MemoryBudget} constructor. */ interface MemoryBudgetOptions { /** * The ceiling, in bytes, that tracked usage may not exceed. Must be a * finite number greater than `0`. `NaN`, negative values, and `Infinity` * are all rejected with a {@link TypeError} (see {@link createMemoryBudget}). */ limitBytes: number; /** * Optional callback invoked **before** a {@link MemoryBudgetExceededError} is * thrown by {@link MemoryBudget.allocate}. It receives the same numbers the * error will carry. It is *not* invoked by {@link MemoryBudget.tryAllocate}, * which never throws. * * Per `exactOptionalPropertyTypes`, declared as `| undefined`. */ onExceed?: ((info: { requested: number; used: number; limit: number; }) => void) | undefined; } /** * A bounded memory accounting guard. See the {@link module:runtime/memoryBudget module documentation} * for the precise semantics — in particular, that this tracks *reported* * sizes and does not measure real RSS. */ declare class MemoryBudget { #private; /** * @param options - The {@link MemoryBudgetOptions}. `limitBytes` must be a * finite number greater than `0`. * @throws {TypeError} If `limitBytes` is not a finite number `> 0`. */ constructor(options: MemoryBudgetOptions); /** Currently tracked usage, in bytes. */ get used(): number; /** The configured ceiling, in bytes. */ get limit(): number; /** Bytes still available before the limit is reached (never negative). */ get remaining(): number; /** * Reserve `bytes` against the budget. * * If `used + bytes` would exceed the limit, {@link onExceed} (if supplied) * is invoked first and then a {@link MemoryBudgetExceededError} is thrown; * tracked usage is left unchanged in that case. * * @param bytes - The size to reserve. Must be a finite number `>= 0`. * @throws {TypeError} If `bytes` is negative, `NaN`, or `Infinity`. * @throws {MemoryBudgetExceededError} If the allocation would exceed the limit. */ allocate(bytes: number): void; /** * Non-throwing variant of {@link allocate}. Reserves `bytes` and returns * `true` on success, or returns `false` (leaving usage unchanged) if the * allocation would exceed the limit. {@link onExceed} is **not** invoked. * * @param bytes - The size to reserve. Must be a finite number `>= 0`. * @returns `true` if reserved, `false` if it would exceed the limit. * @throws {TypeError} If `bytes` is negative, `NaN`, or `Infinity`. */ tryAllocate(bytes: number): boolean; /** * Return `bytes` to the budget. Usage is clamped at `0`, so over-releasing * (or releasing more than was reserved) never produces a negative value. * * @param bytes - The size to release. Must be a finite number `>= 0`. * @throws {TypeError} If `bytes` is negative, `NaN`, or `Infinity`. */ release(bytes: number): void; /** Reset tracked usage to zero. The limit is unchanged. */ reset(): void; /** * Reserve `bytes`, run `fn`, and release `bytes` in a `finally` block so the * reservation is returned even if `fn` throws. * * If the reservation itself would exceed the limit, `fn` is never invoked * and a {@link MemoryBudgetExceededError} is thrown (nothing to release). * * @typeParam T - The return type of `fn`. * @param bytes - The size to reserve for the duration of `fn`. * @param fn - The work to run while the reservation is held. * @returns Whatever `fn` returns. * @throws {TypeError} If `bytes` is negative, `NaN`, or `Infinity`. * @throws {MemoryBudgetExceededError} If the reservation would exceed the limit. */ withAllocation(bytes: number, fn: () => T): T; } /** * Create a {@link MemoryBudget} with the given ceiling. * * The limit must be a finite number strictly greater than `0`; `NaN`, * negative values, and `Infinity` are all rejected with a {@link TypeError}. * (An infinite budget is intentionally disallowed: the whole point is to cap * untrusted input, and `Infinity` would silently disable the guard.) * * @param limitBytes - The ceiling, in bytes. Must be finite and `> 0`. * @returns A new {@link MemoryBudget}. * @throws {TypeError} If `limitBytes` is not a finite number `> 0`. */ declare function createMemoryBudget(limitBytes: number): MemoryBudget; //#endregion //#region src/runtime/runtimeCapabilities.d.ts /** * @module runtime/runtimeCapabilities * * Honest, throw-free detection of the **perf-relevant** capabilities of the * current JavaScript runtime, so callers can gate fast paths (WASM, SIMD, * threads, shared memory, 64-bit typed arrays) on what the host can actually * run. * * Design rules followed here: * * - **No feature is ever assumed.** Every probe feature-detects and is wrapped * so a missing global or a host that throws on access degrades to `false` * rather than crashing. This mirrors the defensive `try/catch` style of the * sibling {@link module:runtime/detect} module. * - **No fake acceleration.** Detection reports only what the host *could* * execute. It does **not** imply modern-pdf-lib's bundled WASM is built with * SIMD/threads — it is not (see {@link SIMD_NOTE}). A `true` here means a * *SIMD-enabled rebuild* would run, not that today's binaries use it. * - **WASM feature probes use the canonical, validated test modules.** Each is * a tiny module whose *only* discriminating instruction is the feature in * question, so `WebAssembly.validate()` returns `true` exclusively when the * host implements that proposal. The byte sequences below were assembled and * verified to (a) validate on a feature-supporting host and (b) fail to * validate when the discriminating section is removed. * * References: * - WebAssembly SIMD (fixed-width 128-bit) proposal — `v128` value type and * `i32x4`/`i8x16` ops. https://github.com/WebAssembly/simd * - WebAssembly threads/atomics proposal — shared memory + `memory.atomic.*`. * https://github.com/WebAssembly/threads * - WebAssembly bulk-memory-operations proposal — `memory.copy`/`memory.fill`. * https://github.com/WebAssembly/bulk-memory-operations * - `WebAssembly.validate` — MDN: returns a boolean, never throws on a * well-formed `BufferSource`. * https://developer.mozilla.org/docs/WebAssembly/JavaScript_interface/validate */ /** * Snapshot of the perf-relevant capabilities of the host runtime. * * Every WASM-prefixed flag answers "would a module using this proposal * validate here?" — i.e. whether the engine implements the proposal — not * whether modern-pdf-lib is currently using it. */ interface RuntimeCapabilities { /** `WebAssembly` is present and `WebAssembly.validate` is callable. */ wasm: boolean; /** The engine implements the fixed-width SIMD proposal (`v128`). */ wasmSimd: boolean; /** * The engine implements the threads/atomics proposal **and** * `SharedArrayBuffer` is available (a wasm shared memory needs it). */ wasmThreads: boolean; /** The engine implements bulk-memory ops (`memory.copy`/`memory.fill`). */ wasmBulkMemory: boolean; /** `SharedArrayBuffer` is a defined global. */ sharedArrayBuffer: boolean; /** `Atomics` is a defined global. */ atomics: boolean; /** `BigInt64Array` is a defined global. */ bigInt64Array: boolean; /** * `globalThis.crossOriginIsolated === true`. Required (in browsers) before * `SharedArrayBuffer` may be shared with workers. `false` when the flag is * absent or not `true`. */ crossOriginIsolated: boolean; /** * Reported logical core count. `navigator.hardwareConcurrency` when present, * otherwise Node's `os.cpus().length` when reachable, otherwise `1`. Always a * positive integer. */ hardwareConcurrency: number; } /** * Honestly detect the perf-relevant capabilities of the current runtime. * * Every probe is feature-detected and throw-free; on a host missing a feature * the corresponding flag is `false` (or `1` for {@link * RuntimeCapabilities.hardwareConcurrency}). The result is **not** cached so a * test harness (or a host that gains a feature, e.g. cross-origin isolation * toggling) sees the live state. * * @returns A fresh {@link RuntimeCapabilities} snapshot. */ declare function detectRuntimeCapabilities(): RuntimeCapabilities; /** * Convenience predicate: does the host implement the WebAssembly SIMD proposal? * * Equivalent to `detectRuntimeCapabilities().wasmSimd`. A `true` result means a * SIMD-enabled module would validate here — **not** that modern-pdf-lib's * shipped WASM uses SIMD (see {@link SIMD_NOTE}). * * @returns `true` iff the SIMD feature-detect module validates. */ declare function isWasmSimdSupported(): boolean; /** * Honesty disclaimer about SIMD acceleration. * * modern-pdf-lib's bundled WebAssembly binaries are built **without** SIMD * today. {@link isWasmSimdSupported} / {@link RuntimeCapabilities.wasmSimd} * report only whether the *host* could run SIMD code — actually benefiting from * SIMD requires a SIMD-enabled rebuild of the WASM modules. This constant * exists so callers and docs do not mistake capability detection for active * acceleration. */ declare const SIMD_NOTE: string; //#endregion //#region src/jsx/jsxRuntime.d.ts /** * A function component: receives its props (with children under * `props.children`) and returns a renderable {@link PdfNode}. */ type PdfComponent = (props: Record) => PdfNode; /** * A JSX element produced by {@link h} / {@link jsx} / {@link jsxs}. */ interface PdfElement { /** Intrinsic tag name (lowercase string) or a function component. */ type: string | PdfComponent; /** Element props (never null after construction). */ props: Record; /** Flattened child nodes. */ children: PdfNode[]; } /** * Anything renderable: an element, primitive text/number, or a falsy node * (which renders nothing). */ type PdfNode = PdfElement | string | number | null | undefined | boolean; /** * Classic hyperscript pragma (`jsxFactory: "h"`). * * @param type Intrinsic tag name or a function component. * @param props Props object, or `null` for no props. * @param children Zero or more child nodes (nested arrays are flattened). * @returns A {@link PdfElement}. */ declare function h(type: string | PdfComponent, props: Record | null, ...children: PdfNode[]): PdfElement; /** * Automatic-runtime factory for elements with a single (or no) child. * * @param type Intrinsic tag name or a function component. * @param props Props object; children (if any) live under `props.children`. * @returns A {@link PdfElement}. */ declare function jsx(type: string | PdfComponent, props: Record): PdfElement; /** * Automatic-runtime factory for elements with multiple static children. * * Behaviour is identical to {@link jsx}; the JSX transform calls `jsxs` when * the children are a static array. * * @param type Intrinsic tag name or a function component. * @param props Props object; children live under `props.children`. * @returns A {@link PdfElement}. */ declare function jsxs(type: string | PdfComponent, props: Record): PdfElement; /** * Fragment component — groups children without adding a layout box. Used by * the JSX transform for `<>...` and directly via `h(Fragment, null, ...)`. * * @param props Props whose `children` are returned for rendering. * @returns The children as a {@link PdfNode} (an array, which the * renderer flattens transparently). */ declare const Fragment: PdfComponent; /** * Render a declarative element tree to a PDF document. * * The `root` should be a `document` element (or a component / fragment that * resolves to one). Each `page` child becomes a PDF page; content flows * top-down within each page per the layout model documented in the module * header. * * @param root The root {@link PdfNode} (typically a `document` element). * @returns The serialized PDF as a `Uint8Array` (begins with `"%PDF-"`). * * @example * ```ts * const bytes = await renderToPdf( * h('document', { size: PageSizes.A4 }, * h('page', null, h('text', { size: 24 }, 'Hello'), h('text', null, 'World')), * ), * ); * ``` */ declare function renderToPdf(root: PdfNode | readonly PdfNode[]): Promise; //#endregion //#region src/form/schemaForm.d.ts /** * The recognised subset of a JSON Schema node. Extra keywords are * permitted by the index signature but ignored by the generator. */ interface JsonSchemaLike { /** JSON Schema `type` keyword (`'object'`, `'string'`, `'boolean'`, …). */ type?: string; /** Child property schemas, keyed by property name (object schemas). */ properties?: Record; /** Names of required properties. */ required?: string[]; /** Enumerated allowed values (used for string → dropdown mapping). */ enum?: unknown[]; /** Human-friendly title; used as the field label when present. */ title?: string; /** Free-form description (currently unused by the generator). */ description?: string; /** JSON Schema `format` hint (currently unused by the generator). */ format?: string; } /** Options controlling the generated form's layout. */ interface SchemaFormOptions { /** Document title drawn at the top of the first page. */ title?: string | undefined; /** Page size as `[width, height]` in PDF points. Defaults to A4. */ pageSize?: [number, number] | undefined; /** Width (points) reserved for the label column. Defaults to 160. */ labelWidth?: number | undefined; } /** The kind of AcroForm field generated for a property. */ type SchemaFieldKind = "text" | "checkbox" | "dropdown"; /** One generated form field descriptor. */ interface SchemaFormField { /** The field name (the schema property key). */ name: string; /** The AcroForm field kind that was generated. */ kind: SchemaFieldKind; } /** Result of {@link buildFormFromJsonSchema}. */ interface SchemaFormResult { /** The generated document (NOT yet saved). */ doc: PdfDocument; /** The fields that were generated, in property order. */ fields: SchemaFormField[]; } /** * Build a fillable AcroForm PDF from a JSON-Schema-like description. * * For an object schema, the `properties` are iterated in insertion * order and one labelled form field is emitted per property. Fields * are stacked top-down; when the vertical cursor runs off the page a * new page is added and the cursor reset. Required fields (listed in * the schema's `required` array) are marked with a trailing asterisk in * their label. * * @param schema The JSON-Schema-like description. * @param options Optional layout options. * @returns The generated (unsaved) {@link PdfDocument} and the * list of generated field descriptors. */ declare function buildFormFromJsonSchema(schema: JsonSchemaLike, options?: SchemaFormOptions): SchemaFormResult; //#endregion //#region src/runtime/serverAdapters.d.ts /** * @module runtime/serverAdapters * * Web-standard and Node-flavoured helpers for serving a generated PDF * from an HTTP server. * * The goal is to make "I have a `Uint8Array` of PDF bytes — now send it * to the client" a one-liner in any runtime: * * ```ts * // Cloudflare Workers / Deno / Bun / Node >=18 (Web `Response`): * import { pdfResponse } from 'modern-pdf-lib'; * return pdfResponse(await doc.save(), { filename: 'report.pdf', download: true }); * * // Express / node:http (no Web `Response`): * import { sendPdfToNodeResponse } from 'modern-pdf-lib'; * sendPdfToNodeResponse(res, await doc.save(), { filename: 'report.pdf' }); * ``` * * Header construction follows **RFC 6266** ("Use of the Content-Disposition * Header Field in HTTP") and its referenced **RFC 5987** extended parameter * encoding: * * - `Content-Disposition` uses the `disposition-type` of either `inline` * (view in browser) or `attachment` (force download). * - The plain `filename` parameter carries an ASCII-only fallback whose * value is a `quoted-string` (so `"` and `\` are backslash-escaped), * per RFC 6266 §4.1 / RFC 2616 quoted-string rules. * - When the filename contains non-ASCII characters, an additional * `filename*` parameter is emitted using the RFC 5987 `ext-value` * grammar: `UTF-8''`. This is the form * recommended by RFC 6266 Appendix D for internationalised filenames, * with the bare `filename` retained as a fallback for legacy agents. * * @see https://www.rfc-editor.org/rfc/rfc6266 — Content-Disposition in HTTP * @see https://www.rfc-editor.org/rfc/rfc5987 — Character set / language * encoding for HTTP header field parameters (the `filename*` form) * * No Node-only modules are imported: `Response` / `ReadableStream` are * feature-detected, and the Node response object is consumed through a * minimal structural interface ({@link NodeServerResponseLike}). */ /** * Options shared by every PDF-serving helper in this module. * * All fields are optional. `exactOptionalPropertyTypes` is enabled in * this project, so each property is declared as `T | undefined` to allow * callers to pass an explicit `undefined`. */ interface PdfResponseOptions { /** * Suggested filename for the document. Used to populate the * `Content-Disposition` header. May contain non-ASCII characters — * an RFC 6266 `filename*` form is emitted automatically when needed. */ filename?: string | undefined; /** * When `true`, the `Content-Disposition` type is `attachment` * (the browser downloads the file). When `false` or omitted it is * `inline` (the browser displays the PDF in a viewer). */ download?: boolean | undefined; /** Value for the `Cache-Control` response header, if any. */ cacheControl?: string | undefined; /** HTTP status code (default `200`). */ status?: number | undefined; /** * Additional response headers. These are merged *first*, so the * core PDF headers (Content-Type / Content-Length / Content-Disposition) * always take precedence over any same-named custom header. */ headers?: Record | undefined; /** * Value for the `Last-Modified` response header. Serialised with * {@link Date.toUTCString} (the HTTP-date format). */ lastModified?: Date | undefined; } /** * Build the set of HTTP response headers for serving a PDF body. * * Always includes `Content-Type: application/pdf`, a numeric * `Content-Length`, and a `Content-Disposition` (`inline` by default, * `attachment` when `options.download` is `true`). `Cache-Control` and * `Last-Modified` are added only when supplied. * * Custom headers from `options.headers` are merged first so the core PDF * headers always win on conflict. * * @param byteLength Length of the PDF body in bytes (the `Content-Length`). * @param options Optional response shaping (see {@link PdfResponseOptions}). * @returns A plain object of header name → value. */ declare function pdfHeaders(byteLength: number, options?: PdfResponseOptions): Record; /** * Build a Web-standard {@link Response} that streams the given PDF bytes * to the client with the correct headers and status code. * * Works in any runtime with the Fetch API: Cloudflare Workers, Deno, Bun, * Node >=18, and browsers (e.g. inside a Service Worker). * * @param bytes The PDF body. * @param options Optional response shaping (see {@link PdfResponseOptions}). * @returns A `Response` with status `options.status ?? 200`. * @throws If the runtime lacks the `Response` constructor. */ declare function pdfResponse(bytes: Uint8Array, options?: PdfResponseOptions): Response; /** * Build a streaming Web-standard {@link Response} from a * `ReadableStream` of PDF bytes (e.g. from `doc.saveAsStream()`). * * Because the total size is generally unknown up-front, `Content-Length` * is **omitted** unless `options.byteLength` is supplied — allowing the * runtime to use chunked transfer encoding. * * @param stream A readable stream of the PDF body. * @param options Response shaping plus an optional known `byteLength`. * @returns A streaming `Response`. * @throws If the runtime lacks the `Response` constructor. */ declare function pdfStreamResponse(stream: ReadableStream, options?: PdfResponseOptions & { byteLength?: number | undefined; }): Response; /** * The minimal structural shape of a Node `http.ServerResponse` (also * satisfied by Express's `res`). Declared inline so that this module * never imports `node:http` and stays runtime-agnostic. */ interface NodeServerResponseLike { /** Write the status line and response headers. */ writeHead(status: number, headers: Record): void; /** Write the final body chunk and end the response. */ end(chunk: Uint8Array): void; } /** * Send a PDF body to a classic Node-style response object * (`http.ServerResponse` or Express `res`). * * This calls {@link NodeServerResponseLike.writeHead} with the status and * {@link pdfHeaders}, then {@link NodeServerResponseLike.end} with the body. * * @param res The response object (structural typing — no import). * @param bytes The PDF body. * @param options Optional response shaping (see {@link PdfResponseOptions}). */ declare function sendPdfToNodeResponse(res: NodeServerResponseLike, bytes: Uint8Array, options?: PdfResponseOptions): void; //#endregion //#region src/render/matrix.d.ts /** * @module render/matrix * * 2-D affine transforms used by the content-stream interpreter and rasterizer. * A PDF transformation matrix is the 6-tuple `[a, b, c, d, e, f]` representing * * ``` * | a b 0 | * | c d 0 | * | e f 1 | * ``` * * A point `(x, y)` maps to `(a·x + c·y + e, b·x + d·y + f)` (ISO 32000-2 §8.3.4). * * @packageDocumentation */ /** A 2-D affine transform as the PDF `[a, b, c, d, e, f]` 6-tuple. */ type Matrix = readonly [number, number, number, number, number, number]; //#endregion //#region src/render/displayList.d.ts /** An 8-bit RGBA color, each channel `0–255`. */ type Rgba = readonly [number, number, number, number]; /** * A flattened sub-path: an array of page-space coordinates as a flat * `[x0, y0, x1, y1, …]` polyline. Bézier curves are flattened to line segments * by the interpreter. */ interface SubPath { /** Flat `[x, y, …]` page-space points. */ readonly points: readonly number[]; /** Whether the sub-path is closed (last point joins the first). */ readonly closed: boolean; } /** A filled region. */ interface FillItem { readonly type: "fill"; readonly subpaths: readonly SubPath[]; /** Winding rule (`f`/`B` → nonzero, `f*`/`B*` → evenodd). */ readonly rule: "nonzero" | "evenodd"; readonly color: Rgba; /** Constant alpha from the graphics state (`ca`), `0–1`. */ readonly alpha: number; /** Active clip path (page space), if any. */ readonly clip?: readonly SubPath[] | undefined; } /** A stroked path. */ interface StrokeItem { readonly type: "stroke"; readonly subpaths: readonly SubPath[]; readonly color: Rgba; readonly alpha: number; /** Line width in page-space units (the user-space width × CTM scale). */ readonly lineWidth: number; readonly lineCap: 0 | 1 | 2; readonly lineJoin: 0 | 1 | 2; readonly clip?: readonly SubPath[] | undefined; } /** A positioned text run (a `Tj`/`TJ`/`'`/`"` show). */ interface TextItem { readonly type: "text"; /** The decoded Unicode text (best-effort via ToUnicode / WinAnsi). */ readonly text: string; /** The resource font name (e.g. `F1`), or `undefined` if unresolved. */ readonly font: string | undefined; /** Font size in text-space units. */ readonly fontSize: number; /** Text-space → page-space transform at the run's origin (Tm × CTM). */ readonly transform: Matrix; /** Fill color (text render modes 0/2/4/6). */ readonly color: Rgba; readonly alpha: number; /** Text rendering mode (Tr), `0–7`; `3`/`7` are invisible (§9.3.3). */ readonly renderMode: number; readonly clip?: readonly SubPath[] | undefined; } /** A placed image XObject (`Do`) or inline image (`BI…EI`). */ interface ImageItem { readonly type: "image"; /** Resource XObject name, or `inline` for an inline image. */ readonly name: string; /** Unit-square `(0,0)–(1,1)` → page-space placement (the CTM at `Do`). */ readonly transform: Matrix; readonly alpha: number; readonly clip?: readonly SubPath[] | undefined; } /** Any drawable produced by the interpreter. */ type DisplayItem = FillItem | StrokeItem | TextItem | ImageItem; /** The full interpreted page: drawables in paint order + page dimensions. */ interface DisplayList { /** Drawables in paint order (first = painted first / bottom-most). */ readonly items: readonly DisplayItem[]; /** Page width in user-space units (from the crop/media box). */ readonly width: number; /** Page height in user-space units. */ readonly height: number; /** Page-space origin offset (crop/media box lower-left), for renderers. */ readonly origin: readonly [number, number]; } //#endregion //#region src/render/interpreter.d.ts /** Options for {@link interpretContentStream}. */ interface InterpretOptions { /** Page (crop/media box) width in user-space units. */ width: number; /** Page (crop/media box) height in user-space units. */ height: number; /** Page-space origin (crop/media box lower-left). Default `[0, 0]`. */ origin?: readonly [number, number] | undefined; /** Page `/Resources` dict, for `Do`/`Tf` resolution. */ resources?: PdfDict | undefined; /** Object registry, to resolve indirect resource refs. */ registry?: PdfObjectRegistry | undefined; } /** * Execute a parsed content stream into a {@link DisplayList}. * * @param operators - Output of {@link parseContentStream}. * @param options - Page dimensions and (optional) resources/registry. */ declare function interpretContentStream(operators: readonly ContentStreamOperator[], options: InterpretOptions): DisplayList; /** * Interpret a {@link PdfPage}'s content into a {@link DisplayList}, using its * crop/media box for dimensions and its resources/registry for `Do`/`gs`/`Tf` * resolution. The entry point for {@link renderPageToImage} et al. */ declare function interpretPage(page: PdfPage): DisplayList; //#endregion //#region src/render/rasterizer.d.ts /** Options controlling raster output. */ interface RenderOptions { /** Scale factor (1 = 72 dpi / 1 px per user unit). Overrides `dpi`. */ scale?: number | undefined; /** Target resolution in dots per inch (72 dpi = scale 1). */ dpi?: number | undefined; /** Background fill; `'transparent'` for a transparent canvas. Default white. */ background?: Rgba | "transparent" | undefined; /** Render text runs as positioned glyph boxes. Default `true`. */ renderText?: boolean | undefined; /** * Render only a pixel sub-window of the full-scale image (for tiling huge * pages). `x`/`y` are the tile's top-left in full-image pixel coordinates; * the returned image is `width`×`height`. */ region?: { x: number; y: number; width: number; height: number; } | undefined; } /** A raw RGBA8888 image. */ interface RasterImage { readonly data: Uint8Array; readonly width: number; readonly height: number; } /** Rasterize a display list to an RGBA8888 buffer. */ declare function rasterize(dl: DisplayList, opts?: RenderOptions): RasterImage; /** * Render a {@link PdfPage} to a PNG image. * @returns The PNG bytes plus pixel dimensions. */ declare function renderPageToImage(page: PdfPage, opts?: RenderOptions): Promise<{ data: Uint8Array; width: number; height: number; }>; //#endregion //#region src/render/canvas.d.ts /** The subset of the Canvas 2D context API used by the renderer. */ interface Canvas2DLike { save(): void; restore(): void; beginPath(): void; moveTo(x: number, y: number): void; lineTo(x: number, y: number): void; closePath(): void; fill(rule?: "nonzero" | "evenodd"): void; stroke(): void; fillRect(x: number, y: number, w: number, h: number): void; fillText(text: string, x: number, y: number): void; fillStyle: string; strokeStyle: string; lineWidth: number; font: string; } /** Options for Canvas rendering. */ interface CanvasRenderOptions { /** Scale (1 = 72 dpi). Overrides `dpi`. */ scale?: number | undefined; /** Target dpi (72 = scale 1). */ dpi?: number | undefined; /** `devicePixelRatio` to multiply into the scale (browser HiDPI). Default 1. */ pixelRatio?: number | undefined; /** Font family for text runs. Default `sans-serif`. */ fontFamily?: string | undefined; } /** Replay a display list onto a 2D context. */ declare function renderDisplayListToCanvas(dl: DisplayList, ctx: Canvas2DLike, opts?: CanvasRenderOptions): void; /** * Render a {@link PdfPage} onto a 2D context. The context's canvas should be * sized to `page.width × scale` by `page.height × scale`. */ declare function renderPageToCanvas(page: PdfPage, ctx: Canvas2DLike, opts?: CanvasRenderOptions): void; //#endregion //#region src/render/thumbnail.d.ts /** Options for {@link generateThumbnail}. */ interface ThumbnailOptions { /** Longest-side length in pixels. Default 256. */ maxSize?: number | undefined; /** Background fill (defaults to white via the rasterizer). */ background?: RenderOptions["background"]; /** Render text runs (as boxes). Default true. */ renderText?: boolean | undefined; } /** * Render `page` to a thumbnail PNG whose longest side is `maxSize` pixels, * preserving aspect ratio. */ declare function generateThumbnail(page: PdfPage, opts?: ThumbnailOptions): Promise<{ data: Uint8Array; width: number; height: number; }>; //#endregion //#region src/render/imageExtract.d.ts /** * A single decoded image extracted from a page's XObject resources. * * `pixels` is interleaved, row-major, 8-bit data: * - RGBA (4 channels) when {@link hasAlpha} is `true`, * - RGB (3 channels) for colour images without alpha, * - grayscale (1 channel) for `/DeviceGray` images without alpha. */ interface ExtractedImage { /** Resource name of the image XObject (without the leading slash, e.g. `Im1`). */ name: string; /** Image width in pixels. */ width: number; /** Image height in pixels. */ height: number; /** Number of interleaved channels in {@link pixels} (1, 3, or 4). */ channels: number; /** Interleaved 8-bit pixel data (RGBA, RGB, or grayscale). */ pixels: Uint8Array; /** Resolved colour-space name (e.g. `DeviceRGB`, `DeviceGray`, `DeviceCMYK`, `Indexed`). */ colorSpace: string; /** Bits per component of the source samples (typically `8`). */ bitsPerComponent: number; /** Whether {@link pixels} includes an alpha channel (4-channel RGBA). */ hasAlpha: boolean; } /** * Extract and decode all image XObjects referenced by a page. * * @param page - The page whose `/Resources /XObject` images are extracted. * @returns One {@link ExtractedImage} per successfully decoded image XObject. * Images that cannot be decoded (unsupported filters/colour spaces, * missing WASM, malformed data) are skipped silently. * * @example * ```ts * import { loadPdf } from 'modern-pdf-lib'; * import { extractImages } from 'modern-pdf-lib/render'; * * const doc = await loadPdf(bytes); * for (const img of extractImages(doc.getPage(0))) { * console.log(img.name, img.width, img.height, img.channels, img.hasAlpha); * } * ``` */ declare function extractImages(page: PdfPage): ExtractedImage[]; //#endregion //#region src/render/fontExtract.d.ts /** The on-disk format of an embedded font program. */ type FontFileFormat = "truetype" | "cff" | "opentype" | "type1"; /** A single embedded font program extracted from a page. */ interface ExtractedFont { /** Resource name under `/Font` (e.g. `F1`), without the leading slash. */ resourceName: string; /** The `/BaseFont` PostScript name, with any leading slash stripped. */ baseFont: string; /** Detected font-program format. */ format: FontFileFormat; /** The standalone, filter-decoded font bytes. */ data: Uint8Array; /** * `true` when {@link baseFont} carries a 6-uppercase-letter `+`-prefixed * subset tag (e.g. `ABCDEF+Helvetica`). */ subset: boolean; } /** * Extract every embedded font program referenced by a page. * * Walks the page's original `/Resources` → `/Font` dictionary. For each * font that carries an embedded file (`/FontFile`, `/FontFile2`, or * `/FontFile3`) — directly or via a Type0 descendant — the standalone, * filter-decoded font bytes are returned. Standard-14 fonts with no * embedded file are omitted, and malformed entries are skipped silently. * * @param page The page to scan (typically from a loaded PDF). * @returns One {@link ExtractedFont} per embedded font program. * * @example * ```ts * const loaded = await PdfDocument.load(bytes); * const fonts = extractFonts(loaded.getPage(0)); * for (const f of fonts) { * console.log(f.resourceName, f.baseFont, f.format, f.data.length, f.subset); * } * ``` */ declare function extractFonts(page: PdfPage): ExtractedFont[]; //#endregion //#region src/render/diff.d.ts /** Result of a visual comparison. */ interface DiffResult { readonly width: number; readonly height: number; /** Number of pixels whose max channel difference exceeds the threshold. */ readonly changedPixels: number; /** `changedPixels / (width·height)`. */ readonly changedRatio: number; /** Mean structural similarity over 8×8 luminance blocks, `0–1` (1 = identical). */ readonly ssim: number; /** RGBA heatmap: changed pixels in red over a dimmed grayscale of image A. */ readonly heatmap: Uint8Array; } /** Options for {@link compareImages}. */ interface CompareOptions { /** Per-channel difference (0–255) above which a pixel counts as changed. Default 16. */ threshold?: number | undefined; } /** Compare two equally-sized raster images. */ declare function compareImages(a: RasterImage, b: RasterImage, opts?: CompareOptions): DiffResult; /** Rasterize two pages at the same scale and compare them. */ declare function comparePages(pageA: PdfPage, pageB: PdfPage, opts?: RenderOptions & CompareOptions): Promise; //#endregion //#region src/render/ocr.d.ts /** * A single recognized word with its bounding box in **page space**. * * Coordinates follow the PDF convention: the origin is the lower-left corner * of the page and the y-axis points up. `x`/`y` are the lower-left corner of * the word box; `width`/`height` are its extent in page units (points). */ interface OcrWord { /** The recognized text of the word. */ text: string; /** X coordinate of the word box's lower-left corner, in page units. */ x: number; /** Y coordinate of the word box's lower-left corner (y-up), in page units. */ y: number; /** Width of the word box, in page units. */ width: number; /** Height of the word box, in page units. */ height: number; } /** * A pluggable OCR backend. * * Implementations receive an interleaved 8-bit RGBA bitmap of the rasterized * page (row-major, top-to-bottom, `width * height * 4` bytes) and return the * recognized words with **page-space** bounding boxes (see {@link OcrWord}). */ interface OcrEngine { /** * Recognize text in a rasterized page. * * @param rgba Interleaved RGBA8888 pixels (`width * height * 4` bytes). * @param width Bitmap width in pixels. * @param height Bitmap height in pixels. * @returns The recognized words, with page-space boxes. */ recognize(rgba: Uint8Array, width: number, height: number): Promise; } /** Options controlling {@link applyOcr}. */ interface ApplyOcrOptions { /** * Rasterization resolution handed to the engine, in dots per inch. * Higher values give the OCR engine more detail at the cost of memory. * Default: `150`. */ dpi?: number | undefined; /** * Resource name to use for the invisible overlay font. A standard * Helvetica Type 1 font is embedded under this name if it is not already * present. Default: `'OCRFont'`. */ fontResourceName?: string | undefined; } /** * Run OCR on a page and append the recognized text as an invisible, * selectable/searchable overlay. * * The page is rasterized to RGBA at `opts.dpi`, passed to `engine.recognize`, * and each returned word is written back as a content-stream fragment: * * ```text * BT 3 Tr / Tf Td () Tj ET * ``` * * where ` ≈ word.height` and ` ` is the word's lower-left corner * in page space. Render mode `3` makes the text invisible (no fill, no * stroke) while keeping it part of the document's text content. * * @param page The page to OCR and annotate. * @param engine The OCR backend. * @param opts Optional DPI and font-resource overrides. * @returns The words returned by the engine (unmodified). */ declare function applyOcr(page: PdfPage, engine: OcrEngine, opts?: ApplyOcrOptions): Promise; //#endregion //#region src/render/redactContent.d.ts /** A rectangular region to redact, in page space (PDF points, y-up, lower-left origin). */ interface RedactRect { /** X coordinate of the lower-left corner. */ x: number; /** Y coordinate of the lower-left corner. */ y: number; /** Width of the region (must be > 0 to match anything). */ width: number; /** Height of the region (must be > 0 to match anything). */ height: number; } /** The outcome of a {@link redactRegions} call. */ interface RedactResult { /** Number of text-showing operators removed. */ removedText: number; /** Number of image (`Do`) placements removed. */ removedImages: number; } /** * Permanently remove text and image content within the given regions from a * page (redaction by removal). * * The page's content stream is parsed, replayed through a position-tracking * graphics-state machine, and re-emitted with every text-showing operator and * image placement that falls inside any redaction rect omitted. All other * operators — paths, fills, colors, clips, state changes — are preserved, so * the surrounding page layout is left intact. The filtered content is written * back to the page and takes effect on the next `save()`. * * @param page The page to redact (modified in place). * @param rects Redaction regions in page space (PDF points, y-up). * @returns Counts of removed text runs and image placements. * * @example * ```ts * const result = redactRegions(page, [{ x: 0, y: 90, width: 200, height: 30 }]); * console.log(`Removed ${result.removedText} text runs`); * const bytes = await doc.save(); * ``` */ declare function redactRegions(page: PdfPage, rects: RedactRect[]): RedactResult; //#endregion //#region src/render/tiles.d.ts /** Options for tiling. */ interface TileOptions { /** Tile edge length in pixels. Default 512. */ tileSize?: number | undefined; /** Scale (1 = 72 dpi). Overrides `dpi`. */ scale?: number | undefined; /** Target dpi (72 = scale 1). */ dpi?: number | undefined; /** Background fill. */ background?: RenderOptions["background"]; /** Render text runs. Default true. */ renderText?: boolean | undefined; } /** Tile grid geometry for a page at a given scale. */ interface TileGrid { readonly columns: number; readonly rows: number; readonly tileSize: number; readonly fullWidth: number; readonly fullHeight: number; readonly scale: number; } /** Compute the tile grid for a page. */ declare function computeTileGrid(page: PdfPage, opts?: TileOptions): TileGrid; /** Render a single tile `(column, row)` of a page to an RGBA image. */ declare function renderPageTile(page: PdfPage, column: number, row: number, opts?: TileOptions): RasterImage; /** * A simple least-recently-used cache (Map-backed). Useful for memoizing * interpreted display lists or rasterized tiles across renders. */ declare class RenderCache { private readonly maxEntries; private readonly map; constructor(maxEntries?: number); /** Number of cached entries. */ get size(): number; /** Look up a value, marking it most-recently-used. */ get(key: string): V | undefined; /** Whether a key is present (without affecting recency). */ has(key: string): boolean; /** Insert/replace a value, evicting the LRU entry when over capacity. */ set(key: string, value: V): void; /** Remove a key. */ delete(key: string): boolean; /** Empty the cache. */ clear(): void; } //#endregion //#region src/compliance/afAttach.d.ts /** * Attach one or more associated files to any PDF object via its `/AF` key. * * Works uniformly for the document catalog, a page dictionary, an annotation * dictionary, a Form/Image XObject stream's dictionary, or a structure-element * dictionary — all of which are plain {@link PdfDict} instances. * * If `target` has no `/AF` yet, a fresh array (built with * {@link buildAfArray}) is set. If `/AF` is already a {@link PdfArray}, the * new refs are appended to it, preserving the existing entries and order. Any * other (malformed) `/AF` value is replaced with a fresh array. * * @param target The object dictionary to attach the files to. * @param fileSpecRefs Indirect references to file-specification dictionaries. */ declare function attachAssociatedFiles(target: PdfDict, fileSpecRefs: readonly PdfRef[]): void; /** * Complete {@link createAssociatedFile}'s "caller responsibility" by wiring a * file-specification reference into the document catalog at the *document * level*. * * Two things happen: * 1. The pair `[PdfString.literal(name), fileSpecRef]` is added to the * catalog's `/Names` → `/EmbeddedFiles` → `/Names` array, keeping the * array's name/value pairs sorted by name (as required for a name tree). * The intermediate dictionaries and the leaf array are created on demand * and reused if already present. * 2. `fileSpecRef` is added to the catalog's `/AF` array (via * {@link attachAssociatedFiles}). * * @param catalog The document catalog dictionary. * @param name The name under which the file is registered in the tree. * @param fileSpecRef Indirect reference to the file-specification dictionary. */ declare function registerEmbeddedFile(catalog: PdfDict, name: string, fileSpecRef: PdfRef): void; //#endregion //#region src/compliance/pageOutputIntent.d.ts /** * Attach output-intent references to a target dictionary's `/OutputIntents` * array. * * If the target has no `/OutputIntents` entry, a fresh {@link PdfArray} is * created and populated with `intentRefs`. If one already exists (and is an * array), the references are appended to it in order, preserving the existing * array instance. * * The target may be a page dictionary (for per-page intents) or a Form * XObject stream's dictionary (for per-stream intents). * * @param target The page or Form XObject dictionary to mutate. * @param intentRefs Indirect references to `/OutputIntent` dictionaries. */ declare function attachOutputIntents(target: PdfDict, intentRefs: readonly PdfRef[]): void; /** * Options for a per-page / per-stream output intent. */ interface PageOutputIntentOptions { /** * Custom ICC profile bytes to embed as the `/DestOutputProfile`. * * @default Built-in minimal sRGB ICC v2 profile. */ iccProfile?: Uint8Array | undefined; /** * Number of colour components in the ICC profile (3 = RGB, 4 = CMYK, * 1 = Gray). Must match the embedded profile's colour space. * * @default 3 */ components?: number | undefined; /** * Formal registry identifier for the output condition (`/OutputConditionIdentifier`). */ outputConditionIdentifier?: string | undefined; /** * Human-readable additional information about the intended output device, * stored as the optional `/Info` entry. */ info?: string | undefined; /** * Output-intent subtype (`/S`). Common values are `/GTS_PDFA1` (PDF/A) and * `/GTS_PDFX` (PDF/X). * * @default '/GTS_PDFA1' */ subtype?: string | undefined; } /** * Build a per-page / per-stream `/OutputIntent` dictionary and register it. * * The embedded ICC `/DestOutputProfile` is produced by reusing * {@link buildOutputIntent}; this builder then layers the per-page subtype * (`/S`), output-condition identifier and optional `/Info` string on top. * The resulting dictionary carries `/Type /OutputIntent` and may be attached * to a page or Form XObject dictionary via {@link attachOutputIntents}. * * @param registry The PDF object registry to register objects into. * @param options Output-intent configuration. * @returns An indirect reference to the `/OutputIntent` dictionary. */ declare function buildPageOutputIntent(registry: PdfObjectRegistry, options?: PageOutputIntentOptions): PdfRef; //#endregion //#region src/compliance/encryptedPayload.d.ts /** Options for building an `/EncryptedPayload` dictionary. */ interface EncryptedPayloadOptions { /** * Name of the crypto filter that protects the payload, without the leading * slash (for example `'AESV3'`). Emitted as the `/Subtype` name. */ readonly subtype: string; /** * Optional version of the crypto filter, without the leading slash. * Emitted as the `/Version` name when present. */ readonly version?: string | undefined; } /** Options for embedding an encrypted payload as an unencrypted wrapper. */ interface WrapperPayloadOptions { /** The (already encrypted) payload bytes to embed. */ readonly data: Uint8Array; /** The filename to record on the embedded file specification. */ readonly filename: string; /** * Name of the crypto filter that protects the payload, without the leading * slash (for example `'AESV3'`). */ readonly subtype: string; /** Optional version of the crypto filter, without the leading slash. */ readonly version?: string | undefined; /** Optional human-readable description of the embedded payload. */ readonly description?: string | undefined; } /** * Build an `/EncryptedPayload` dictionary (ISO 32000-2 §7.6.7). * * The returned dictionary has: * - `/Type /EncryptedPayload` * - `/Subtype /` — the crypto filter name * - `/Version /` — only when {@link EncryptedPayloadOptions.version} * is supplied * * @param options - The crypto-filter subtype and optional version. * @returns A spec-shaped `/EncryptedPayload` {@link PdfDict}. */ declare function buildEncryptedPayload(options: EncryptedPayloadOptions): PdfDict; /** * Build the embedded encrypted-payload file for an unencrypted wrapper * document and return its file-specification reference. * * The payload bytes are embedded via {@link createAssociatedFile} with an * `/AFRelationship` of `/EncryptedPayload` and an `application/octet-stream` * MIME type. The resolved file-specification dictionary then receives an * `/EP` entry holding the {@link buildEncryptedPayload} dictionary. * * The caller is responsible for attaching the returned file-spec reference to * the catalog `/AF` array and the `/Names /EmbeddedFiles` name tree. * * @param registry - The PDF object registry to register objects into. * @param options - The payload bytes, filename, crypto subtype/version, and * optional description. * @returns An indirect reference to the file-specification dictionary. */ declare function buildUnencryptedWrapper(registry: PdfObjectRegistry, options: WrapperPayloadOptions): PdfRef; //#endregion //#region src/core/softMask.d.ts /** * Options describing a soft-mask group to wrap in an `ExtGState`. */ interface SoftMaskGroupOptions { /** * Indirect reference to the transparency-group form XObject that supplies * the mask. Its `/Group` dictionary must declare `/S /Transparency`. */ readonly groupXObject: PdfRef; /** * Mask subtype: `'Luminosity'` (default) measures the composited * luminosity, `'Alpha'` measures the accumulated alpha. */ readonly type?: "Luminosity" | "Alpha" | undefined; /** * Backdrop colour the group is composited against before the luminosity is * measured. Component count must match the group's colour space. Honoured * only for luminosity masks; ignored for alpha masks. */ readonly backdropColor?: readonly number[] | undefined; /** * Transfer function remapping computed mask values — either an indirect * reference to a function object or the literal name `'Identity'`. */ readonly transferFunction?: PdfRef | "Identity" | undefined; } /** * Build an `ExtGState` dictionary that installs a soft-mask group. * * The returned dictionary has `/Type /ExtGState` and an `/SMask` mask * dictionary: * * - `/Type /Mask` * - `/S /Luminosity` or `/S /Alpha` (per {@link SoftMaskGroupOptions.type}, * defaulting to `Luminosity`) * - `/G` → the supplied group XObject reference * - `/BC [ … ]` — backdrop colour, **only** for luminosity masks and only * when {@link SoftMaskGroupOptions.backdropColor} is provided * - `/TR` → the transfer function (indirect reference) or the name * `/Identity`, only when {@link SoftMaskGroupOptions.transferFunction} is * provided * * @param options - The soft-mask group description. * @returns A spec-shaped `ExtGState` {@link PdfDict}. */ declare function buildSoftMaskGroupExtGState(options: SoftMaskGroupOptions): PdfDict; /** * Build an `ExtGState` dictionary that clears any active soft mask by setting * `/SMask /None`. Apply this after a masked region to restore unmasked * painting. * * @returns An `ExtGState` {@link PdfDict} with `/SMask /None`. */ declare function buildSoftMaskNone(): PdfDict; //#endregion //#region src/core/imageMask.d.ts /** * Build a stencil mask: a 1-bit `/ImageMask` image XObject (§8.9.6.2). * * The returned stream has `/Type /XObject`, `/Subtype /Image`, * `/ImageMask true`, `/BitsPerComponent 1`, and the supplied `/Width` and * `/Height`. When a `decode` pair is given it is emitted as a `/Decode` * array, allowing the mask polarity to be inverted (`[1 0]`). * * The `bits` buffer must already be packed one bit per sample with each row * byte-aligned (`ceil(width / 8)` bytes per row); this builder stores it * verbatim and does not repack it. * * @param registry - Registry to register the stream into. * @param bits - Packed, byte-aligned 1-bpc mask data. * @param width - Image width in samples. * @param height - Image height in samples. * @param decode - Optional `[d0, d1]` decode pair. * @returns An indirect reference to the registered image XObject stream. */ declare function buildStencilMask(registry: PdfObjectRegistry, bits: Uint8Array, width: number, height: number, decode?: readonly [number, number] | undefined): PdfRef; /** * Build a colour-key masking array (§8.9.6.4). * * The `ranges` list holds two integers — a minimum and a maximum — per * colour component, laid out as `[min0 max0 min1 max1 …]`. Sample colours * whose every component falls within its range become transparent. The * returned {@link PdfArray} is assigned to a base image's `/Mask` entry. * * @param ranges - An even-length list of `[min, max]` integer pairs. * @returns A `/Mask` {@link PdfArray} of {@link PdfNumber}s. * @throws RangeError if `ranges` is empty or has an odd length. */ declare function buildColorKeyMask(ranges: readonly number[]): PdfArray; /** * Build an image soft mask: a DeviceGray image XObject usable as a base * image's `/SMask` (§11.6.5.2). * * The returned stream has `/Type /XObject`, `/Subtype /Image`, * `/ColorSpace /DeviceGray`, the supplied `/Width` and `/Height`, and * `/BitsPerComponent` (defaulting to 8). Each grayscale sample provides the * opacity of the corresponding base-image pixel. * * @param registry - Registry to register the stream into. * @param gray - Grayscale opacity samples. * @param width - Image width in samples. * @param height - Image height in samples. * @param bitsPerComponent - Bits per sample; defaults to 8. * @returns An indirect reference to the registered soft-mask image XObject. */ declare function buildImageSoftMask(registry: PdfObjectRegistry, gray: Uint8Array, width: number, height: number, bitsPerComponent?: number | undefined): PdfRef; /** * Build an ExtGState that controls black-point compensation (§8.6.5.9). * * The returned dictionary has `/Type /ExtGState` and `/UseBlackPtComp` set * to the requested mode: * * - `Default` — leave the choice to the conforming reader. * - `ON` — always apply black-point compensation. * - `OFF` — never apply black-point compensation. * * @param mode - The `/UseBlackPtComp` mode. * @returns An ExtGState {@link PdfDict}. */ declare function buildBlackPointCompensationExtGState(mode: "Default" | "ON" | "OFF"): PdfDict; //#endregion //#region src/accessibility/taggingHelpers.d.ts /** * The set of values that the PDF list-attribute `/ListNumbering` may * take (ISO 32000, Table 384, owner `/List`). These determine how a * list's item labels are presented to assistive technology: * * - `None` — no autogenerated numbering (labels are explicit). * - `Disc`, `Circle`, `Square` — unordered bullet glyphs. * - `Decimal` — `1`, `2`, `3`, … * - `UpperRoman` — `I`, `II`, `III`, … * - `LowerRoman` — `i`, `ii`, `iii`, … * - `UpperAlpha` — `A`, `B`, `C`, … * - `LowerAlpha` — `a`, `b`, `c`, … */ type ListNumbering = "None" | "Disc" | "Circle" | "Square" | "Decimal" | "UpperRoman" | "LowerRoman" | "UpperAlpha" | "LowerAlpha"; /** * The property key under which {@link tagList} records the chosen * {@link ListNumbering} on a list element's `options` object. * * `StructureElementOptions` has no dedicated `listNumbering` field, so * the value is stored as an extra (string-keyed) property on the same * options object. When the structure tree is serialized this is the * value an attribute writer should emit as the list's `/ListNumbering` * entry inside an `/A` attribute dictionary whose owner is `/List` * (ISO 32000, Table 384): * * ``` * /A << /O /List /ListNumbering /Decimal >> * ``` * * Using a well-known string key (rather than a `Symbol`) keeps the * value plain-serializable and inspectable from tests. */ declare const LIST_NUMBERING_KEY: "__listNumbering"; /** * Tag a heading element of the given level. * * @param tree The structure tree to add the element to. * @param parent The parent element, or `null` to add under the root * `Document` element. * @param level The heading level (`1`..`6`); maps to `H1`..`H6`. * @param options Optional attributes (title, language, id, …). * @returns The newly created heading element (type `H1`..`H6`). * * @example * ```ts * const tree = doc.createStructureTree(); * const h2 = tagHeading(tree, null, 2, { title: 'Background' }); * // h2.type === 'H2' * ``` */ declare function tagHeading(tree: PdfStructureTree, parent: PdfStructureElement | null, level: 1 | 2 | 3 | 4 | 5 | 6, options?: StructureElementOptions): PdfStructureElement; /** * Tag a paragraph (`P`) element. * * @param tree The structure tree to add the element to. * @param parent The parent element, or `null` for the root. * @param options Optional attributes. * @returns The newly created `P` element. */ declare function tagParagraph(tree: PdfStructureTree, parent: PdfStructureElement | null, options?: StructureElementOptions): PdfStructureElement; /** * Tag a figure (`Figure`) element with alternative text. * * The `altText` argument is required because PDF/UA mandates * alternative text for illustration elements. If the caller also * supplies `altText` in `options`, that explicit value takes * precedence over the positional argument. * * @param tree The structure tree to add the element to. * @param parent The parent element, or `null` for the root. * @param altText Alternative text describing the figure. * @param options Optional additional attributes. * @returns The newly created `Figure` element with `/Alt` set. */ declare function tagFigure(tree: PdfStructureTree, parent: PdfStructureElement | null, altText: string, options?: StructureElementOptions): PdfStructureElement; /** * Tag a link (`Link`) element. * * @param tree The structure tree to add the element to. * @param parent The parent element, or `null` for the root. * @param options Optional attributes. * @returns The newly created `Link` element. */ declare function tagLink(tree: PdfStructureTree, parent: PdfStructureElement | null, options?: StructureElementOptions): PdfStructureElement; /** * Tag a list (`L`) element and record its numbering style. * * The chosen {@link ListNumbering} is stored on the returned element's * `options` object under {@link LIST_NUMBERING_KEY} (since * `StructureElementOptions` has no dedicated field). A serializer can * emit it as the list's `/ListNumbering` attribute (ISO 32000, * Table 384) inside an `/A` dictionary owned by `/List`. * * @param tree The structure tree to add the element to. * @param parent The parent element, or `null` for the root. * @param numbering The list numbering style (default `'None'`). * @param options Optional additional attributes. * @returns The newly created `L` element. */ declare function tagList(tree: PdfStructureTree, parent: PdfStructureElement | null, numbering?: ListNumbering, options?: StructureElementOptions): PdfStructureElement; /** * The constituent elements created for a single list item by * {@link tagListItem}. */ interface TaggedListItem { /** The `LI` (list item) element. */ readonly item: PdfStructureElement; /** The `Lbl` (label) element — the item's bullet/number. */ readonly label: PdfStructureElement; /** The `LBody` (list body) element — the item's content. */ readonly body: PdfStructureElement; } /** * Tag a list item under a list, building the conventional * `LI` → (`Lbl`, `LBody`) substructure. * * @param tree The structure tree to add the elements to. * @param list The parent `L` (list) element. * @param options Optional attributes for the `LI` element. * @returns The created `item` (`LI`), `label` (`Lbl`) and * `body` (`LBody`) elements. * * @example * ```ts * const list = tagList(tree, null, 'Decimal'); * const { item, label, body } = tagListItem(tree, list); * // item.type === 'LI', label.type === 'Lbl', body.type === 'LBody' * ``` */ declare function tagListItem(tree: PdfStructureTree, list: PdfStructureElement, options?: StructureElementOptions): TaggedListItem; /** * Tag a table (`Table`) element. * * @param tree The structure tree to add the element to. * @param parent The parent element, or `null` for the root. * @param options Optional attributes. * @returns The newly created `Table` element. */ declare function tagTable(tree: PdfStructureTree, parent: PdfStructureElement | null, options?: StructureElementOptions): PdfStructureElement; /** * Tag a table row (`TR`) under a table. * * @param tree The structure tree to add the element to. * @param table The parent `Table` element. * @returns The newly created `TR` element. */ declare function tagTableRow(tree: PdfStructureTree, table: PdfStructureElement): PdfStructureElement; /** * Tag a table header cell (`TH`) under a row, recording its scope. * * The `scope` is stored in the element's options (`/Scope` attribute, * one of `Row`, `Column`, or `Both`) and is used by table-header * validation to associate header cells with the cells they describe. * * @param tree The structure tree to add the element to. * @param row The parent `TR` element. * @param scope The header scope (default `'Column'`). * @param options Optional additional attributes (e.g. colSpan/rowSpan). * @returns The newly created `TH` element with `scope` set. */ declare function tagTableHeaderCell(tree: PdfStructureTree, row: PdfStructureElement, scope?: "Row" | "Column" | "Both", options?: StructureElementOptions): PdfStructureElement; /** * Tag a table data cell (`TD`) under a row. * * @param tree The structure tree to add the element to. * @param row The parent `TR` element. * @param options Optional attributes (e.g. colSpan/rowSpan). * @returns The newly created `TD` element. */ declare function tagTableDataCell(tree: PdfStructureTree, row: PdfStructureElement, options?: StructureElementOptions): PdfStructureElement; //#endregion //#region src/accessibility/pdfUa2.d.ts /** * A single PDF/UA-2 conformance issue. * * Every issue carries a machine-readable {@link code}, a human-readable * {@link message}, and the ISO 14289-2 {@link clause} the requirement is * drawn from. */ interface PdfUa2Issue { /** Machine-readable issue code (e.g. `"UA2-STRUCT-001"`). */ code: string; /** Human-readable description of the violation. */ message: string; /** The ISO 14289-2 clause reference for the requirement. */ clause: string; } /** * Result of a {@link validatePdfUa2} check. * * `conformant` is `true` only when there are no issues. */ interface PdfUa2Result { /** Whether the document satisfies all PDF/UA-2 requirements checked. */ conformant: boolean; /** The list of conformance issues (empty when conformant). */ issues: PdfUa2Issue[]; } /** * Validate a PDF document against PDF/UA-2 (ISO 14289-2) requirements. * * The check reuses {@link validatePdfUa} for the shared tagging, language, * MarkInfo, and metadata requirements, then layers the PDF 2.0 / UA-2 * specific requirements on top: * * - **UA2-STRUCT-001** — a structure tree must exist (tagged PDF). * - **UA2-NS-001** — the structure tree must declare structure * `/Namespaces` (PDF/UA-2 builds on PDF 2.0 namespaces). * - **UA2-LANG-001** — the document must declare a natural language * (`/Lang`). * - **UA2-FIG-001** — every figure must carry alternative text. * * Each failure is mapped to an ISO 14289-2 clause string. The returned * result is `conformant` only when there are no issues. * * @param doc The PDF document to validate. * @returns A {@link PdfUa2Result} describing conformance and issues. * * @example * ```ts * import { createPdf } from 'modern-pdf-lib'; * import { validatePdfUa2 } from 'modern-pdf-lib/accessibility'; * * const doc = createPdf(); * const result = validatePdfUa2(doc); * if (!result.conformant) { * for (const issue of result.issues) { * console.error(`[${issue.code}] ${issue.message} (§${issue.clause})`); * } * } * ``` */ declare function validatePdfUa2(doc: PdfDocument): PdfUa2Result; /** * Build an XMP packet (RDF/XML) that identifies a document as PDF/UA-2. * * The packet declares the AIIM PDF/UA identification schema * (`pdfuaid`, namespace `http://www.aiim.org/pdfua/ns/id/`) with: * * - `pdfuaid:part` = `2` — the PDF/UA part (ISO 14289-2); * - `pdfuaid:rev` = the revision year of the standard. * * The result is a serialized, packet-wrapped XMP string suitable for * embedding as the document's `/Metadata` stream. * * @returns The serialized PDF/UA-2 identification XMP packet. * * @example * ```ts * import { buildPdfUa2Xmp } from 'modern-pdf-lib/accessibility'; * * doc.setXmpMetadata(buildPdfUa2Xmp()); * ``` */ declare function buildPdfUa2Xmp(): string; //#endregion //#region src/accessibility/autoTag.d.ts /** * Options controlling heuristic auto-tagging. */ interface AutoTagOptions { /** * A text run whose font size is `>= headingScale × bodySize` is treated * as a heading. The body size is the most common (median) font size on * the page. Defaults to `1.2` (a run 20% larger than body text is a * heading). */ headingScale?: number | undefined; } /** * Summary of what {@link autoTagPage} inferred and added to the structure * tree. */ interface AutoTagResult { /** Number of heading (`H1`..`H6`) elements added. */ headings: number; /** Number of paragraph (`P`) elements added. */ paragraphs: number; /** Total number of structure elements added (headings + paragraphs). */ elements: number; } /** * Infer a coarse logical structure for a single untagged page and add the * inferred `H1`..`H6` and `P` elements to the document's structure tree. * * The procedure: * 1. Interpret the page into positioned text runs. * 2. Group runs into visual lines by their baseline y-position. * 3. Determine the body font size as the median run font size. * 4. Order lines top-to-bottom (reading order on a y-up page). * 5. Classify each line as a heading (font size `>= headingScale × body`) * or body text; map distinct heading sizes to `H1`..`H6` * (largest → `H1`). * 6. Emit one heading element per heading line and one `P` element per * contiguous block of body lines. * * Never throws on an empty (or text-free) page — it returns all-zero * counts and leaves the structure tree untouched. * * @param doc The document containing the page. * @param pageIndex Zero-based index of the page to tag. * @param options Optional heuristic tuning ({@link AutoTagOptions}). * @returns Counts of the elements that were added. */ declare function autoTagPage(doc: PdfDocument, pageIndex: number, options?: AutoTagOptions): AutoTagResult; //#endregion //#region src/compliance/profileConvert.d.ts /** * A single preflight finding produced by {@link preflightPdfA}. * * `code` mirrors the `PDFA-0xx` vocabulary of the byte-level `validatePdfA` * validator. `fixable` indicates whether a downstream enforcement step can * resolve the issue automatically. `clause` is an optional ISO clause hint. */ interface PreflightIssue { readonly code: string; readonly message: string; readonly severity: "error" | "warning"; readonly fixable: boolean; readonly clause?: string | undefined; } /** * Run a synchronous, pre-save PDF/A preflight over an in-memory document. * * See the module documentation for the (intentional) scope and limitations of * this check relative to the byte-level `validatePdfA` validator. * * @param doc - The in-memory document to inspect. Never mutated. * @param level - Optional target level (e.g. `'2b'`, `'3u'`, `'PDF/A-4'`). * Only used to refine messages; all checks here are * level-agnostic prerequisites common to every PDF/A part. * @returns A (possibly empty) list of preflight issues. Never throws. */ declare function preflightPdfA(doc: PdfDocument, level?: string): PreflightIssue[]; /** * Remap the PDF/A identification (`pdfaid:part`, and optionally * `pdfaid:conformance`) inside an existing XMP packet. * * Both the **attribute** form (`pdfaid:part="3"`) and the **element** form * (`3`) are handled. When no `pdfaid:part` is * present, identification is injected into the first `rdf:Description` element * (declaring the `pdfaid` namespace on it if necessary). All other content of * the packet is preserved verbatim. * * This is a pure string transform; it does not parse or re-serialize the XML. * * @param xmp - The source XMP packet string. * @param toPart - Target PDF/A part (1, 2, 3 or 4). * @param toConformance - Optional target conformance level (`a`/`b`/`u`). When * omitted, any existing conformance is left untouched. * @returns The transformed XMP packet string. */ declare function convertPdfAConformanceXmp(xmp: string, toPart: 1 | 2 | 3 | 4, toConformance?: "a" | "b" | "u"): string; //#endregion //#region src/compliance/rasterProfile.d.ts /** * @module compliance/rasterProfile * * Identification XMP packet builders for two PDF 2.0-era conformance * profiles that, unlike PDF/A and PDF/UA, do **not** define their own * ISO `…id/`-style XMP identification namespace: * * - **WTPDF** — "Well-Tagged PDF" (PDF Association specification, * "Using Tagged PDF for Accessibility and Reuse in PDF 2.0", v1.0, * February 2024). * - **PDF/R** — "Raster image transport and storage" (ISO 23504-1:2020, * the ISO version of the PDF Association's PDF/Raster 1.0 spec). * * These builders emit *identification markers only*. They assert which * profile a document claims to follow; they do **not** validate or * guarantee conformance, and they do not mutate any PDF document. * * --------------------------------------------------------------------------- * WHAT IS VERIFIED vs. WHAT IS PROVISIONAL * --------------------------------------------------------------------------- * * VERIFIED (from primary / corroborated sources): * * - WTPDF conformance is asserted via the PDF Association **"PDF * Declarations"** mechanism embedded in document-level XMP — NOT via a * bespoke `pdfwtid:part`/`conformance` namespace. PDF Declarations use * the namespace prefix `pdfd` with namespace URI `http://pdfa.org/ * declarations/`, an `pdfd:declarations` container holding an `rdf:Bag` * of declaration resources, each with a `pdfd:conformsTo` URI and an * optional `pdfd:claimData` block (`pdfd:claimBy`, `pdfd:claimDate`, * `pdfd:claimCredentials`, `pdfd:claimReport`). * (PDF Association, "PDF Declarations — A use of ISO 32000", 2019; * "Industry-recognized PDF Declarations".) * * - WTPDF 1.0 defines two conformance levels: **reuse** and * **accessibility**. (PDF Association WTPDF 1.0.) * * - PDF/R (ISO 23504 / PDF/Raster 1.0) is primarily identified by a * PDF *comment marker placed immediately before the final `startxref`* * in the file trailer — it has **no ISO-defined XMP identification * namespace**. (PDF Association, "PDF/raster: An Overview"; * ISO 23504-1:2020.) Any XMP-based identification for PDF/R is therefore * non-normative. * * - The general ISO XMP identification pattern (used by `pdfaid` / * `pdfuaid`) renders an integer `part`, an optional 4-digit-year `rev`, * and a `conformance` token inside an `rdf:Description rdf:about=""`. * * PROVISIONAL / UNVERIFIED (clearly flagged; do not treat as normative): * * - The exact `pdfd:conformsTo` target URIs used below for WTPDF and * PDF/R. The WTPDF declaration URI form is *explicitly acknowledged as * inconsistent* in the source material: the PDF Association corrected it * from `http://pdfa.org/declarations#wtpdf-reuse1.0` to * `http://pdfa.org/declarations/wtpdf#reuse1.0`, and even the trailing * `/`-vs-`#` form remains contested (see pdf-association/pdf-issues * #395). We therefore treat the precise fragment as provisional. * * - No PDF/R `conformsTo` URI is published under the PDF Declarations * registry at the time of writing; the value used here follows the same * pattern and is provisional. * * Because of the above, callers MUST NOT rely on byte-for-byte matching of * the emitted `conformsTo` URIs for normative validation. The verified, * stable parts are the XMP envelope, the `pdfd` namespace/structure, and * the rendered `part`/`conformance` values. * * @see https://pdfa.org/wtpdf/ * @see https://pdfa.org/resource/pdf-declarations/ * @see https://pdfa.org/resource/iso-23504-pdfr/ * @see https://github.com/pdf-association/pdf-issues/issues/395 */ /** Options for building a profile identification XMP packet. */ interface ProfileXmpOptions { /** * The standard's part number. Defaults to `1` * (WTPDF 1.0 / ISO 23504-1, i.e. PDF/R-1). */ part?: number | undefined; /** * The conformance level / token. Optional and free-form because these * profiles do not share a single normative conformance vocabulary * (e.g. WTPDF uses `'reuse'` | `'accessibility'`). */ conformance?: string | undefined; } /** * Build a WTPDF ("Well-Tagged PDF") identification XMP packet. * * WTPDF conformance is asserted through the PDF Association's PDF * Declarations mechanism (VERIFIED). The `conformsTo` target URI is * PROVISIONAL — see the module doc comment and pdf-issues #395 for the * acknowledged inconsistency in its exact form. This builder produces an * identification marker only and does not assert or validate WTPDF * conformance. * * @param options - Optional part (default `1`, i.e. WTPDF 1.0) and a * conformance level (WTPDF defines `'reuse'` and `'accessibility'`). * @returns A serialized XMP/RDF identification packet. */ declare function buildWtpdfIdentificationXmp(options?: ProfileXmpOptions): string; /** * Build a PDF/R (ISO 23504 / PDF/Raster) identification XMP packet. * * IMPORTANT: PDF/R is normatively identified by a comment marker before * the final `startxref` in the file trailer, NOT by XMP. There is no * ISO-defined XMP identification namespace for PDF/R, so this XMP marker * is non-normative: the `pdfd:conformsTo` target is PROVISIONAL. Use this * only as a supplementary, machine-readable hint alongside the required * trailer comment marker; it does not assert or validate PDF/R * conformance. * * @param options - Optional part (default `1`, i.e. ISO 23504-1 / PDF/R-1) * and a conformance token. * @returns A serialized XMP/RDF identification packet. */ declare function buildPdfRIdentificationXmp(options?: ProfileXmpOptions): string; //#endregion //#region src/compliance/facturXAssemble.d.ts /** Options for {@link assembleFacturX}. */ interface FacturXAssembleOptions { /** Factur-X / ZUGFeRD profile (conformance level). Default: `'EN16931'`. */ readonly profile?: FacturXProfile | undefined; /** Embedded XML file name. Default: `'factur-x.xml'`. */ readonly filename?: string | undefined; } /** * Build the Factur-X PDF/A-3 XMP extension metadata. * * Returns an XMP RDF fragment containing two `rdf:Description` blocks: * * 1. The **actual Factur-X values** in the `fx:` namespace — * `fx:DocumentType` (`INVOICE`), `fx:DocumentFileName`, `fx:Version` * (`1.0`) and `fx:ConformanceLevel` (derived from `profile`). * 2. The **PDF/A extension-schema description** (`pdfaExtension:schemas`), * which is required for PDF/A-3 conformance so that validators can resolve * the custom `fx:` properties. * * The fragment is rooted at `` so it can be merged into a larger XMP * packet (e.g. alongside the `pdfaid`, `dc`, `xmp` and `pdf` descriptions * produced by the PDF/A XMP generator). * * @param profile The Factur-X / ZUGFeRD profile. * @param documentFileName The embedded XML file name. Must match the name under * which the XML is attached. Default: `'factur-x.xml'`. * @returns The XMP RDF string. */ declare function buildFacturXXmp(profile: FacturXProfile, documentFileName?: string): string; /** * Assemble a hybrid Factur-X PDF/A-3 invoice. * * Generates the CII XML for `invoice` under the requested profile, encodes it * as UTF-8 bytes and attaches it to `doc` as a PDF/A-3 associated file with the * `/Alternative` relationship (referenced from the catalog `/AF` array). * * The XMP from {@link buildFacturXXmp} can be merged into the document's * metadata by the caller to complete PDF/A-3 / Factur-X conformance. * * @param doc The target PDF document (should already be PDF/A-3 shaped). * @param invoice The invoice data. * @param options Optional profile and embedded file name. * @returns The generated CII XML string. */ declare function assembleFacturX(doc: PdfDocument, invoice: Invoice, options?: FacturXAssembleOptions): string; //#endregion //#region src/compliance/eInvoiceValidate.d.ts /** A single EN 16931 business-rule violation. */ interface EInvoiceIssue { /** The EN 16931 rule id, e.g. 'BR-02' or 'BR-CO-15'. */ readonly rule: string; /** Human-readable description of the violation. */ readonly message: string; /** Severity: a hard rule breach ('error') or an advisory ('warning'). */ readonly severity: "error" | "warning"; } /** * Document-level totals the caller intends to write onto the invoice. * * The base {@link Invoice} model computes its totals from the lines, so a * mismatch can only exist when a caller declares its own totals. Supplying * these enables the BR-CO-* calculation-chain checks; omitting them skips * those checks entirely (the computed totals are consistent by definition). * * All amounts are in the invoice currency. */ interface DeclaredInvoiceTotals { /** Sum of Invoice line net amounts (BT-106). */ readonly lineTotal: number; /** * Invoice total amount without VAT / tax basis total (BT-109). * Defaults to {@link DeclaredInvoiceTotals.lineTotal} when omitted, * since the model carries no document-level allowances or charges. */ readonly taxBasisTotal?: number | undefined; /** Invoice total VAT amount (BT-110). */ readonly taxTotal: number; /** Invoice total amount with VAT / grand total (BT-112). */ readonly grandTotal: number; /** Amount due for payment (BT-115). Defaults to the grand total. */ readonly duePayable?: number | undefined; } /** * An {@link Invoice} optionally annotated with the document-level totals * the caller plans to emit, enabling the BR-CO-* calculation checks. * * A plain {@link Invoice} is assignable to this type, so * {@link validateEn16931} accepts either. */ interface ValidatableInvoice extends Invoice { /** Declared document totals to validate against the line-derived totals. */ readonly declaredTotals?: DeclaredInvoiceTotals | undefined; } /** * Validate an invoice against the core EN 16931 business rules that are * checkable from the typed {@link Invoice} model. * * Content-presence rules (BR-02, BR-03, BR-05, BR-06, BR-07, BR-16) are * always evaluated. The totals-calculation chain (BR-CO-10, BR-CO-13, * BR-CO-15, BR-CO-16) is only evaluated when the caller supplies * {@link ValidatableInvoice.declaredTotals}; otherwise those checks are * skipped because the model derives consistent totals from its lines. * * The function never throws; a structurally valid invoice returns `[]`. * * @param invoice - The invoice (optionally annotated with declared totals). * @returns A list of {@link EInvoiceIssue}s, empty when fully valid. */ declare function validateEn16931(invoice: ValidatableInvoice): EInvoiceIssue[]; //#endregion //#region src/compliance/ciiReader.d.ts /** * Parse a UN/CEFACT Cross Industry Invoice (CII) XML string into the * typed {@link Invoice} model. * * The parser is namespace-prefix tolerant (it matches on local element * names) and recovers the invoice number, issue date, currency, the * seller and buyer parties (name, country, VAT id) and every line item * (description, quantity, unit price, tax rate). * * @param xml - The CII XML document. * @returns The parsed {@link Invoice}. * @throws If the input does not contain a `CrossIndustryInvoice` root. */ declare function parseCiiXml(xml: string): Invoice; /** * Detect the Factur-X / ZUGFeRD profile of a CII XML document by reading * its `GuidelineSpecifiedDocumentContextParameter/ID` (the profile URN) * and mapping it back to a {@link FacturXProfile}. * * @param xml - The CII XML document. * @returns The matching {@link FacturXProfile}, or `undefined` if no * guideline URN is present or it does not match a known profile. */ declare function detectFacturXProfile(xml: string): FacturXProfile | undefined; declare namespace index_d_exports { export { AFDate_FormatEx, AFNumber_Format, AFRelationship, AFSpecial_Format, AccessibilityIssue, AccessibilityPluginOptions, AddBookmarkOptions, AnalysisReport, AnalyzeImagesOptions, Angle, AnnotationFlags, AnnotationOptions, AnnotationType, AppearanceProviderFor, AppendOptions, ApplyOcrOptions, AssociatedFileOptions, AssociatedFileResult, AutoTagOptions, AutoTagResult, AvarSegmentMap, BarcodeMatrix, BarcodeOptions, BarcodeReadResult, BatchErrorStrategy, BatchOptimizeOptions, BatchOptions, BatchProcessingError, BatchProgressCallback, BatchResult, BidiDirection, BidiResult, BidiRun, BitsPerComponent, BitsPerCoordinate, BitsPerFlag, BlendMode$1 as BlendMode, BookmarkNode, BookmarkRef, BoxGeometry, ButtonAppearanceOptions, ByteRangeResult, ByteWriter, CIDFontData, CIDSystemInfoData, CalGrayParams, CalRGBParams, Canvas2DLike, CanvasRenderOptions, CaretSymbol, CatalogOptions, CellContent, CertPathResult, ChangeTracker, CheckboxAppearanceOptions, ChromaSubsampling, CmykColor, Code128Options, Code39Options, CodeFrameOptions, CollectionOptions, CollectionSchemaField, CollectionView, Color, ColorFontInfo, ColorGlyphLayer, ColorStop, CombedTextLayoutError, CompareOptions, CompositeOp, ComputeFontSizeOptions, ContentStreamOperator, CoonsPatch, CoonsPatchOptions, CounterSignatureInfo, CpalPalette, CropBox, DEFAULT_DOC_TIMESTAMP_CONTENTS_SIZE, DEFAULT_SARIF_TOOL_NAME, DataMatrixOptions, DataMatrixResult, DeclaredInvoiceTotals, DecodedRasterImage, DeduplicationReport, DeferredSignOptions, DeferredSignResult, Degrees, DeviceNColor, DiffEntry, DiffResult, DirectEmbedOptions, DirectEmbedResult, DisplayItem, DisplayList, DocTimeStampOptions, DocumentDiff, DocumentMetadata, DocumentPart, DocumentStructure, DownscaleOptions, DrawCircleOptions, DrawEllipseOptions, DrawImageOptions, DrawLineOptions, DrawPageOptions, DrawQrCodeOptions, DrawRectangleOptions, DrawSquareOptions, DrawSvgPathOptions, DrawTableOptions, DrawTextOptions, DropdownAppearanceOptions, DssData, EInvoiceIssue, EKU_OIDS, BarcodeOptions as EanOptions, EmbedFontOptions, EmbedPageOptions, EmbeddedFile, EmbeddedFont, EmbeddedPdfPage, EncryptAlgorithm, EncryptDictValues, EncryptOptions, EncryptedPayloadOptions, EncryptedPdfError, EncryptionReport, EnforcePdfAOptions, EnforcePdfAResult, EnforcementAction, ErrorCorrectionLevel, ExceededMaxLengthError, ExponentialFunction, ExternalSigner, ExtractedFont, ExtractedImage, ExtractedTable, FacturXAssembleOptions, FacturXProfile, FallbackFont, FallbackRun, FetchLike, FetchLikeResponse, FieldAlreadyExistsError, FieldExistsAsNonTerminalError, FieldFlags, FieldLockInfo, FieldLockOptions, FieldType, FileAttachmentIcon, FillItem, FlaggedVertex, FlattenFormResult, FlattenOptions, FontDescriptorData, FontEmbeddingResult, FontFileFormat, FontMetrics, FontNotEmbeddedError, FontRef, ForeignPageError, Fragment, FreeFormGouraudOptions, FreeTextAlignment, FunctionShadingOptions, GradientFill, GrayscaleColor, HeaderFooterContent, HeaderFooterOptions, HeaderFooterPosition, IccProfile, IccTransformInfo, IfdEntry, ImageAlignment, ImageAnalysis, ImageDecoder, ImageDpi, ImageFormat, ImageInfo, ImageItem, ImageOptimizeEntry, ImageOptimizeOptions, ImageRef, IncrementalChange, IncrementalObject, IncrementalSaveOptions, IncrementalSaveResult, InitWasmOptions, InterpretOptions, InvalidColorError, InvalidFieldNamePartError, InvalidPageSizeError, Invoice, InvoiceLine, InvoiceParty, ItfOptions, JpegDecodeResult, JpegMarkerInfo, JpegMetadata, JpegWasmModule, JsonReport, JsonSchemaLike, LIST_NUMBERING_KEY, LabParams, LatticeFormGouraudOptions, LayoutCombedOptions, LayoutMultilineOptions, LayoutMultilineResult, LayoutSinglelineOptions, LayoutSinglelineResult, LineCapStyle, LineEndingStyle, LineJoinStyle, LinearGradientOptions, LinearizationInfo, LinearizationOptions, LinkHighlightMode, ListNumbering, ListboxAppearanceOptions, LoadPdfOptions, LtvOptions, MATHML_NAMESPACE, MarkdownToPdfOptions, MarkedContentScope, Matrix, MdpPermission, MemoryBudget, MemoryBudgetExceededError, MemoryBudgetOptions, MeshShadingCommon, MeshVertex, MetadataPluginOptions, MissingOnValueCheckError, ModificationReport, ModificationViolation, ModificationViolationType, MultiPageTableResult, NamedInstance, NamespaceDef, NestedTableContent, NextGenFormat, NextGenImageInfo, NoSuchFieldError, NodeServerResponseLike, NormalizedStop, OcrEngine, OcrWord, Operand, OptimizationReport, OptimizeResult, OrderXType, OutlineDestination, OutlineItemOptions, OutputIntentOptions, OverflowMode, OverflowResult, OverlayAlignment, PDF2_NAMESPACE, PDFOperator, PageContent, PageEntry, PageLabelRange, PageLabelStyle, PageOutputIntentOptions, PageRange, PageSize, PageSizes, ParseSpeeds, ParsedPage, ParsedXmpMetadata, PatternFill, Pdf417Matrix, Pdf417Options, PdfA4ExtensionProperty, PdfA4ExtensionSchema, PdfA4Level, PdfA4Options, PdfAIssue, PdfALevel, PdfAProfile, PdfAValidationResult, PdfAXmpOptions, PdfAnnotation, PdfArray, PdfBool, PdfButtonField, PdfCaretAnnotation, PdfCheckboxField, PdfCircleAnnotation, PdfComponent, PdfDict, PdfDocument, PdfDocumentBuilder, PdfDropdownField, PdfElement, PdfEncryptionHandler, PdfField, PdfFileAttachmentAnnotation, PdfForm, PdfFreeTextAnnotation, PdfFunctionDef, PdfHighlightAnnotation, PdfInkAnnotation, PdfLayer, PdfLayerManager, PdfLineAnnotation, PdfLinkAnnotation, PdfListboxField, PdfName, PdfNode, PdfNull, PdfNumber, PdfObject, PdfObjectRegistry, PdfOutlineItem, PdfOutlineTree, PdfPage, PdfParseError, PdfPermissionFlags, PdfPlugin, PdfPluginManager, PdfPolyLineAnnotation, PdfPolygonAnnotation, PdfPopupAnnotation, PdfRadioGroup, PdfRect, PdfRedactAnnotation, PdfRef, PdfResponseOptions, PdfSaveOptions, PdfSignatureField, PdfSignatureInfo, PdfSquareAnnotation, PdfSquigglyAnnotation, PdfStampAnnotation, PdfStream, PdfStreamWriter, PdfStrikeOutAnnotation, PdfString, PdfStructureElement, PdfStructureTree, PdfTextAnnotation, PdfTextField, PdfUa2Issue, PdfUa2Result, PdfUaEnforcementResult, PdfUaError, PdfUaLevel, PdfUaValidationResult, PdfUaWarning, PdfUnderlineAnnotation, PdfViewerPreferences, PdfVtConformance, PdfWorker, PdfWorkerOptions, PdfWriter, PdfX6Options, PdfX6Variant, PermissionFlags, PluginDocument, PluginError, PluginPage, PostScriptFunction, PreflightIssue, PrepareAppearanceOptions, PresetName, PresetOptions, ProfileXmpOptions, ProgressInfo, QrCodeMatrix, QrCodeOptions, RadialGradientFill, RadialGradientOptions, Radians, RadioAppearanceOptions, RangeFetchOptions, RangeFetcher, RasterBuffer, RasterImage, RawImageData, RecompressOptions, ReconstructOptions, RedactRect, RedactResult, RedactionLeak, RedactionMark, RedactionOperatorOptions, RedactionOptions, RedactionRegion, RedactionResult, RedactionVerificationReport, RefResolver, RegistryEntry, RemovePageFromEmptyDocumentError, RenderCache, RenderOptions, RequirementType, RgbColor, Rgba, RichTextFieldReadError, RuntimeCapabilities, RuntimeKind, SARIF_SCHEMA_URI, SIMD_NOTE, SRGB_ICC_PROFILE, STANDARD_SPOT_FUNCTIONS, SampledFunction, SanitizeClass, SanitizeOptions, SanitizeReport, SarifLog, SarifResult, SarifRun, SchemaFieldKind, SchemaFormField, SchemaFormOptions, SchemaFormResult, ScriptRun, SetTitleOptions, SharedCounter, SharedFlag, SharedFlagWaitResult, SharedRingBuffer, SignOptions, SignatureAlgorithm, SignatureAppearanceOptions, SignatureByteRange, SignatureChainEntry, SignatureChainResult, SignatureOptions, SignatureVerificationResult, SignerInfo, SoftMaskBuilder, SoftMaskGroupOptions, SoftMaskRef, SpotColor, StandardFontName, StandardFonts, StandardStampName, StitchingFunction, StreamingParseError, StreamingParseResult, StreamingParserEvent, StreamingParserOptions, StreamingPdfParser, StripOptions, StripResult, StrippedFeature, StrokeItem, StructureElementOptions, StructureType, StyledBarcodeOptions, SubPath, SubsetCmap, SubsetResult, SvgDrawCommand, SvgElement, SvgGradient, SvgGradientStop, SvgRenderOptions, TableCell, TableColumn, TableExtractOptions, TablePreset, TableRenderResult, TableRow, TaggedListItem, TaskRunner, TensorPatch, TensorPatchOptions, TextAlignment$1 as TextAlignment, TextAnnotationIcon, TextAppearanceOptions, TextItem as TextDisplayItem, TextExtractionOptions, TextItem$1 as TextItem, Line as TextLine, Paragraph as TextParagraph, TextRenderingMode, TextRun, ThreatFinding, ThreatReport, ThreatSeverity, ThumbnailOptions, TiffCmykEmbedResult, TiffDecodeOptions, TiffIfdEntry, TiffImage, TileGrid, TileOptions, TilingPatternOptions, TimestampPluginOptions, TimestampResult, TrailerInfo, TransparencyFinding, TransparencyGroupOptions, TransparencyInfo, TrustStore, Type0FontData, Type1Halftone, UnexpectedFieldTypeError, BarcodeOptions as UpcOptions, VNode, ValidatableInvoice, ValidationFinding, ValidationLevel, VariableFontInfo, VariationAxis, RenderOptions$1 as VdomRenderOptions, ViewerPreferences, VisibleSignatureOptions, RecordMetadata as VtRecordMetadata, WasmLoaderConfig, WasmModuleName, WatermarkOptions, WebPImage, WidgetAnnotationHost, WidthEntry, WoffInfo, WorkerPool, WorkerPoolOptions, WrapperPayloadOptions, XRechnungOptions, XmpIssue, XmpValidationResult, accessibilityPlugin, addBookmark, addCounterSignature, addFieldLock, addVisibilityAction, addWatermark, addWatermarkToPage, aesDecryptCBC, aesEncryptCBC, analyzeImages, analyzeJpegMarkers, annotationFromDict, appendIncrementalUpdate, applyFillColor, applyHeaderFooter, applyHeaderFooterToPage, applyOcr, applyOverflow, applyPreset, applyRedaction, applyRedactions, applySpreadMethod, applyStrokeColor, applyTablePreset, asNumber, asPDFName, asPDFNumber, asPdfName, asPdfNumber, assembleFacturX, assembleTiles, attachAssociatedFiles, attachFile, attachOutputIntents, autoTagPage, base64Decode, base64Encode, batchFlatten, batchMerge, beginArtifact, beginArtifactWithType, beginLayerContent, beginMarkedContent, beginMarkedContentSequence, beginMarkedContentWithProperties, beginText, borderedPreset, buildAfArray, buildAnnotationDict, buildBlackPointCompensationExtGState, buildBoxDict, buildCalGray, buildCalRGB, buildCatalog, buildCertPath, buildCertificateChain, buildCollection, buildColorKeyMask, buildCoonsPatchShading, buildDPartRoot, buildDeviceNColorSpace, buildDocMdpReference, buildDocTimeStampDict, buildDocumentStructure, buildDssDictionary, buildEmbeddedFilesNameTree, buildEncryptedPayload, buildFacturXXmp, buildFieldLockDict, buildFormFromJsonSchema, buildFreeFormGouraudShading, buildFunctionShading, buildGradientObjects, buildGtsPdfxVersion, buildImageSoftMask, buildInfoDict, buildLab, buildLatticeFormGouraudShading, buildNamespace, buildNamespacesArray, buildOutputIntent, buildPageOutputIntent, buildPageTree, buildPatternObjects, buildPdfA4Xmp, buildPdfRIdentificationXmp, buildPdfUa2Xmp, buildPdfVtDParts, buildPdfX6OutputIntent, buildPdfXOutputIntent, buildPieceInfo, buildPkcs7Signature, buildRequirement, buildRequirements, buildSampledTransferFunction, buildSeparationColorSpace, buildSigningCertificateV2Attribute, buildSoftMaskGroupExtGState, buildSoftMaskNone, buildStencilMask, buildTensorPatchShading, buildThresholdHalftone, buildTimestampRequest, buildType1Halftone, buildType5Halftone, buildUnencryptedWrapper, buildViewerPreferencesDict, buildVtDpm, buildWtpdfIdentificationXmp, buildXmpMetadata, calculateBarcodeDimensions, calculateEanCheckDigit, calculateUpcCheckDigit, canDirectEmbed, checkAccessibility, checkCertificateStatus, circlePath, clearWasmCache, clipEvenOdd, clip as clipOp, closeAndStroke, closeFillAndStroke, closeFillEvenOddAndStroke, closePath as closePathOp, cmyk, cmykToRgb, code128ToOperators, code39ToOperators, colorToComponents, colorToHex, compareImages, comparePages, componentsToColor, computeCode39CheckDigit, computeFileEncryptionKey, computeFontSize, computeImageDpi, computeObjectHash, computeSignatureHash, computeTargetDimensions, computeTileGrid, concatMatrix, concatMatrix as concatTransformationMatrix, configureWasmLoader, convertPdfAConformanceXmp, convertTiffCmykToRgb, convertToGrayscale, copyPages, countOccurrences, createAnnotation, createAssociatedFile, createMarkedContentScope, createMemoryBudget, createPdf, createRangeFetcher, createSandbox, h$1 as createVNode, createWorkerPool, createXmpStream, cropPage, curveToFinal, curveToInitial, curveTo as curveToOp, dataMatrixToOperators, decodeImageStream, decodeJpeg2000, decodeJpegWasm, decodePermissions, decodeRegisteredImage, decodeStream, decodeTiff, decodeTiffAll, decodeTiffPage, decodeTile, decodeTileRegion, decodeWebP, decodeWoff, deduplicateImages, degrees, degreesToRadians, delinearizePdf, detectFacturXProfile, detectImageFormat, detectModifications, detectNextGenFormat, detectRuntime, detectRuntimeCapabilities, detectTransparency, deviceNColor, deviceNResourceName, deviceRgbToXyz, didYouMean, diffSignedContent, downloadCrl, downscale16To8, 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, enforcePdfX, estimateJpegQuality, estimateTextWidth, evaluateFunction, extractCrlUrls, extractEmbeddedRevocationData, extractFonts, extractIccProfile, extractImages$1 as extractImages, extractJpegMetadata, extractMetrics, extractOcspUrl, extractImages as extractPageImages, extractSigningCertificateV2, extractTables, extractText, extractTextWithPositions, extractXmpMetadata, feBlend, feColorMatrix, feColorMatrixSaturate, feComposite, feFlood, feGaussianBlur, feOffset, fillAndStroke as fillAndStrokeOp, fillEvenOdd, fillEvenOddAndStroke, fill as fillOp, findChangedObjects, findExistingSignatures, findHyphenationPoints, findSignatures, flattenField, flattenFields, flattenForm, flattenTransparency, formatDate$1 as formatAcrobatDate, formatDate, formatHexContext, formatNumber, formatPdfDate, generateButtonAppearance, generateCheckboxAppearance, generateCiiXml, generateCircleAppearance, generateDropdownAppearance, generateFreeTextAppearance, generateHighlightAppearance, generateInkAppearance, generateLineAppearance, generateListboxAppearance, generateOrderX, generatePdfAXmp, generatePdfAXmpBytes, generateRadioAppearance, generateSignatureAppearance, generateSquareAppearance, generateSquigglyAppearance, generateSrgbIccProfile, generateStrikeOutAppearance, generateSymbolToUnicodeCmap, generateTextAppearance, generateThumbnail, generateUnderlineAppearance, generateWinAnsiToUnicodeCmap, generateXRechnungCii, generateZapfDingbatsToUnicodeCmap, getAttachments, getBookmarks, getCertificationLevel, getColorGlyphLayers, getComponentDepths, getCounterSignatures, getFieldLocks, getFieldValue, getImageDecoder, getImageFormatName, getInlineWasmBytes, getInlineWasmSize, getLinearizationInfo, getPageLabels, getPageSize, getProfile, getRedactionMarks, getSignatures, getSupportedFormats, getSupportedLevels, getTiffPageCount, getToUnicodeCmap, grayscale, gtsPdfVtVersion, hasImageDecoder, hasInlineWasmData, hasLtvData, hexToColor, hslToRgb, hsvToRgb, identityTransferFunction, initJpegWasm, initWasm, injectJpegMetadata, insertPage, inspectEncryption, instantiateWasmModuleStreaming, interpolateLinearRgb, interpretContentStream, interpretPage, isAccessible, isCertificateRevoked, isCmykTiff, isGrayscaleImage, isJpegWasmReady, isLinearized, isOpenTypeCFF, isSharedMemoryAvailable, isTiff, isTrueType, isValidLevel, isValidModuleName, isWasmDisabled, isWasmModuleCached, isWasmSimdSupported, isWebP, isWebPLossless, isWoff, isWoff2, itfToOperators, jsx, h as jsxh, jsxs, labToRgb, layoutColumns, layoutCombedText, layoutMultilineText, layoutParagraph, layoutSinglelineText, layoutTextFlow, levenshtein, lineTo as lineToOp, linearGradient, linearizePdf, loadPdf, loadWasmModule, loadWasmModuleStreaming, markForRedaction, markdownToPdf, md5, mergePdfs, metadataPlugin, minimalPreset, movePage, moveText as moveTextOp, moveTextSetLeading, moveTo as moveToOp, nameHalftone, nextLine as nextLineOp, normalizeAxisCoordinate, normalizeComponentDepth, offsetSignedToUnsigned, optimizeAllImages, optimizeImage, optimizeIncrementalSave, parseAcrobatDate, parseCiiXml, parseColorFont, parseContentStream, parseExistingTrailer, parseIccColorSpace, parseIccDescription, parseIccTransform, parseSvg, parseSvgColor, parseSvgPath, parseSvgTransform, parseTiffIfd, parseTileInfo, parseTimestampResponse, parseVariableFont, parseViewerPreferences, parseXmpMetadata$1 as parseXmpMetadata, parseXmpMetadata as parseXmpPdfAMetadata, pdf417ToOperators, pdfA4Rules, pdfHeaders, pdfResponse, pdfStreamResponse, restoreState as popGraphicsState, preflightPdfA, preloadInlineWasm, prepareForSigning, probeNextGenImage, processBatch, professionalPreset, provideWasmBytes, saveState as pushGraphicsState, qrCodeToOperators, radialGradient, radians, radiansToDegrees, rasterize, rc4, readBarcode, readCode128, readCode39, readEan13, readEan8, readWoffHeader, recompressImage, recompressWebP, reconstructLines, reconstructParagraphs, rectangle as rectangleOp, redactRegions, registerEmbeddedFile, registerImageDecoder, removeAllBookmarks, removeBookmark, removePage, removePageLabels, removePages, renderCodeFrame, renderDisplayListToCanvas, renderToPdf as renderJsxToPdf, renderMultiPageTable, renderPageTile, renderPageToCanvas, renderPageToImage, renderStyledBarcode, renderTable, renderToPdf$1 as renderToPdf, reorderVisual, replaceTemplateVariables, requestTimestamp, resetWasmLoader, resizePage, resolveBidi, resolveFallback, resolveFieldReference, resolveInstanceCoordinates, restoreState, reversePages, rgb, rgbToCmyk, rgbToHsl, rgbToHsv, rgbToLab, rgbToXyz, rotateAllPages, rotate as rotateOp, rotatePage, rotationMatrix, sampleShadingColor, sanitizePdf, saveDocumentIncremental, saveIncremental, saveIncrementalWithSignaturePreservation, saveState, scale as scaleOp, scanPdfThreats, searchTextItems, sendPdfToNodeResponse, serializePdf, setCertificationLevel, setCharacterSpacing as setCharacterSpacingOp, setCharacterSpacing as setCharacterSqueeze, setColorSpace, setDashPattern as setDashPatternOp, setFieldValue, setFieldVisibility, 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, signDeferred, signPdf, skew as skewOp, splitByScript, splitPdf, spotColor, spotResourceName, stripProhibitedFeatures, stripedPreset, stroke as strokeOp, summarizeBitDepth, summarizeIssues, svgToPdfOperators, tableToCsv, tableToJson, tagFigure, tagHeading, tagLink, tagList, tagListItem, tagParagraph, tagTable, tagTableDataCell, tagTableHeaderCell, tagTableRow, tilingPattern, timestampPlugin, toAlpha, toJsonReport, toRoman, toSarif, translate as translateOp, truncateText, unregisterImageDecoder, upcAToOperators, upscale8To16, validateBoxGeometry, validateByteRangeIntegrity, validateCertificateChain, validateCertificatePolicy, validateEn16931, validateExtendedKeyUsage, validateFieldValue, validateKeyUsage, validatePdfA, validatePdfUa, validatePdfUa2, validatePdfX, validateSignatureChain, validateXmpMetadata, valuesToModules, verifyOfflineRevocation, verifyOwnerPassword, verifyRedactions, verifySignature, verifySignatureDetailed, verifySignatures, verifyUserPassword, webpToJpeg, webpToPng, wrapInMarkedContent, wrapText, xyzToLab, xyzToRgb }; } /** * 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 { attachAssociatedFiles as $, buildCalRGB as $a, detectRuntime as $c, SignatureByteRange as $d, generateStrikeOutAppearance as $f, buildPdfA4Xmp as $i, deduplicateImages as $l, curveToInitial as $m, xyzToLab as $n, PageLabelRange as $o, PdfUaValidationResult as $p, layoutColumns as $r, TablePreset as $s, SchemaFormOptions as $t, getToUnicodeCmap as $u, tagHeading as A, PdfFunctionDef as Aa, encodeEan8 as Ac, getCounterSignatures as Ad, encodeLength as Af, gtsPdfVtVersion as Ai, getImageFormatName as Al, setFont as Am, feGaussianBlur as An, MetadataPluginOptions as Ao, formatNumber as Ap, BidiRun as Ar, RemovePageFromEmptyDocumentError as As, rasterize as At, EnforcementAction as Au, buildColorKeyMask as B, buildCollection as Ba, encodeCode128 as Bc, ModificationViolation as Bd, computeSignatureHash as Bf, FallbackFont as Bi, JpegMarkerInfo as Bl, showTextNextLine as Bm, NextGenImageInfo as Bn, WasmModuleName as Bo, sha384 as Bp, SanitizeClass as Br, replaceTemplateVariables as Bs, StrokeItem as Bt, ParsedXmpMetadata as Bu, PdfUa2Result as C, buildSampledTransferFunction as Ca, calculateUpcCheckDigit as Cc, DssData as Cd, parseTimestampResponse as Cf, WorkerPool as Ci, embedTiffDirect as Cl, drawXObject as Cm, CompositeOp as Cn, ExtractedTable as Co, PdfLinkAnnotation as Cp, VariableFontInfo as Cr, ForeignPageError as Cs, generateThumbnail as Ct, RedactionResult as Cu, ListNumbering as D, identityTransferFunction as Da, ean13ToOperators as Dc, hasLtvData as Dd, buildPkcs7Signature as Df, RecordMetadata as Di, webpToPng as Dl, moveTextSetLeading as Dm, feColorMatrixSaturate as Dn, tableToJson as Do, formatDate$1 as Dp, resolveInstanceCoordinates as Dr, MissingOnValueCheckError as Ds, renderPageToCanvas as Dt, validatePdfX as Du, LIST_NUMBERING_KEY as E, buildType5Halftone as Ea, calculateEanCheckDigit as Ec, embedLtvData as Ed, SignerInfo as Ef, PdfVtConformance as Ei, webpToJpeg as El, moveText as Em, feColorMatrix as En, tableToCsv as Eo, AFDate_FormatEx as Ep, parseVariableFont as Er, InvalidPageSizeError as Es, renderDisplayListToCanvas as Et, enforcePdfX as Eu, tagTable as F, MarkdownToPdfOptions as Fa, code39ToOperators as Fc, FieldLockOptions as Fd, encodeSet as Ff, FetchLike as Fi, embedTiffCmyk as Fl, setTextRise as Fm, getImageDecoder as Fn, StreamingParseResult as Fo, addVisibilityAction as Fp, inspectEncryption as Fr, HeaderFooterOptions as Fs, DisplayItem as Ft, StripOptions as Fu, buildSoftMaskNone as G, reconstructParagraphs as Ga, base64Decode as Gc, getCertificationLevel as Gd, searchTextItems as Gf, OrderXType as Gi, IccProfile as Gl, clip as Gm, rgbToHsl as Gn, preloadInlineWasm as Go, md5 as Gp, ThreatReport as Gr, applyOverflow as Gs, PdfResponseOptions as Gt, validateXmpMetadata as Gu, buildStencilMask as H, Paragraph as Ha, valuesToModules as Hc, detectModifications as Hd, findSignatures as Hf, ScriptRun as Hi, ImageDpi as Hl, buildDeviceNColorSpace as Hm, probeNextGenImage as Hn, getInlineWasmSize as Ho, aesDecryptCBC as Hp, SanitizeReport as Hr, toRoman as Hs, TextItem as Ht, XmpValidationResult as Hu, tagTableDataCell as I, markdownToPdf as Ia, computeCode39CheckDigit as Ic, addFieldLock as Id, encodeUTCTime as If, FetchLikeResponse as Ii, isCmykTiff as Il, setWordSpacing as Im, hasImageDecoder as In, StreamingParserEvent as Io, setFieldVisibility as Ip, RedactionLeak as Ir, HeaderFooterPosition as Is, DisplayList as It, StripResult as Iu, buildEncryptedPayload as J, buildDocTimeStampDict as Ja, PdfWorkerOptions as Jc, SignatureChainResult as Jd, generateHighlightAppearance as Jf, generateXRechnungCii as Ji, parseIccColorSpace as Jl, closeFillAndStroke as Jm, rgbToXyz as Jn, BatchProgressCallback as Jo, verifyOwnerPassword as Jp, CertPathResult as Jr, shrinkFontSize as Js, pdfStreamResponse as Jt, getSupportedLevels as Ju, EncryptedPayloadOptions as K, DEFAULT_DOC_TIMESTAMP_CONTENTS_SIZE as Ka, base64Encode as Kc, setCertificationLevel as Kd, generateCircleAppearance as Kf, XRechnungOptions as Ki, embedIccProfile as Kl, clipEvenOdd as Km, rgbToHsv as Kn, BatchErrorStrategy as Ko, EncryptDictValues as Kp, ThreatSeverity as Kr, ellipsisText as Ks, pdfHeaders as Kt, PdfAProfile as Ku, tagTableHeaderCell as L, CollectionOptions as La, encodeCode39 as Lc, buildFieldLockDict as Ld, encodeUtf8String as Lf, RangeFetchOptions as Li, JpegMetadata as Ll, showText as Lm, registerImageDecoder as Ln, StreamingParserOptions as Lo, AFSpecial_Format as Lp, RedactionRegion as Lr, applyHeaderFooter as Ls, FillItem as Lt, StrippedFeature as Lu, tagList as M, SampledFunction as Ma, encodeItf as Mc, DocumentDiff as Md, encodeOctetString as Mf, VNode as Mi, TiffCmykEmbedResult as Ml, setLeading as Mm, DecodedRasterImage as Mn, TimestampPluginOptions as Mo, getFieldValue as Mp, resolveBidi as Mr, StreamingParseError as Ms, InterpretOptions as Mt, PdfAXmpOptions as Mu, tagListItem as N, StitchingFunction as Na, itfToOperators as Nc, diffSignedContent as Nd, encodePrintableString as Nf, h$1 as Ni, TiffIfdEntry as Nl, setTextMatrix as Nm, ImageDecoder as Nn, timestampPlugin as No, resolveFieldReference as Np, EncryptionReport as Nr, UnexpectedFieldTypeError as Ns, interpretContentStream as Nt, generatePdfAXmp as Nu, TaggedListItem as O, nameHalftone as Oa, ean8ToOperators as Oc, CounterSignatureInfo as Od, encodeContextTag as Of, buildPdfVtDParts as Oi, ImageFormat as Ol, nextLine as Om, feComposite as On, AccessibilityPluginOptions as Oo, parseAcrobatDate as Op, BidiDirection as Or, NoSuchFieldError as Os, RasterImage as Ot, EnforcePdfAOptions as Ou, tagParagraph as P, evaluateFunction as Pa, Code39Options as Pc, FieldLockInfo as Pd, encodeSequence as Pf, renderToPdf$1 as Pi, convertTiffCmykToRgb as Pl, setTextRenderingMode as Pm, decodeRegisteredImage as Pn, ParsedPage as Po, setFieldValue as Pp, PermissionFlags as Pr, HeaderFooterContent as Ps, interpretPage as Pt, generatePdfAXmpBytes as Pu, buildPageOutputIntent as Q, buildCalGray as Qa, configureWasmLoader as Qc, IncrementalSaveOptions as Qd, generateSquigglyAppearance as Qf, PdfA4Options as Qi, DeduplicationReport as Ql, curveToFinal as Qm, parseIccTransform as Qn, processBatch as Qo, PdfUaLevel as Qp, findHyphenationPoints as Qr, PresetOptions as Qs, SchemaFormField as Qt, generateZapfDingbatsToUnicodeCmap as Qu, tagTableRow as R, CollectionSchemaField as Ra, Code128Options as Rc, getFieldLocks as Rd, ByteRangeResult as Rf, RangeFetcher as Ri, extractJpegMetadata as Rl, showTextArray as Rm, unregisterImageDecoder as Rn, StreamingPdfParser as Ro, validateFieldValue as Rp, RedactionVerificationReport as Rr, applyHeaderFooterToPage as Rs, ImageItem as Rt, countOccurrences as Ru, PdfUa2Issue as S, Type1Halftone as Sa, encodeDataMatrix as Sc, optimizeIncrementalSave as Sd, buildTimestampRequest as Sf, __exportAll as Sh, TaskRunner as Si, canDirectEmbed as Sl, drawImageXObject as Sm, isSharedMemoryAvailable as Sn, buildDPartRoot as So, LinkHighlightMode as Sp, NamedInstance as Sr, FontNotEmbeddedError as Ss, ThumbnailOptions as St, RedactionOperatorOptions as Su, validatePdfUa2 as T, buildType1Halftone as Ta, upcAToOperators as Tc, buildDssDictionary as Td, SignatureOptions as Tf, createWorkerPool as Ti, recompressWebP as Tl, endText as Tm, feBlend as Tn, extractTables as To, TextAnnotationIcon as Tp, normalizeAxisCoordinate as Tr, InvalidFieldNamePartError as Ts, CanvasRenderOptions as Tt, buildPdfXOutputIntent as Tu, SoftMaskGroupOptions as U, ReconstructOptions as Ua, BarcodeMatrix as Uc, MdpPermission as Ud, prepareForSigning as Uf, resolveFallback as Ui, computeImageDpi as Ul, buildSeparationColorSpace as Um, hslToRgb as Un, hasInlineWasmData as Uo, aesEncryptCBC as Up, sanitizePdf as Ur, OverflowMode as Us, Matrix as Ut, extractXmpMetadata as Uu, buildImageSoftMask as V, Line as Va, encodeCode128Values as Vc, ModificationViolationType as Vd, embedSignature as Vf, FallbackRun as Vi, analyzeJpegMarkers as Vl, showTextWithSpacing as Vm, detectNextGenFormat as Vn, getInlineWasmBytes as Vo, sha512 as Vp, SanitizeOptions as Vr, toAlpha as Vs, SubPath as Vt, XmpIssue as Vu, buildSoftMaskGroupExtGState as W, reconstructLines as Wa, BarcodeOptions as Wc, buildDocMdpReference as Wd, decodeJpeg2000 as Wf, splitByScript as Wi, computeTargetDimensions as Wl, circlePath as Wm, hsvToRgb as Wn, isValidModuleName as Wo, rc4 as Wp, ThreatFinding as Wr, OverflowResult as Ws, NodeServerResponseLike as Wt, parseXmpMetadata as Wu, PageOutputIntentOptions as X, CalRGBParams as Xa, WasmLoaderConfig as Xc, AppendOptions as Xd, generateLineAppearance as Xf, PdfA4ExtensionSchema as Xi, convertToGrayscale as Xl, closePath as Xm, IccTransformInfo as Xn, batchFlatten as Xo, PdfUaEnforcementResult as Xp, buildSigningCertificateV2Attribute as Xr, wrapText as Xs, JsonSchemaLike as Xt, generateSymbolToUnicodeCmap as Xu, buildUnencryptedWrapper as Y, CalGrayParams as Ya, RuntimeKind as Yc, validateSignatureChain as Yd, generateInkAppearance as Yf, PdfA4ExtensionProperty as Yi, parseIccDescription as Yl, closeFillEvenOddAndStroke as Ym, xyzToRgb as Yn, BatchResult as Yo, verifyUserPassword as Yp, buildCertPath as Yr, truncateText as Ys, sendPdfToNodeResponse as Yt, isValidLevel as Yu, attachOutputIntents as Z, LabParams as Za, clearWasmCache as Zc, IncrementalObject as Zd, generateSquareAppearance as Zf, PdfA4Level as Zi, isGrayscaleImage as Zl, curveTo as Zm, deviceRgbToXyz as Zn, batchMerge as Zo, PdfUaError as Zp, extractSigningCertificateV2 as Zr, PresetName as Zs, SchemaFieldKind as Zt, generateWinAnsiToUnicodeCmap as Zu, convertPdfAConformanceXmp as _, buildBoxDict as _a, encodePdf417 as _c, isLinearized as _d, extractCrlUrls as _f, isTrueType as _h, DeferredSignOptions as _i, decodeWebP as _l, createMarkedContentScope as _m, createMemoryBudget as _n, buildPieceInfo as _o, PdfSquigglyAnnotation as _p, ColorGlyphLayer as _r, CombedTextLayoutError as _s, ExtractedFont as _t, decodeJpegWasm as _u, parseCiiXml as a, didYouMean as aa, stripedPreset as ac, TransparencyInfo as ad, validateByteRangeIntegrity as af, fillEvenOddAndStroke as ah, offsetSignedToUnsigned as ai, provideWasmBytes as al, summarizeIssues as am, PdfNode as an, SarifLog as ao, PdfPopupAnnotation as ap, FlaggedVertex as ar, BookmarkNode as as, renderPageTile as at, DownscaleOptions as au, AutoTagResult as b, validateBoxGeometry as ba, DataMatrixResult as bc, computeObjectHash as bd, extractOcspUrl as bf, saveDocumentIncremental as bh, SignatureAlgorithm as bi, DirectEmbedOptions as bl, wrapInMarkedContent as bm, SharedFlagWaitResult as bn, buildRequirements as bo, FreeTextAlignment as bp, parseColorFont as br, FieldAlreadyExistsError as bs, ExtractedImage as bt, isJpegWasmReady as bu, ValidatableInvoice as c, FacturXProfile as ca, readCode128 as cc, PdfAIssue as cd, validateCertificatePolicy as cf, rectangle as ch, assembleTiles as ci, TiffDecodeOptions as cl, parseXmpMetadata$1 as cm, jsxs as cn, ValidationFinding as co, PdfStampAnnotation as cp, MeshShadingCommon as cr, getBookmarks as cs, redactRegions as ct, RawImageData as cu, assembleFacturX as d, InvoiceParty as da, readEan8 as dc, enforcePdfA as dd, TrustStore as df, setLineCap as dh, parseTileInfo as di, decodeTiffAll as dl, MarkedContentScope as dm, SIMD_NOTE as dn, toSarif as do, PdfCircleAnnotation as dp, TensorPatchOptions as dr, FlattenFormResult as ds, OcrWord as dt, estimateJpegQuality as du, pdfA4Rules as ea, applyPreset as ec, OutputIntentOptions as ed, TrailerInfo as ef, ellipsePath as eh, layoutParagraph as ei, instantiateWasmModuleStreaming as el, PdfUaWarning as em, SchemaFormResult as en, buildLab as eo, generateUnderlineAppearance as ep, BitsPerComponent as er, PageLabelStyle as es, registerEmbeddedFile as et, BatchOptimizeOptions as eu, buildFacturXXmp as f, generateCiiXml as fa, StyledBarcodeOptions as fc, validatePdfA as fd, extractEmbeddedRevocationData as ff, setLineJoin as fh, WoffInfo as fi, decodeTiffPage as fl, beginArtifact as fm, detectRuntimeCapabilities as fn, MATHML_NAMESPACE as fo, PdfLineAnnotation as fp, buildCoonsPatchShading as fr, FlattenOptions as fs, applyOcr as ft, optimizeImage as fu, PreflightIssue as g, PdfX6Variant as ga, Pdf417Options as gc, getLinearizationInfo as gd, downloadCrl as gf, isOpenTypeCFF as gh, readWoffHeader as gi, WebPImage as gl, beginMarkedContentWithProperties as gm, MemoryBudgetOptions as gn, buildNamespacesArray as go, PdfHighlightAnnotation as gp, ColorFontInfo as gr, BatchProcessingError as gs, comparePages as gt, JpegWasmModule as gu, buildWtpdfIdentificationXmp as h, PdfX6Options as ha, Pdf417Matrix as hc, delinearizePdf as hd, validateCertificateChain as hf, stroke as hh, isWoff2 as hi, parseTiffIfd as hl, beginMarkedContentSequence as hm, MemoryBudgetExceededError as hn, buildNamespace as ho, PdfSquareAnnotation as hp, buildTensorPatchShading as hr, flattenForm as hs, compareImages as ht, JpegDecodeResult as hu, detectFacturXProfile as i, CodeFrameOptions as ia, professionalPreset as ic, TransparencyFinding as id, saveIncrementalWithSignaturePreservation as if, fillEvenOdd as ih, normalizeComponentDepth as ii, loadWasmModuleStreaming as il, isAccessible as im, PdfElement as in, SARIF_SCHEMA_URI as io, PdfCaretAnnotation as ip, CoonsPatchOptions as ir, AddBookmarkOptions as is, computeTileGrid as it, optimizeAllImages as iu, tagLink as j, PostScriptFunction as ja, ItfOptions as jc, DiffEntry as jd, encodeOID as jf, RenderOptions$1 as ji, getSupportedFormats as jl, setFontSize as jm, feOffset as jn, metadataPlugin as jo, createSandbox as jp, reorderVisual as jr, RichTextFieldReadError as js, renderPageToImage as jt, enforcePdfAFull as ju, tagFigure as k, ExponentialFunction as ka, encodeEan13 as kc, addCounterSignature as kd, encodeInteger as kf, buildVtDpm as ki, detectImageFormat as kl, setCharacterSpacing as km, feFlood as kn, accessibilityPlugin as ko, AFNumber_Format as kp, BidiResult as kr, PluginError as ks, RenderOptions as kt, EnforcePdfAResult as ku, validateEn16931 as l, Invoice as la, readCode39 as lc, PdfALevel as ld, validateExtendedKeyUsage as lf, setDashPattern as lh, decodeTile as li, TiffImage as ll, PdfStreamWriter as lm, renderToPdf as ln, ValidationLevel as lo, StandardStampName as lp, MeshVertex as lr, removeAllBookmarks as ls, ApplyOcrOptions as lt, RecompressOptions as lu, buildPdfRIdentificationXmp as m, PdfRect as ma, renderStyledBarcode as mc, LinearizationOptions as md, buildCertificateChain as mf, setMiterLimit as mh, isWoff as mi, isTiff as ml, beginMarkedContent as mm, MemoryBudget as mn, PDF2_NAMESPACE as mo, PdfPolygonAnnotation as mp, buildLatticeFormGouraudShading as mr, flattenFields as ms, DiffResult as mt, ChromaSubsampling as mu, index_d_exports as n, buildFunctionShading as na, borderedPreset as nc, SRGB_ICC_PROFILE as nd, findExistingSignatures as nf, fill as nh, downscale16To8 as ni, isWasmModuleCached as nl, validatePdfUa as nm, Fragment as nn, DEFAULT_SARIF_TOOL_NAME as no, PdfFileAttachmentAnnotation as np, BitsPerFlag as nr, removePageLabels as ns, TileGrid as nt, OptimizationReport as nu, DeclaredInvoiceTotals as o, levenshtein as oa, BarcodeReadResult as oc, detectTransparency as od, verifySignatureDetailed as of, lineTo as oh, summarizeBitDepth as oi, resetWasmLoader as ol, buildXmpMetadata as om, h as on, SarifResult as oo, PdfRedactAnnotation as op, FreeFormGouraudOptions as or, BookmarkRef as os, RedactRect as ot, ImageOptimizeOptions as ou, ProfileXmpOptions as p, BoxGeometry as pa, calculateBarcodeDimensions as pc, LinearizationInfo as pd, verifyOfflineRevocation as pf, setLineWidth as ph, decodeWoff as pi, getTiffPageCount as pl, beginArtifactWithType as pm, isWasmSimdSupported as pn, NamespaceDef as po, PdfPolyLineAnnotation as pp, buildFreeFormGouraudShading as pr, flattenField as ps, CompareOptions as pt, recompressImage as pu, WrapperPayloadOptions as q, DocTimeStampOptions as qa, PdfWorker as qc, SignatureChainEntry as qd, generateFreeTextAppearance as qf, generateOrderX as qi, extractIccProfile as ql, closeAndStroke as qm, rgbToLab as qn, BatchOptions as qo, computeFileEncryptionKey as qp, scanPdfThreats as qr, estimateTextWidth as qs, pdfResponse as qt, getProfile as qu, initWasm as r, sampleShadingColor as ra, minimalPreset as rc, generateSrgbIccProfile as rd, parseExistingTrailer as rf, fillAndStroke as rh, getComponentDepths as ri, loadWasmModule as rl, checkAccessibility as rm, PdfComponent as rn, JsonReport as ro, CaretSymbol as rp, CoonsPatch as rr, setPageLabels as rs, TileOptions as rt, ProgressInfo as ru, EInvoiceIssue as s, renderCodeFrame as sa, readBarcode as sc, flattenTransparency as sd, EKU_OIDS as sf, moveTo as sh, upscale8To16 as si, IfdEntry as sl, createXmpStream as sm, jsx as sn, SarifRun as so, PdfInkAnnotation as sp, LatticeFormGouraudOptions as sr, addBookmark as ss, RedactResult as st, OptimizeResult as su, InitWasmOptions as t, FunctionShadingOptions as ta, applyTablePreset as tc, buildOutputIntent as td, appendIncrementalUpdate as tf, endPath as th, layoutTextFlow as ti, isWasmDisabled as tl, enforcePdfUa as tm, buildFormFromJsonSchema as tn, labToRgb as to, FileAttachmentIcon as tp, BitsPerCoordinate as tr, getPageLabels as ts, RenderCache as tt, ImageOptimizeEntry as tu, FacturXAssembleOptions as u, InvoiceLine as ua, readEan13 as uc, PdfAValidationResult as ud, validateKeyUsage as uf, setFlatness as uh, decodeTileRegion as ui, decodeTiff as ul, PDFOperator as um, RuntimeCapabilities as un, toJsonReport as uo, LineEndingStyle as up, TensorPatch as ur, removeBookmark as us, OcrEngine as ut, downscaleImage as uu, preflightPdfA as v, buildGtsPdfxVersion as va, pdf417ToOperators as vc, linearizePdf as vd, isCertificateRevoked as vf, ChangeTracker as vh, DeferredSignResult as vi, isWebP as vl, endArtifact as vm, SharedCounter as vn, RequirementType as vo, PdfStrikeOutAnnotation as vp, CpalPalette as vr, EncryptedPdfError as vs, FontFileFormat as vt, encodeJpegWasm as vu, buildPdfUa2Xmp as w, buildThresholdHalftone as wa, encodeUpcA as wc, LtvOptions as wd, requestTimestamp as wf, WorkerPoolOptions as wi, encodePngFromPixels as wl, beginText as wm, RasterBuffer as wn, TableExtractOptions as wo, PdfTextAnnotation as wp, VariationAxis as wr, InvalidColorError as ws, Canvas2DLike as wt, applyRedaction as wu, autoTagPage as x, STANDARD_SPOT_FUNCTIONS as xa, dataMatrixToOperators as xc, findChangedObjects as xd, TimestampResult as xf, saveIncremental as xh, signDeferred as xi, DirectEmbedResult as xl, drawImageWithMatrix as xm, SharedRingBuffer as xn, DocumentPart as xo, PdfFreeTextAnnotation as xp, AvarSegmentMap as xr, FieldExistsAsNonTerminalError as xs, extractImages as xt, OverlayAlignment as xu, AutoTagOptions as y, buildPdfX6OutputIntent as ya, DataMatrixOptions as yc, IncrementalChange as yd, checkCertificateStatus as yf, IncrementalSaveResult as yh, ExternalSigner as yi, isWebPLossless as yl, endMarkedContent as ym, SharedFlag as yn, buildRequirement as yo, PdfUnderlineAnnotation as yp, getColorGlyphLayers as yr, ExceededMaxLengthError as ys, extractFonts as yt, initJpegWasm as yu, buildBlackPointCompensationExtGState as z, CollectionView as za, code128ToOperators as zc, ModificationReport as zd, PrepareAppearanceOptions as zf, createRangeFetcher as zi, injectJpegMetadata as zl, showTextHex as zm, NextGenFormat as zn, PdfDocumentBuilder as zo, sha256 as zp, verifyRedactions as zr, formatDate as zs, Rgba as zt, stripProhibitedFeatures as zu }; //# sourceMappingURL=index-KifTKVe6.d.mts.map