@qrcommunication/gigapdf-lib — SDK API reference - v0.110.3
    Preparing search index...

    Class GigaPdfDoc

    A live document handle. Call close when done.

    Index

    Constructors

    Methods

    close pageCount save saveCompressed saveOptimized toLinearized saveLinearized textRuns elements textElements documentLanguage imageElements vectorPaths structuredText pageBlocks search replaceText removeElement moveElement transformElement setPathStyle setTextRunStyle setElementOpacity reorderElement duplicateElement elementAt addRectangle drawLine addEllipse addGradient addFilledRectangle addFilledPolygon addTextColor setOverprint addOutputIntent addPolygon addPath addImage replaceImage addImageWatermark addSvg redact redactPii rotatePage deletePage movePage appendPages addTextLayer extractPages resizePage scalePageContent scalePageContentXY scalePageTo setUserUnit pageUserUnit addPage copyPage placePage placePageMatrix nUp pageInfo pageMargins setPageMargins setEditorMeta editorMeta setEditorMargins editorMargins getPageBoxes setPageBox getPageLabels setPageLabels pageLabel setPageTransition getPageTransition clearPageTransition setHeader setFooter removeHeaders removeFooters headerFooter setRunningHeaderFooter runningHeaderFooter renderPage renderPageNoText renderPageExcluding renderPageExcludingMarkedContent embedFont addText addStandardText addWatermark neededFonts extractFont extractWebFont embeddedFonts toText toHtml toModel toDocx toPptx toOdp toOdt toXlsx toOds toRtf toPdfA toTagged figureCount setFigureAlt saveEncrypted changePasswords removeEncryption encryptForRecipients sign certify signatures verifySignatures signP12 signTimestamped signLtv getMetadata setMetadata getXmp setXmp setInfo annotations removeAnnotation addSquare addHighlight addLineAnnotation addFreeText addUnderline addStrikeOut addMarkupAnnotation addTextNote addInk addStamp addCircleAnnotation addPolygonAnnotation addPolylineAnnotation addCaretAnnotation regenerateAppearance flattenAnnotations flattenForm flattenFormXObjects links addUriLink addGotoLink addNamedDest namedDests attachments addAttachment addAssociatedFile removeAttachment setCollection collection addDocumentJavascript documentJavascripts removeDocumentJavascript addFileAttachmentAnnot addGotoLinkNamed layers addLayer setLayerVisibility setLayerLocked removeLayer beginOptionalContent endOptionalContent outline setOutline addLink setOpenAction removeLink setBookmarks setViewerPreferences setPageLayout setPageMode fields setTextField setCheckbox setRadio setChoice addTextField addCheckbox addRadioGroup addComboBox addListBox addSignatureField setFieldScript setCalculationOrder removeField regenerateFieldAppearance

    Constructors

    Methods

    • Returns Uint8Array

    • Serialize with PDF 1.5+ object streams + a cross-reference stream (ISO 32000-1 §7.5.7 / §7.5.8) — the most compact output. objectStreams (default true) packs non-stream objects into compressed /ObjStms (needs the xref stream); xrefStreams (default true) writes a /XRef stream. version selects the %PDF-x.y header banner (default "1.7"). Uncompressed streams are Flate-compressed first, like saveCompressed. Linearization (Fast Web View) is not performed.

      Parameters

      • opts: { objectStreams?: boolean; xrefStreams?: boolean; version?: PdfVersion } = {}

      Returns Uint8Array

    • Serialize as a linearized ("Fast Web View") PDF (ISO 32000-1 Annex F).

      The first page and only the objects needed to render it — together with a /Linearized parameter dictionary and a primary hint stream — are written at the front of the file, so a web viewer can display page 1 before the rest of the document has downloaded (progressive rendering / byte-range serving). The remaining pages follow, then a main cross-reference table; the first-page cross-reference section chains to it via /Prev. Streams are Flate-compressed first (like saveCompressed) and embedded fonts are subset.

      Falls back to the plain save output if the document cannot be linearized (no catalog / page tree / zero pages). version selects the %PDF-x.y header banner (default "1.7").

      Parameters

      Returns Uint8Array

    • Every text element on a page, enriched for an editor: the decoded text, its bounding box (user space, bottom-left), the resolved font family + bold/italic, the effective point size, the RGB fill colour and the baseline rotation. index is the text-run index for replaceText, so a host can extract, render and edit text from one model — the native replacement for a reader's per-run text layer (which elements() omits font + colour).

      Parameters

      • page: number

      Returns TextElementInfo[]

    • The document's aggregate language signal — its dominant reading direction (ltr/rtl/neutral), writing system, and a best-effort ISO-639-1 language code — computed across every page's decoded text. Lets a host pick fonts, set the UI direction or label the document without its own bidi pass (e.g. detect an Arabic/Hebrew/Japanese PDF). lang is omitted when the script does not pin a single language.

      Returns DocumentLanguage

    • Every image element on a page: its placement box (user space, bottom-left), the embeddable encoded bytes (data) + format (jpeg/png/jp2/ unknown), and the source pixel dimensions. DCTDecode/JPXDecode images pass through as jpeg/jp2; Flate/raw DeviceRGB|DeviceGray are re-encoded to PNG. The native replacement for a reader's image extraction (bytes + placement).

      Each result's index is the unified element index usable directly with removeElement / transformElement / duplicateElement / moveElement — so you can extract an image and edit that exact image.

      Parameters

      • page: number

      Returns ImageElementInfo[]

    • Every painted vector path on page (frames, rules, lines, filled shapes…) as geometry + style: segments and bounds in user space (origin bottom-left), fill/stroke RGB, line width, alpha and dash. Clip-only paths are omitted. The native replacement for walking a reader's operator list to rebuild the shape layer.

      Each result's index is the unified element index usable directly with setPathStyle / removeElement / transformElement — so you can extract a path and restyle/remove that exact path.

      Parameters

      • page: number

      Returns VectorPathInfo[]

    • The layout blocks of a single page — the structural reconstruction (paragraphs, headings, lists, tables, shapes, images) of the page's flat glyph/path geometry, in reading order (column-major), each GigaBlock keeping a top-down frame and every text run its source_index back to the editable content-stream operator.

      The per-page counterpart of GigaPdfDoc.toModel (which reconstructs the whole document at once): a continuous / lazily-virtualized editor calls this one page at a time. Identifies 1- and 2-column layouts, merges lines into justified/left/centred/right paragraphs, promotes large isolated lines to headings, and recovers ruled tables. An out-of-range page yields [].

      Parameters

      • page: number

      Returns GigaBlock[]

    • Parameters

      • query: string
      • caseInsensitive: boolean = true

      Returns SearchHit[]

    • Replace text run index on page with text. Font-aware: works with any font — a run set in an embedded Type0/Identity-H face (TrueType or OpenType-CFF) is re-encoded through that font's char→glyph map; base-14 and simple fonts use WinAnsi. Returns false if the run/page doesn't exist.

      Parameters

      • page: number
      • index: number
      • text: string

      Returns boolean

    • Parameters

      • page: number
      • index: number

      Returns boolean

    • Parameters

      • page: number
      • index: number
      • dx: number
      • dy: number

      Returns boolean

    • Apply a full affine transform to element index on page, wrapping it in q … cm … Q with the matrix m = [a, b, c, d, e, f]. This generalises moveElement (whose matrix is the pure translate [1,0,0,1,dx,dy]) to scale, rotation, shear and translation in one call. Because it is purely matrix-based it works identically for text, images and shapes — their internal coordinates are never touched. Returns false if the element/page doesn't exist.

      Parameters

      • page: number
      • index: number
      • m: [number, number, number, number, number, number]

      Returns boolean

    • Re-style the path element index on page in place: any provided field overrides that part of the graphics state for the path's paint; omitted fields keep the inherited state. Implemented by wrapping the path's op range in q … Q and injecting the requested state operators (rg/RG/w/d) before its construction + paint ops, so the original paint op now draws with the override and following content is unaffected. RGB colours are [r,g,b] in 0..=1; dash is the PDF dash array ([] = solid). Returns false if the element is not a path (or the page/index doesn't exist).

      Opacity: fillAlpha/strokeAlpha (0..=1) are fully supported — an /ExtGState carrying /ca//CA is registered on the page and a /<gs> gs is injected into the path's q … Q wrap, so the alpha applies to that path run only. (For non-path elements such as images, use setElementOpacity.)

      Parameters

      • page: number
      • index: number
      • style: {
            fill?: [number, number, number];
            stroke?: [number, number, number];
            strokeWidth?: number;
            fillAlpha?: number;
            strokeAlpha?: number;
            dash?: number[];
        }

      Returns boolean

    • Re-style sub-ranges of text run index on page in place — the by-character-run companion of setPathStyle. Each span sets the style of the [start, end) UTF-16 slice of the run's decoded text (bold / italic / underline / strike / colour / size); the run is split so the rest keeps its original style and positioning is preserved (the original glyph codes, including TJ kerning, are sliced and re-emitted — never re-encoded — and each styled slice is wrapped in q … Q). Spans may be given in any order and are clamped to the run's length.

      Notes on each field: color is [r,g,b] in 0..=1 (text fill); sizePt rescales the slice's font in the run's own text scale; bold is faux-bold (fill+stroke render mode) when no bold variant font is wired; italic is a no-op without an italic/oblique variant (a stream edit can't shear glyphs without disturbing advances); underline/strike draw a thin rule in page space. Returns false when index does not resolve to a top-level text run (e.g. it addresses form-XObject text), like setPathStyle for a non-matching element.

      Parameters

      • page: number
      • index: number
      • spans: {
            start: number;
            end: number;
            color?: [number, number, number];
            sizePt?: number;
            bold?: boolean;
            italic?: boolean;
            underline?: boolean;
            strike?: boolean;
        }[]

      Returns boolean

    • Set a constant opacity on element index on page — text, image or shape — by registering an /ExtGState (/ca = /CA = fillAlpha, clamped to 0..=1) on the page and wrapping the element's op range in q /<gs> gs … Q. This is the way to set an image's alpha in place; shapes may also use setPathStyle's fillAlpha/strokeAlpha (same underlying /ExtGState mechanism). Returns false if the page/index doesn't exist.

      Parameters

      • page: number
      • index: number
      • fillAlpha: number

      Returns boolean

    • Change the paint order (z-order) of element index on page. toFront brings it visually on top (its op range is moved to the end of the content stream, painted last); otherwise it is sent behind everything (moved to the start, painted first). The moved range is re-wrapped in q … Q so it neither inherits nor leaks graphics state. Works for text, image and shape elements. The element's index changes after the move — re-read GigaPdfDoc.elements. Returns false if the page/index doesn't exist.

      Parameters

      • page: number
      • index: number
      • toFront: boolean

      Returns boolean

    • Parameters

      • page: number
      • index: number

      Returns boolean

    • Index of the element at page point (x, y), or -1 if none.

      Parameters

      • page: number
      • x: number
      • y: number

      Returns number

    • Draw a vector rectangle. Pass an 0xRRGGBB colour for stroke/fill, or null to omit that paint. 0 → success.

      Parameters

      • page: number
      • x: number
      • y: number
      • w: number
      • h: number
      • stroke: number | null = null
      • fill: number | null = 0
      • lineWidth: number = 1
      • opacity: number = 1

      Returns boolean

    • Draw a straight line from (x1,y1) to (x2,y2). stroke is 0xRRGGBB.

      Parameters

      • page: number
      • x1: number
      • y1: number
      • x2: number
      • y2: number
      • stroke: number = 0
      • lineWidth: number = 1
      • opacity: number = 1

      Returns boolean

    • Draw an ellipse (circle when rx === ry) centred at (cx,cy). Pass an 0xRRGGBB colour for stroke/fill, or null to omit that paint.

      Parameters

      • page: number
      • cx: number
      • cy: number
      • rx: number
      • ry: number
      • stroke: number | null = null
      • fill: number | null = 0
      • lineWidth: number = 1
      • opacity: number = 1

      Returns boolean

    • Paint a linear or radial gradient over rect on page (ISO 32000-1 §8.7.4 shading + §8.7.3 pattern). coords is [x0,y0,x1,y1] for "linear" or [x0,y0,r0,x1,y1,r1] for "radial"; stops is ≥ 2 colour stops (offset 0…1, rgb packed 0xRRGGBB). extend (default [true,true]) sets /Extend; opacity (default 1) is the fill alpha.

      Parameters

      Returns boolean

      doc.addGradient(1, {
      kind: "linear", coords: [50, 50, 250, 50],
      stops: [{ offset: 0, rgb: 0xff0000 }, { offset: 1, rgb: 0x0000ff }],
      rect: { x: 50, y: 40, w: 200, h: 60 },
      });
    • Fill a rectangle with color in any colour space — the press-ready counterpart of addRectangle (CMYK, spot Separation, gray, ICC).

      Parameters

      • page: number
      • rect: Box
      • color: Color
      • opacity: number = 1

      Returns boolean

      doc.addFilledRectangle(1, { x: 40, y: 700, w: 200, h: 40 },
      { space: "cmyk", c: 0.1, m: 0.8, y: 0.9, k: 0 });
    • Fill a polygon through flat [x0,y0,x1,y1,…] points (≥ 3 vertices) with color in any colour space. The path is closed automatically.

      Parameters

      • page: number
      • points: number[]
      • color: Color
      • opacity: number = 1

      Returns boolean

    • Draw a base-14 text run in any colour space — the press-ready counterpart of addTextStandard. font is a base-14 family (Helvetica, Times-Roman, Courier, …).

      Parameters

      • page: number
      • x: number
      • y: number
      • size: number
      • text: string
      • font: string
      • color: Color
      • opts: {
            opacity?: number;
            rotation?: number;
            underline?: boolean;
            strikethrough?: boolean;
        } = {}

      Returns boolean

    • Turn overprint on/off for content drawn after this call (/op fill, /OP stroke, /OPM mode — 0 independent colorants, 1 non-erasing). Essential for prepress black-overprint / trapping.

      Parameters

      • page: number
      • fill: boolean
      • stroke: boolean
      • mode: number = 1

      Returns boolean

    • Add a document-level OutputIntent embedding the ICC profile (its /N is read from the profile), with condition as the output-condition identifier (e.g. "Coated FOGRA39"). Decoupled from the PDF/A path.

      Parameters

      • profile: Uint8Array
      • condition: string

      Returns boolean

    • Draw a polyline/polygon through flat [x0,y0,x1,y1,…] points. close joins the last vertex back to the first. 0xRRGGBB colours, or null to omit.

      Parameters

      • page: number
      • points: number[]
      • close: boolean = true
      • stroke: number | null = null
      • fill: number | null = 0
      • lineWidth: number = 1
      • opacity: number = 1

      Returns boolean

    • Draw an SVG path (M/L/C/Q/Z…) anchored so the SVG origin maps to (ox,oy) with the Y axis flipped — same convention as pdf-lib's drawSvgPath. Covers freeform/polygon/triangle shapes.

      Parameters

      • page: number
      • svgPath: string
      • ox: number
      • oy: number
      • stroke: number | null = null
      • fill: number | null = 0
      • lineWidth: number = 1
      • opacity: number = 1

      Returns boolean

    • Embed a raster image at (x,y) sized (w,h) in PDF user space. Format auto-detected: PNG, JPEG, GIF, WebP, AVIF, TIFF (non-PNG/JPEG decoded to RGBA in pure Rust/WASM). PNG alpha is honoured; opacity (0..1) sets an overall alpha.

      Parameters

      • page: number
      • data: Uint8Array
      • x: number
      • y: number
      • w: number
      • h: number
      • opacity: number = 1

      Returns boolean

    • Replace the pixels of an existing image XObject in place — swap a logo or photo while every reference to it stays intact (ISO 32000-1 §8.9). index is the unified element index of an image on page, exactly the index reported by imageElements (and accepted by removeElement / transformElement); data is any raster the engine decodes — PNG, JPEG, WebP, GIF, TIFF or AVIF (the same set addImage accepts).

      Unlike a delete-then-re-add, the image keeps its object number, every /Do placement, and its position / scale / rotation / clip matrix — only the stream bytes and the image dictionary (/Width, /Height, /ColorSpace, /BitsPerComponent, /Filter) are rewritten. The new raster is re-encoded through the same path as addImage (PNG alpha → a fresh /SMask; JPEG → /DCTDecode passthrough). It need not match the old pixel size — it is drawn into the same box (transform the element first to re-fit it).

      Returns false if page/index doesn't resolve to a top-level image, or the bytes aren't a decodable raster.

      Parameters

      • page: number
      • index: number
      • data: Uint8Array

      Returns boolean

    • Stamp an image watermark across pages from raw image bytes. Accepts the formats the engine decodes — PNG, JPEG, WebP, GIF, AVIF, TIFF. The image is embedded once and referenced on every target page.

      opts.pages is a list of 1-based page numbers; omit it (or pass []) to stamp every page. opts.anchor positions the image ('center' default, or a corner) and opts.offsetX/offsetY nudge it (in points; in tile mode they become the gaps between tiles). opts.width/height set the target size in points (height keeps the source aspect ratio when omitted). opts.rotationDeg rotates about the image centre and opts.opacity (0–1) sets the alpha. Returns false if the image can't be decoded.

      Parameters

      • data: Uint8Array
      • opts: {
            pages?: number[];
            anchor?:
                | "center"
                | "top-left"
                | "top-right"
                | "bottom-left"
                | "bottom-right";
            offsetX?: number;
            offsetY?: number;
            width?: number;
            height?: number;
            rotationDeg?: number;
            opacity?: number;
            tile?: boolean;
        } = {}

      Returns boolean

    • Draw SVG markup on a page as native vector paths (crisp at any zoom, not rasterized), fitting its viewBox into the box (x, y, w, h) in PDF points (origin bottom-left). Supports shapes, <path>, groups, transforms and fill/stroke/opacity. Returns false if the SVG can't be parsed.

      Parameters

      • page: number
      • svg: string
      • x: number
      • y: number
      • w: number
      • h: number

      Returns boolean

    • True redaction: delete content intersecting the region (no opaque cover by default).

      Parameters

      • page: number
      • x: number
      • y: number
      • w: number
      • h: number
      • coverRgb: number = 0
      • hasCover: boolean = false

      Returns number

    • True PII redaction of one or more rectangles (x, y, width, height) in PDF points (origin bottom-left), in a single call. For every rect this:

      • deletes the overlapping text/vector elements from the content stream — the glyphs and their /ToUnicode mapping are gone, so copy/paste and text extraction reveal nothing in the area;
      • overwrites the pixels of any underlying image (a scan/photo) with opaque black — only the intersecting sub-rectangle, so the rest of the page image survives — and re-encodes the image, erasing the sensitive pixels from the bytes (not merely covering them);
      • strips overlapping annotations and clears their form-field values;
      • paints an opaque black box over the rect as the visible redaction mark.

      The black cover is the default for PII (unlike redact). Pass opts.coverRgb to change the mark colour, or opts.cover = false to remove the content/pixels with no visible box. Returns the number of content elements deleted across all rects.

      Parameters

      • page: number
      • rects: { x: number; y: number; width: number; height: number }[]
      • opts: { cover?: boolean; coverRgb?: number } = {}

      Returns number

    • Parameters

      • page: number
      • degrees: number

      Returns boolean

    • Parameters

      • page: number

      Returns boolean

    • Parameters

      • from: number
      • to: number

      Returns boolean

    • Append pages of another PDF onto this document. With no pages, every page is appended (powers merge). With pages — 1-based page numbers, in the order given — only that selection is brought in (ISO 32000-1 §7.7.3), each page keeping its content, resources, annotations and box geometry. Numbers out of range are skipped; an empty/all-out-of-range selection returns false.

      Parameters

      • otherPdf: Uint8Array
      • Optionalpages: number[]

      Returns boolean

    • Add an invisible (text render mode 3) standard-Helvetica text layer to page in a SINGLE content append — for OCR. Each run is {x, y, size, text, rotation?} (PDF user space, baseline-anchored, rotation° CCW). Runs whose text has any non-WinAnsi glyph are skipped. Returns the number of runs actually written (0 on engine error).

      Parameters

      • page: number
      • runs: { x: number; y: number; size: number; text: string; rotation?: number }[]

      Returns number

    • Extract the given 1-based page numbers into a NEW standalone PDF.

      Parameters

      • pages: number[]

      Returns Uint8Array

    • Resize a page's /MediaBox to width×height points — box geometry only. The drawn content keeps its own coordinates (it is not rescaled to the new box, so it may clip or float). To scale the page content along with the box (keeping annotations aligned) use scalePageContent or scalePageTo; for large-format authoring see setUserUnit.

      Parameters

      • page: number
      • width: number
      • height: number

      Returns boolean

    • Scale a page's content uniformly by factor about the page origin (ISO 32000-1 §8.3.4) — a true zoom of the whole page, not just the box. Three things move together: (1) the content stream is wrapped in q <factor 0 0 factor 0 0> cm … Q; (2) /MediaBox and /CropBox (resolved through inheritance) plus any locally declared /BleedBox//TrimBox/ /ArtBox are scaled about the origin; (3) every annotation /Rect is scaled, so widget/stamp appearances — mapped from their /BBox into the /Rect per §12.5.5 — rescale to stay aligned automatically. factor must be finite and positive. false on engine error (bad page number / non-positive factor).

      Parameters

      • page: number
      • factor: number

      Returns boolean

    • Anisotropic scalePageContent: scale a page's content by sx horizontally and sy vertically about the origin, scaling the boxes and annotation /Rects by the same factors. Both must be finite and positive. false on engine error.

      Parameters

      • page: number
      • sx: number
      • sy: number

      Returns boolean

    • Scale a page's content to fit within width×height points (shrink- or grow-to-fit), preserving aspect ratio — equivalent to scalePageContent with min(width / currentWidth, height / currentHeight) over the page's displayed size (/MediaBox with /Rotate applied). Returns the uniform factor applied, or null on engine error (bad page number, non-positive target, or zero-area page).

      Parameters

      • page: number
      • width: number
      • height: number

      Returns number | null

    • Set a page's /UserUnit (ISO 32000-1 §14.11.2) for large-format authoring: one default user-space unit becomes unit⁄72 inch, so the same coordinates render larger (e.g. 2.0 doubles the physical size, lifting the ~200-inch coordinate ceiling). 1.0 is the default and removes the key. This is distinct from scalePageContent: it rescales the coordinate system (a viewer-level zoom of the medium), not the content or boxes. unit must be finite and positive. false on engine error.

      Parameters

      • page: number
      • unit: number

      Returns boolean

    • A page's /UserUnit (ISO 32000-1 §14.11.2), defaulting to 1.0 when absent. Returns null on engine error (bad page number).

      Parameters

      • page: number

      Returns number | null

    • Insert a blank page after the 1-based after page (0 = front); returns its id.

      Parameters

      • width: number
      • height: number
      • after: number = 0

      Returns number

    • Duplicate a page, inserting the copy right after it; returns the new page's id.

      Parameters

      • page: number

      Returns number

    • N-up imposition (ISO 32000-1 §8.10): draw the content of the 1-based source page, scaled and translated, onto the 1-based target page — the basis for 2-up/4-up, booklets, contact sheets and page-on-page stamping. The source page becomes a Form XObject (its content + /Resources, so its fonts and images come along) and is drawn with q <cm> /Fmn Do Q appended to the target. (x, y) is where the visible page's lower-left corner lands and (scaleX, scaleY) scale the page as displayed (its /MediaBox origin and /Rotate are absorbed into the matrix). Wrapped in q/Q, so it never disturbs existing target content and is composable — call it repeatedly (different sources and/or cells) to build an N-up sheet. source and target may be the same page. false on engine error (bad page number).

      Parameters

      • target: number
      • source: number
      • x: number
      • y: number
      • scaleX: number
      • scaleY: number

      Returns boolean

    • Place source onto target (both 1-based) using an explicit content-stream matrix [a, b, c, d, e, f] — the low-level primitive behind placePage for full control of the affine (shear, arbitrary rotation, reflection). The matrix maps the source page's form space (its user space, including the /MediaBox origin) to the target; unlike placePage no origin/rotation normalisation is applied, so identity draws the source 1:1 at the target origin. false on engine error.

      Parameters

      • target: number
      • source: number
      • matrix: [number, number, number, number, number, number]

      Returns boolean

    • Impose all existing pages cols × rows per sheet onto freshly added sheets (2-up, 4-up, booklet thumbnails, contact sheets). Pages go left-to-right, top-to-bottom; each is scaled uniformly to fit its cell (aspect preserved) and centred. The new sheets are appended after the last original page and the originals are removed, leaving only the imposed sheets. Returns the number of sheets produced (negative on error: cols/ rows 0, or an empty document). sheetWidth/sheetHeight default to A4 portrait; margin/gutter to 14 pt.

      Parameters

      • cols: number
      • rows: number
      • opts: { sheetWidth?: number; sheetHeight?: number; margin?: number; gutter?: number } = {}

      Returns number

    • A page's size (points) and /Rotate (0/90/180/270).

      Parameters

      • page: number

      Returns PageInfo

    • A page's margins (points): the gap between /CropBox and /MediaBox when a CropBox exists, else estimated from the content bounding box.

      Parameters

      • page: number

      Returns PageMargins

    • Set a page's margins (points) by insetting its /CropBox from the /MediaBox — a real, visible margin change. Returns true on success.

      Parameters

      Returns boolean

    • Store an opaque JSON string as the document's GigaPDF editor-metadata sidecar — private editor state that travels with the PDF (catalog /GigaPDF /EditorMeta, a FlateDecode-compressed stream). It is ignored by every standard PDF reader and the round-trip survives save/open. Pass a JSON object if you also use setEditorMargins (which read-modify-writes that object's margins key). Returns true on success.

      Parameters

      • json: string

      Returns boolean

    • The document's GigaPDF editor-metadata sidecar string (set by setEditorMeta), or null when the document carries none.

      Returns string | null

    • Record the editor's per-page display margins (points) in the editor-metadata sidecar (under margins, keyed by page) without touching /CropBox or /MediaBox — distinct from setPageMargins, which performs a real visible recrop. Any other host keys in the sidecar are preserved. Returns true on success.

      Parameters

      Returns boolean

    • The editor's per-page display margins (points) recorded for page by setEditorMargins, or null when none were stored. Reads only the sidecar — never /CropBox.

      Parameters

      • page: number

      Returns PageMargins | null

    • All five page boundary boxes (media/crop/bleed/trim/art) for the 1-based page, each as [x0, y0, x1, y1] in points, with ISO 32000-1 inheritance and defaults applied. See PageBoxes for the exact default chain and the declared flags.

      Parameters

      • page: number

      Returns PageBoxes

    • Set one of a page's boundary boxes. kind is one of PAGE_BOX_KINDS and box is given as { x, y, w, h } (origin + size, points); it is written as [x, y, x+w, y+h], normalised so reversed sizes are accepted. Sibling boxes are preserved. Returns true on success, false for an unknown kind, a degenerate box (zero/negative area), or a bad page number.

      Setting "trim"/"bleed" is the prerequisite for PDF/X and commercial-print (imposition, bleed, finished-size) pipelines.

      Parameters

      • page: number
      • kind: "media" | "crop" | "bleed" | "trim" | "art"
      • box: Box

      Returns boolean

    • The document's page-label ranges (/PageLabels, ISO 32000-1 §12.4.2), sorted by startPage (1-based). Empty when the document declares no page labels.

      Returns PageLabelRange[]

    • Replace the document's page labels. Pass an empty array to remove all labels. Ranges are sorted by startPage and collapsed to one entry per page (last wins). Returns true on success.

      Parameters

      Returns boolean

      // Front matter in lowercase roman, body in decimal, appendix "A-1, A-2…".
      doc.setPageLabels([
      { startPage: 1, style: "romanLower", prefix: "", startNumber: 1 },
      { startPage: 5, style: "decimal", prefix: "", startNumber: 1 },
      { startPage: 20, style: "decimal", prefix: "A-", startNumber: 1 },
      ]);
    • The viewer-visible label string for the 1-based page (e.g. "iv", "A-3"), resolving the applicable /PageLabels range; the decimal page number when no range applies (including a document with no page labels).

      Parameters

      • page: number

      Returns string

    • Author a presentation transition + auto-advance on page (1-based), ISO 32000-1 §12.4.4. Writes the page's /Trans dictionary from PageTransition.style plus only the optional sub-keys that apply to that style (dimension/motion for split, direction/scale/ flyAreaOpaque for fly, …) — inapplicable fields are dropped. PageTransition.displayDuration becomes the page's /Dur (auto-advance); omitting it removes any existing /Dur. Re-calling replaces the prior transition in full (idempotent). Returns true on success, false for an unknown style, a negative/non-finite duration/scale/ displayDuration, or a bad page number.

      Parameters

      Returns boolean

      // Kiosk slideshow: every page wipes in over 0.5 s, auto-advancing after 5 s.
      for (let p = 1; p <= doc.pageCount(); p++) {
      doc.setPageTransition(p, { style: "wipe", duration: 0.5, displayDuration: 5 });
      }
    • The presentation transition declared on page (1-based), or null when the page has no /Trans (ISO 32000-1 §12.4.4). Optional fields that do not apply to the recovered style are omitted from the result.

      Parameters

      • page: number

      Returns PageTransition | null

    • Remove any presentation transition from page (1-based) — drops the page's /Trans dictionary and its /Dur auto-advance entry. A no-op if neither is present. Returns true on success.

      Parameters

      • page: number

      Returns boolean

    • Bake a running header onto every in-range page (idempotent: re-baking replaces the prior header). Returns true on success.

      Parameters

      Returns boolean

    • Remove every previously-baked running header from all pages.

      Returns boolean

    • Remove every previously-baked running footer from all pages.

      Returns boolean

    • Detect the running header/footer already baked into this PDF — the reader counterpart of GigaPdfDoc.setHeader / GigaPdfDoc.setFooter. Each side is a HeaderFooterSpec (with its recovered text) when a baked /GPHF span is present, or null when absent. The text is faithful (the per-page-substituted text of the first matching page); align, fontSize, color, etc. are best-effort defaults, since the bake records only the drawn text. Use it to reflect existing document state (e.g. a Word-like editor toggle).

      Returns { header: HeaderFooterSpec | null; footer: HeaderFooterSpec | null }

    • Bake a rich, Word-like running header/footer from a RunningHeaderFooter def (the source of truth — stored in the editor-meta sidecar, its visible /GPHF band regenerated on every page). Text is set in an embedded font (each item's fontRef, else the bundled OFL face — never base-14) and images via the same path as addImage; both live inside the /GPHF span, so they are excluded from elements/textRuns and masked by renderPageExcludingMarkedContent. Idempotent (re-baking replaces the prior band).

      opts.date is the bake date for {{date}} (the engine is clockless — pass e.g. new Date().toISOString().slice(0, 10)); omit to fall back to the document's /Info date. opts.images supplies the pixels each HFItem of type: "image" references by imageId — an iterable of [imageId, bytes] (a Map<number, Uint8Array> works directly); an image whose id is absent is skipped. Returns true on success.

      Parameters

      • def: RunningHeaderFooter
      • Optionalopts: {
            date?: string;
            images?: Iterable<[number, Uint8Array<ArrayBufferLike>], any, any>;
        }

      Returns boolean

      doc.setRunningHeaderFooter(
      {
      default: {
      header: [{ type: "image", imageId: 1, w: 80, h: 24, anchor: "left" }],
      footer: [{ type: "text", text: "{{title}} — {{page}}/{{pages}}", anchor: "center" }],
      },
      firstPage: { header: [], footer: [] }, // blank cover
      differentFirstPage: true,
      differentOddEven: true,
      evenPage: { header: [{ type: "text", text: "{{page}}", anchor: "left" }], footer: [] },
      oddPage: { header: [{ type: "text", text: "{{page}}", anchor: "right" }], footer: [] },
      },
      { date: new Date().toISOString().slice(0, 10), images: new Map([[1, logoPng]]) }
      );
    • Parameters

      • page: number
      • scale: number = 1

      Returns Uint8Array

    • Rasterize a page to a PNG without the page content stream's text — glyphs are suppressed while gradients, shadings, images, vectors and patterns are preserved. Form-field widget appearances are omitted (the editor re-shows their values as an editable overlay, so baking them in would double every field); other annotation appearances (stamps, highlights, ink) are still painted. Use this to paint a text-free raster background the editor can overlay real, editable text on top of.

      Parameters

      • page: number
      • scale: number = 1

      Returns Uint8Array

    • Rasterize a page to a PNG while omitting the given top-level element indices (from GigaPdfDoc.elements). Each excluded element paints nothing — fills, strokes, shadings, images and text alike — while everything else (including the non-text content of non-excluded elements) renders normally. Use it to paint a background without specific elements and overlay live, editable versions on top. Generalises renderPageNoText (which suppresses all text). Like renderPageNoText, form-field widget appearances are omitted (the editor re-shows them as an editable overlay); other annotation appearances are painted. An empty indices renders the full page; unknown indices are ignored.

      Parameters

      • page: number
      • indices: number[]
      • scale: number = 1

      Returns Uint8Array

    • Rasterize a page to a PNG excluding the ops inside a baked marked-content span named marker — and, when skipText is true, the page's text too — in a single raster pass. For marker = "GPHF" (the default) this drops the baked running header/footer band: the extraction views (elements, textRuns) already omit that band (it is never editable body content), and this render omits it from the picture so it cannot double against an editable overlay. With skipText = true it is the editor's text-free display background minus the band; with skipText = false, the full page minus the band. Like renderPageNoText, form-field widget appearances are omitted.

      Parameters

      • page: number
      • scale: number = 1
      • skipText: boolean = true
      • marker: string = "GPHF"

      Returns Uint8Array

    • Embed an outline font program as a Type0 font and return its object number (pass to addText / re-encoded by replaceText). Accepts any font file — glyf TrueType (.ttf) or OpenType-CFF (.otf/OTTO), flavour auto-detected — so font may be a Google Font the host fetched, an .otf you supply, or a face pulled out of a document with extractFont. Returns 0 on a malformed/unsupported program.

      Parameters

      • family: string
      • font: Uint8Array

      Returns number

    • Draw real, selectable text at (x, y) (PDF points, origin bottom-left) in a font embedded with embedFont (fontObj). Works with any embedded face — glyf TrueType or OpenType-CFF — encoding each character through the font's char→glyph map (Identity-H, 2-byte glyph ids). rgb is packed 0xRRGGBB; rotationDeg rotates CCW about (x, y). For a built-in base-14 family with no embedding, use addStandardText.

      Pass opts to bake text decorations into the run: { underline: true } draws a rule just below the baseline, { strikethrough: true } a rule near the x-height — both span the run's advance and are filled in the text colour. Omitting opts is fully backward-compatible (no decoration).

      Parameters

      • page: number
      • x: number
      • y: number
      • size: number
      • text: string
      • fontObj: number
      • rgb: number = 0
      • opacity: number = 1
      • rotationDeg: number = 0
      • Optionalopts: { underline?: boolean; strikethrough?: boolean }

      Returns boolean

    • Draw text at (x, y) in a built-in base-14 standard font (fontName, e.g. "Times-Bold", "Courier-Oblique", "Symbol") — no embedding needed, every viewer ships these 14. For any other family embed a TrueType with embedFont (a Google Font fetched by the host, or one pulled out of the document with extractFont) and use addText. Returns false on an unknown font name or bad page.

      Pass opts to bake text decorations into the run: { underline: true } and/or { strikethrough: true } draw filled rules in the text colour. Omitting opts is fully backward-compatible (no decoration).

      Parameters

      • page: number
      • x: number
      • y: number
      • size: number
      • text: string
      • fontName: string
      • rgb: number = 0
      • opacity: number = 1
      • rotationDeg: number = 0
      • Optionalopts: { underline?: boolean; strikethrough?: boolean }

      Returns boolean

    • Stamp a standard-Helvetica watermark (no font embed needed): text at (x, y), rotated rotationDeg° counter-clockwise, rgb packed 0xRRGGBB, opacity 0–1. Pair with GigaPdfEngine.helveticaWidth for centring.

      Parameters

      • page: number
      • x: number
      • y: number
      • size: number
      • text: string
      • rgb: number = 0x808080
      • opacity: number = 0.25
      • rotationDeg: number = 0

      Returns boolean

    • Extract an embedded font program by (fuzzy) /BaseFont name — so a host editor can re-embed the document's own font when re-baking edited text and keep the original glyphs. Returns the raw decoded bytes and the program format (truetype embeds directly; cff/type1 need a TTF conversion), or null when nothing embedded matches.

      Parameters

      • name: string

      Returns { format: "truetype" | "cff" | "type1"; bytes: Uint8Array } | null

    • Extract an embedded font as a browser-loadable sfnt by (fuzzy) /BaseFont name — for a host editor's @font-face overlay-text layer. Unlike extractFont (raw program, for re-embedding), this always returns bytes a browser's FontFace/OTS will accept, keeping the document's own glyphs (no substitution): a bare CFF (Type1C) is wrapped to OpenType with a cmap from its charset, and a cmap-less TrueType subset is repaired with a cmap synthesised from the PDF's code → Unicode (original glyf kept). truetype/otf are directly loadable; cff/type1 are raw last-resort fallbacks. null when nothing embedded matches.

      Parameters

      • name: string

      Returns { format: "truetype" | "cff" | "type1" | "otf"; bytes: Uint8Array } | null

    • The fonts embedded in the document — each { baseFont, format }. Pair with extractFont to pull a font's bytes out and re-embed them via embedFont, e.g. to draw new text (with addText) in a face the document already carries — no external font file needed.

      Returns EmbeddedFont[]

    • Convert to an editable OpenDocument Presentation (.odp).

      Returns Uint8Array

    • Re-serialize the document as PDF/A (archival).

      level selects the conformance flavour (default "pdfa-2b"):

      • "pdfa-1b" — ISO 19005-1, based on PDF 1.4.
      • "pdfa-1a" — ISO 19005-1 Tagged PDF (level A): 1b + a logical structure tree, marked content and /Lang. Built from the structure the engine reconstructs (paragraphs, headings, tables, lists).
      • "pdfa-2b" — ISO 19005-2 (default).
      • "pdfa-2u" — like 2b but requires every glyph Unicode-mapped (a /ToUnicode CMap on each font); only validator-clean when the source fonts already carry one — otherwise prefer "pdfa-2b".
      • "pdfa-2a" — ISO 19005-2 Tagged PDF (level A): 2u + a logical structure tree and marked content (/StructTreeRoot, /MarkInfo).
      • "pdfa-3b" — ISO 19005-3; permits embedded file attachments.

      Full conformance also requires every font embedded — this method does not embed missing fonts (see the Rust to_pdfa_level docs). For the level-A (1a/2a) flavours the tagging is rendering-neutral: it only inserts balanced marked-content operators and a structure tree, never changing the page appearance.

      Parameters

      • level: "pdfa-1b" | "pdfa-1a" | "pdfa-2b" | "pdfa-2u" | "pdfa-2a" | "pdfa-3b" = "pdfa-2b"

      Returns Uint8Array

    • Author a tagged (accessible) PDF — a /StructTreeRoot logical-structure tree (P/H1H6/Table/L/Figure …) with marked content, /MarkInfo, /Lang, /RoleMap and /Alt on figures — without forcing PDF/A. Pass { pdfUa: true } to also stamp the PDF/UA-1 identifier (ISO 14289). If the document has no reconstructable structure the plain PDF is returned. ISO 32000-1 §14.7/§14.8.

      Parameters

      • opts: { pdfUa?: boolean } = {}

      Returns Uint8Array

    • The number of taggable figures the engine reconstructs across the whole document — the valid range 0..figureCount() for setFigureAlt's index. Each figure is an image the geometric reconstruction surfaces; the Tagged-PDF / PDF-A-level-A export emits one /Figure structure element per figure, in this same order.

      Returns number

    • Attach author-supplied alternate text (/Alt) to a figure so assistive technology can describe the image (WCAG / PDF/UA, ISO 32000-1 §14.9.3).

      index is the document-global figure index — figures are numbered 0, 1, 2, … in page order, then in page-content order within each page (the Nth image of the whole document is figure N; figureCount bounds the range). The text lands on the matching /Figure structure element's /Alt when an accessible export is produced — toTagged or toPdfA with "pdfa-1a"/"pdfa-2a". Figures with no author-supplied text keep a generic non-empty placeholder, so the output stays structurally valid even for unlabeled figures.

      Returns true on success; false if alt is empty (a /Alt must be non-empty) or the call otherwise fails.

      Parameters

      • index: number
      • alt: string

      Returns boolean

    • Serialize the document encrypted with the PDF Standard Security Handler. Defaults to AES-256 (R6). fileId is the document /ID (any stable hex/string). For AES-256 a secret 32-byte key is required — it is taken from opts.keySeed or generated with Web Crypto; RC4/AES-128 derive their key from the password and ignore it.

      Parameters

      • password: string
      • fileId: string
      • opts: {
            ownerPassword?: string;
            algorithm?: "rc4" | "aes128" | "aes256";
            flags?: Partial<PdfPermissions>;
            permissions?: number;
            keySeed?: Uint8Array<ArrayBufferLike>;
        } = {}
        • OptionalownerPassword?: string
        • Optionalalgorithm?: "rc4" | "aes128" | "aes256"
        • Optionalflags?: Partial<PdfPermissions>

          Named access permissions (ISO 32000-1 Table 22). Omitted flags default to granted. Takes precedence over permissions when present.

        • Optionalpermissions?: number

          Raw signed 32-bit /P bitmask. Use flags (above) for a readable API. Defaults to all permissions granted when neither is given.

        • OptionalkeySeed?: Uint8Array<ArrayBufferLike>

      Returns Uint8Array

    • Re-encrypt an already-opened (decrypted) document with new passwords, discarding the prior encryption (ISO 32000-1 §7.6). Opening with the old password is what authorises the change. Mirrors saveEncrypted plus encryptMetadata (when false, the metadata stream is left in the clear).

      Parameters

      • newPassword: string
      • fileId: string
      • opts: {
            ownerPassword?: string;
            algorithm?: "rc4" | "aes128" | "aes256";
            flags?: Partial<PdfPermissions>;
            permissions?: number;
            keySeed?: Uint8Array<ArrayBufferLike>;
            encryptMetadata?: boolean;
        } = {}

      Returns Uint8Array

    • Strip encryption from an already-opened (decrypted) document, returning a plaintext PDF. The document must have been opened with a valid password.

      Returns Uint8Array

    • Encrypt the document to one or more X.509 recipients (public-key / certificate security, ISO 32000-1 §7.6.5, /Filter /Adobe.PubSec): only a holder of a recipient private key can open it — no shared password. certificates are DER X.509 certs. seed/rngSeed default to Web Crypto randomness. Open the result with GigaPdfEngine.openWithPrivateKey.

      Parameters

      • certificates: Uint8Array<ArrayBufferLike>[]
      • opts: {
            flags?: Partial<PdfPermissions>;
            permissions?: number;
            aes256?: boolean;
            encryptMetadata?: boolean;
            seed?: Uint8Array<ArrayBufferLike>;
            rngSeed?: Uint8Array<ArrayBufferLike>;
        } = {}

      Returns Uint8Array

    • Self-signed digital signature. random ≥ 256 bytes from crypto.getRandomValues.

      Parameters

      • fields: string
      • random: Uint8Array
      • keyBits: number = 2048

      Returns Uint8Array

    • Certify the document (DocMDP) — like sign but also declares which later changes are allowed: docmdpLevel is 1 (no changes), 2 (form-fill

      • sign) or 3 (also annotate). fields is the same tab-separated string as sign (name⇥reason⇥date⇥notBefore⇥notAfter).

      Parameters

      • fields: string
      • random: Uint8Array
      • docmdpLevel: 1 | 2 | 3
      • keyBits: number = 2048

      Returns Uint8Array

    • Cryptographically verify every signature against pdf — the original bytes this document was opened from. Each report carries byteRangeOk, digestOk (content integrity), signatureOk (the RSA signature), coversWholeDocument, the signer CN, and the algorithm.

      Parameters

      • pdf: Uint8Array

      Returns SignatureReport[]

    • Sign with a PKCS#12 (.p12/.pfx) identity — a CA-issued / eIDAS certificate and its RSA key, imported natively (no external crypto). opts populates the signature dictionary: name (/Name), reason (/Reason), date (/M, a PDF date string e.g. D:20260616120000Z), and the optional location (/Location) and contactInfo (/ContactInfo). Throws a single generic error on a wrong password, malformed file, unsupported cipher, or missing certificate.

      Parameters

      Returns Uint8Array

    • Sign with an embedded RFC 3161 trusted timestamp (PAdES-B-T). Unlike sign/signP12 this is async: the timestamp requires a network round trip to a TSA, so the method runs the engine's two-phase flow — build the signature → POST the TimeStampReq to the TSA → embed the returned token — with the HTTP in between.

      The signing identity is opts.p12 (+ opts.password) when supplied, else a generated self-signed digital ID from opts.random (+ notBefore/ notAfter). opts.tsaUrl is the TSA endpoint (e.g. FreeTSA https://freetsa.org/tsr); pass opts.tsaFetch to customise the request (auth, proxy, SSRF allow-list). Throws a single generic error on any failure (bad identity, TSA HTTP error, malformed response, or signature too large).

      Parameters

      Returns Promise<Uint8Array<ArrayBufferLike>>

    • Sign with long-term validation material embedded (PAdES-B-LT, or B-LTA with opts.archiveTimestamp). Builds a B-T signature (signTimestamped), then fetches the certificate chain's revocation material (OCSP responses / CRLs, by URL from the certificates — the engine computes which URLs, the host fetches) and stores it in a /DSS, so the signature validates long after the certificates expire or are revoked. With archiveTimestamp a document timestamp over the whole file (DSS included) is added for renewable archival.

      async, multi-round-trip: one TSA POST for the B-T timestamp, one OCSP/CRL fetch per chain certificate, and (if archiveTimestamp) a second TSA POST. Unreachable responders are skipped — the DSS is built from whatever resolves; a self-signed identity (no AIA/CRL-DP) simply yields a /DSS/Certs-only store. Override tsaFetch/revocationFetch/crlFetch to add auth, proxies, or an SSRF allow-list. Throws on a fatal failure (bad identity, B-T signature, or a malformed PDF the DSS can't chain to).

      Parameters

      Returns Promise<Uint8Array<ArrayBufferLike>>

    • Parameters

      • key: string

      Returns string

    • Set a single Info-dictionary entry (e.g. "Title", "Author"). This touches only /Info; use setInfo to update the typed fields and keep the XMP /Metadata packet in sync.

      Parameters

      • key: string
      • value: string

      Returns boolean

    • The document's XMP metadata packet (catalog /Metadata, ISO 32000-1 §14.3.2) as raw bytes, or null when the document carries no XMP.

      Returns Uint8Array<ArrayBufferLike> | null

    • Replace (or create) the document's XMP metadata stream (catalog /Metadata, stored uncompressed). Accepts a UTF-8 string or raw bytes. Returns true on success.

      Parameters

      • xmp: string | Uint8Array<ArrayBufferLike>

      Returns boolean

    • Set the standard document-information fields, writing both the /Info dictionary and a synced XMP /Metadata packet so the two never drift. This is a partial update — only the fields you provide are changed; omit a field to leave it untouched. Returns true on success.

      Parameters

      Returns boolean

      doc.setInfo({ title: "Annual Report", author: "Ada Lovelace", keywords: "finance, 2026" });
      
    • Parameters

      • page: number
      • index: number

      Returns boolean

    • Parameters

      • page: number
      • x0: number
      • y0: number
      • x1: number
      • y1: number
      • stroke: number | null = 0
      • fill: number | null = null
      • lineWidth: number = 1

      Returns boolean

    • Parameters

      • page: number
      • x0: number
      • y0: number
      • x1: number
      • y1: number
      • rgb: number = 0xffff00

      Returns boolean

    • Add a /Line annotation from (x1,y1) to (x2,y2). When endArrow is true, an open arrowhead (/LE [/None /OpenArrow]) is drawn at the (x2,y2) end — a real, editable annotation in conforming readers, ideal for callouts that point at content.

      Parameters

      • page: number
      • x1: number
      • y1: number
      • x2: number
      • y2: number
      • rgb: number = 0
      • lineWidth: number = 1
      • endArrow: boolean = false

      Returns boolean

    • Parameters

      • page: number
      • x0: number
      • y0: number
      • x1: number
      • y1: number
      • text: string
      • fontSize: number = 12
      • rgb: number = 0

      Returns boolean

    • Parameters

      • page: number
      • x0: number
      • y0: number
      • x1: number
      • y1: number
      • rgb: number = 0

      Returns boolean

    • Parameters

      • page: number
      • x0: number
      • y0: number
      • x1: number
      • y1: number
      • rgb: number = 0

      Returns boolean

    • Add a text-markup annotation (highlight | underline | strikeout | squiggly) spanning one or more quads (each [x0, y0, x1, y1] in PDF user space, bottom-left origin — multi-quad covers wrapped text), with full reviewer metadata. date is a PDF date string (e.g. "D:20260616T…Z") — the engine has no clock, so the host supplies it.

      Parameters

      • page: number
      • subtype: "underline" | "highlight" | "strikeout" | "squiggly"
      • quads: [number, number, number, number][]
      • rgb: number
      • opacity: number
      • meta: { contents?: string; author?: string; id?: string; date?: string } = {}

      Returns boolean

    • Add a sticky-note (/Text) annotation: a badge at rect ([x0,y0,x1,y1]) that opens a popup with meta.contents. icon is the named icon ("Note", "Comment", …); open sets the initial popup state.

      Parameters

      • page: number
      • rect: [number, number, number, number]
      • rgb: number
      • meta: { contents?: string; author?: string; id?: string; date?: string } = {}
      • icon: string = "Note"
      • open: boolean = false

      Returns boolean

    • Freehand ink annotation from one polyline (points = flat [x0,y0,x1,y1,…]).

      Parameters

      • page: number
      • points: number[]
      • rgb: number = 0
      • lineWidth: number = 1

      Returns boolean

    • Parameters

      • page: number
      • x0: number
      • y0: number
      • x1: number
      • y1: number
      • label: string
      • rgb: number = 0xc00000

      Returns boolean

    • Add a /Circle (ellipse) annotation inscribed in [x0,y0,x1,y1]. stroke (border) and fill (interior) are packed 0xRRGGBB numbers, or null to omit. Returns true on success.

      Parameters

      • page: number
      • x0: number
      • y0: number
      • x1: number
      • y1: number
      • stroke: number | null = 0
      • fill: number | null = null
      • lineWidth: number = 1

      Returns boolean

    • Add a /Polygon annotation — a closed shape through points (a flat [x0, y0, x1, y1, …] array, PDF user space), with optional stroke/fill (0xRRGGBB or null). Returns true on success.

      Parameters

      • page: number
      • points: number[]
      • stroke: number | null = 0
      • fill: number | null = null
      • lineWidth: number = 1

      Returns boolean

    • Add a /PolyLine annotation — an open path through points (a flat [x0, y0, x1, y1, …] array). rgb is packed 0xRRGGBB.

      Parameters

      • page: number
      • points: number[]
      • rgb: number = 0
      • lineWidth: number = 1

      Returns boolean

    • Add a /Caret annotation — a small upward wedge in [x0,y0,x1,y1] marking an insertion point. rgb is packed 0xRRGGBB.

      Parameters

      • page: number
      • x0: number
      • y0: number
      • x1: number
      • y1: number
      • rgb: number = 0

      Returns boolean

    • Regenerate the appearance stream (/AP /N) of the 0-based index annotation on page from its stored geometry, after editing its colour, border or geometry. Returns true on success, false for a bad index or a subtype whose appearance can't be reconstructed (FreeText/Stamp/Text/Link).

      Parameters

      • page: number
      • index: number

      Returns boolean

    • Parameters

      • page: number

      Returns number

    • Flatten the interactive form: bake every field widget across all pages into the page content and drop /AcroForm, so the document is no longer fillable and fields returns empty afterwards. Returns the number of widgets baked (0 when there is no form).

      Returns number

    • Inline a page's form XObjects (/Subtype /Form invoked via Do) into its content stream, de-sharing each placement so the former form text/graphics become ordinary page content with real, editable text-run indices (no form sentinel) — the enabler for editing invoice/template text in place via replaceText / moveElement / removeElement instead of the redact+add overlay. Image XObjects are left untouched. Returns the number of form XObjects inlined (every Do invocation, since each is de-shared).

      Distinct from flattenForm, which flattens AcroForm interactive fields (and drops /AcroForm); this flattens reusable Form XObjects.

      Parameters

      • page: number

      Returns number

    • Parameters

      • page: number
      • x0: number
      • y0: number
      • x1: number
      • y1: number
      • uri: string

      Returns boolean

    • Parameters

      • page: number
      • x0: number
      • y0: number
      • x1: number
      • y1: number
      • targetPage: number

      Returns boolean

    • Register a named destination nametargetPage (a whole-page /Fit view) in the catalog. Links and bookmarks can then jump by name via addGotoLinkNamed; because resolution goes through the catalog (not a frozen page number), the anchor survives page extraction/split as long as its page is kept. Re-using a name overwrites its target.

      Parameters

      • name: string
      • targetPage: number

      Returns boolean

    • Every embedded file attachment in the document's /Names /EmbeddedFiles name tree, decoded. Each Attachment carries the name-tree key, the filespec display name (/UF//F), the embedded stream's MIME (/Subtype) and /Params dates, and the decoded bytes. Entries that don't resolve to a readable embedded stream are skipped, so the result is only extractable files (the native replacement for a reader's getAttachments()).

      Returns Attachment[]

    • Embed bytes as a document-level file attachment named name (/Names /EmbeddedFiles, ISO 32000-1 §7.11.4). Re-using a name replaces that attachment; the bytes are stored FlateDecode-compressed. Returns true on success (false e.g. for an empty name).

      Parameters

      Returns boolean

    • Embed bytes as an associated file (/AF, PDF/A-3) named name with the given AfRelationship — the mechanism Factur-X / ZUGFeRD / Order-X use to carry their invoice XML ("alternative"). The file is also a normal attachment, is linked from the catalog /AF array, and its filespec carries /AFRelationship. Returns true on success.

      Parameters

      Returns boolean

    • Remove the attachment named name (from /Names /EmbeddedFiles and, if present, the catalog /AF array). Returns true if one was removed, false if no attachment had that name.

      Parameters

      • name: string

      Returns boolean

    • Mark this document as an embedded-file portfolio and configure how its attachments are presented, by writing the catalog /Collection (ISO 32000-1 §7.11.6, §12.3.5). The files must already be embedded (add them first with addAttachment / addAssociatedFile); this only adds the presentation layer: the initial view, the schema columns, the sort order, the default file, and per-file column values (each written as a /CI on the matching file's filespec). An empty/omitted schema still produces a valid /Collection. Calling again replaces the previous configuration. Returns true on success (false on a malformed config or write error).

      Parameters

      Returns boolean

    • Read this document's portfolio configuration back from the catalog /Collection — the reader counterpart of setCollection. Returns null when the document is not a portfolio. The recovered CollectionConfig carries the view, the schema columns (sorted by order), the sort, the defaultFile, and each embedded file's /CI column values.

      Returns CollectionConfig | null

    • Install a document-level JavaScript under the catalog /Names /JavaScript name tree (ISO 32000-1 §7.7.3.4 + §12.6.4.16): a named JavaScript action (<< /S /JavaScript /JS … >>) keyed by name. On open, a conforming viewer runs every document-level script in name (lexical) order — this is where form-calculation / validation helper libraries live (e.g. AFNumber_Format). Re-using a name replaces that script; long sources are stored as a FlateDecode stream, and sibling /Names subtrees (/EmbeddedFiles, /Dests, …) are preserved. Returns true on success (false e.g. for an empty name).

      Parameters

      • name: string
      • script: string

      Returns boolean

    • Remove the document-level JavaScript named name from /Names /JavaScript. Returns true if one was removed, false if none had that name.

      Parameters

      • name: string

      Returns boolean

    • Add a page-anchored FileAttachment annotation over rect on the 1-based page, pointing at the already-embedded attachment name (add it first with addAttachment). icon is the visual marker (default "PushPin"). Returns true on success (false if no such attachment exists).

      Parameters

      Returns boolean

    • Add an internal hyperlink over a rectangle that jumps to the named destination name (define it with addNamedDest). Unlike addGotoLink (an explicit page), this stores /Dest /name, keeping cross-references intact through split/extract.

      Parameters

      • page: number
      • x0: number
      • y0: number
      • x1: number
      • y1: number
      • name: string

      Returns boolean

    • Create a new (visible, unlocked) layer; returns its id (0 on error).

      Parameters

      • name: string

      Returns number

    • Parameters

      • id: number
      • visible: boolean

      Returns boolean

    • Parameters

      • id: number
      • locked: boolean

      Returns boolean

    • Parameters

      • id: number

      Returns boolean

    • Begin an optional-content marked-content sequence on page for the layer ocg (its id, from addLayer). Registers the OCG under the page's /Resources /Properties and appends /OC /OCn BDC to the content stream; every drawing call after it (addText, addRectangle, addImage, …) is gated on that layer's visibility until the matching endOptionalContent appends EMC. Calls nest. Returns the OCn property name (empty string on error).

      Parameters

      • page: number
      • ocg: number

      Returns string

    • End the innermost optional-content sequence on page (EMC).

      Parameters

      • page: number

      Returns boolean

    • Replace the outline. Each entry: {level, page?, title} (page 0/undefined = no dest).

      Parameters

      Returns boolean

    • Add a /Link annotation over rect ({ x, y, w, h }) carrying any Action — the full action & destination model (GoTo with every fit mode, GoToR, URI, Named navigation, Launch, JavaScript, SubmitForm, ResetForm). Returns true on success (false for a malformed action).

      Parameters

      Returns boolean

      doc.addLink(1, { x: 72, y: 700, w: 120, h: 16 },
      { type: "goto", dest: { fit: "xyz", page: 4, top: 720, zoom: 1.5 } });
    • Set the document /OpenAction — the Action performed when the file is opened. Returns true on success.

      Parameters

      Returns boolean

    • Remove the linkIndex-th /Link annotation on page (links counted in order, ignoring non-link annotations). Returns true if one was removed.

      Parameters

      • page: number
      • linkIndex: number

      Returns boolean

    • Replace the outline with Bookmarks that may carry actions (a goto action becomes a /Dest, any other action an /A). An empty array clears the outline. Returns true on success.

      Parameters

      Returns boolean

    • Write the catalog /ViewerPreferences (ISO 32000-1 §12.2). Each omitted field is left unchanged; a boolean sets the key. After applying, an empty dictionary is removed. Returns false on an invalid direction.

      Parameters

      Returns boolean

    • Set the catalog /PageLayout. null removes the key. Returns false on an unknown name.

      Parameters

      Returns boolean

    • Set the catalog /PageMode. null removes the key. Returns false on an unknown name.

      Parameters

      Returns boolean

    • Parameters

      • name: string
      • value: string

      Returns boolean

    • Parameters

      • name: string
      • checked: boolean

      Returns boolean

    • Parameters

      • name: string
      • value: string

      Returns boolean

    • Set a choice field's selection (multi-select list boxes accept several values).

      Parameters

      • name: string
      • values: string[]

      Returns boolean

    • Create a text field on page covering rect = [x0, y0, x1, y1] (PDF user space). Options: maxLen character cap, multiline, password, and visual style.

      Parameters

      • page: number
      • name: string
      • rect: [number, number, number, number]
      • value: string = ""
      • opts: { maxLen?: number; multiline?: boolean; password?: boolean; style?: FieldStyle } = {}

      Returns boolean

    • Create a checkbox. export is the on-state name (default On).

      Parameters

      • page: number
      • name: string
      • rect: [number, number, number, number]
      • checked: boolean = false
      • opts: { export?: string; style?: FieldStyle } = {}

      Returns boolean

    • Create a radio-button group: one logical field whose options are the individual buttons. selected is the initially-chosen export value.

      Parameters

      Returns boolean

    • Create a drop-down combo box. editable permits values outside options.

      Parameters

      • page: number
      • name: string
      • rect: [number, number, number, number]
      • options: string[]
      • opts: { selected?: string; editable?: boolean; style?: FieldStyle } = {}

      Returns boolean

    • Create a scrolling list box. multi allows selecting several options.

      Parameters

      • page: number
      • name: string
      • rect: [number, number, number, number]
      • options: string[]
      • opts: { selected?: string; multi?: boolean; style?: FieldStyle } = {}

      Returns boolean

    • Create a visible signature field (/FT /Sig) over rect — an empty widget the signing pipeline can later target — and flag the AcroForm /SigFlags. Returns true on success.

      Parameters

      • page: number
      • name: string
      • rect: [number, number, number, number]
      • opts: { style?: FieldStyle } = {}

      Returns boolean

    • Attach field-level JavaScript to a field's /AA for the given trigger ("keystroke" filters input, "format" formats display, "validate" checks on change, "calculate" recomputes — ordered by setCalculationOrder). Returns true if set, false if no field has that name.

      Parameters

      • name: string
      • trigger: "format" | "keystroke" | "validate" | "calculate"
      • js: string

      Returns boolean

    • Set the AcroForm calculation order (/CO) — the sequence in which fields with a calculate script recompute. Unknown names are skipped.

      Parameters

      • names: string[]

      Returns boolean

    • Delete a form field by name (removed from /Fields, /CO and every page's annotations). Returns true if a field was removed.

      Parameters

      • name: string

      Returns boolean

    • Rebuild a field's appearance from its current value/style — call after changing a field's value programmatically. Returns true if regenerated (false for an unknown name or a kind that can't be regenerated alone, e.g. a radio parent with kids).

      Parameters

      • name: string

      Returns boolean