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.
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").
Alias of toLinearized — serialize as a linearized (Fast Web View) PDF.
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).
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.
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.
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.
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 [].
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.
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.
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.)
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.
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.
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.
Index of the element at page point (x, y), or -1 if none.
Draw a vector rectangle. Pass an 0xRRGGBB colour for stroke/fill, or
null to omit that paint. 0 → success.
Draw a straight line from (x1,y1) to (x2,y2). stroke is 0xRRGGBB.
Draw an ellipse (circle when rx === ry) centred at (cx,cy). Pass an
0xRRGGBB colour for stroke/fill, or null to omit that paint.
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.
Fill a rectangle with color in any colour space — the press-ready
counterpart of addRectangle (CMYK, spot Separation, gray, ICC).
Fill a polygon through flat [x0,y0,x1,y1,…] points (≥ 3 vertices) with
color in any colour space. The path is closed automatically.
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, …).
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.
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.
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.
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.
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.
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.
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.
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.
True redaction: delete content intersecting the region (no opaque cover by default).
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:
/ToUnicode mapping are gone, so copy/paste and text
extraction reveal nothing in the area;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.
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.
Optionalpages: number[]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).
Extract the given 1-based page numbers into a NEW standalone PDF.
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.
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).
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.
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).
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.
A page's /UserUnit (ISO 32000-1 §14.11.2), defaulting to 1.0 when absent.
Returns null on engine error (bad page number).
Insert a blank page after the 1-based after page (0 = front); returns its id.
Duplicate a page, inserting the copy right after it; returns the new page's id.
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).
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.
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.
A page's margins (points): the gap between /CropBox and /MediaBox when a
CropBox exists, else estimated from the content bounding box.
Set a page's margins (points) by insetting its /CropBox from the /MediaBox
— a real, visible margin change. Returns true on success.
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.
The document's GigaPDF editor-metadata sidecar string (set by
setEditorMeta), or null when the document carries none.
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.
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.
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.
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.
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.
// 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).
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.
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.
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.
Bake a running header onto every in-range page (idempotent: re-baking
replaces the prior header). Returns true on success.
Bake a running footer onto every in-range page (idempotent).
Remove every previously-baked running header from all pages.
Remove every previously-baked running footer from all pages.
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).
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.
Optionalopts: {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]]) }
);
The rich RunningHeaderFooter definition recorded by
setRunningHeaderFooter (read from the editor-meta sidecar — the
source of truth), or a minimal one reconstructed from a legacy flat
setHeader/setFooter bake, or null when neither is present.
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.
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.
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.
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.
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).
Optionalopts: { underline?: boolean; strikethrough?: 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).
Optionalopts: { underline?: boolean; strikethrough?: 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.
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.
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.
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.
Reconstruct this PDF into the unified editable model — the format-neutral GigaDocument tree (sections → pages → blocks → runs) that every format lowers into. Edit it with GigaPdfEngine.applyModelOps, then export it to any target with GigaPdfEngine.modelToDocx / GigaPdfEngine.modelToPdf / … — the foundation for editing any document indifferently of its source format.
Convert to an editable OpenDocument Presentation (.odp).
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.
Author a tagged (accessible) PDF — a /StructTreeRoot logical-structure
tree (P/H1–H6/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.
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.
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.
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.
OptionalownerPassword?: stringOptionalalgorithm?: "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?: numberRaw signed 32-bit /P bitmask. Use flags (above) for a readable API.
Defaults to all permissions granted when neither is given.
OptionalkeySeed?: Uint8Array<ArrayBufferLike>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).
Strip encryption from an already-opened (decrypted) document, returning a plaintext PDF. The document must have been opened with a valid password.
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.
Self-signed digital signature. random ≥ 256 bytes from crypto.getRandomValues.
Certify the document (DocMDP) — like sign but also declares which
later changes are allowed: docmdpLevel is 1 (no changes), 2 (form-fill
3 (also annotate). fields is the same tab-separated string as
sign (name⇥reason⇥date⇥notBefore⇥notAfter).List every signature on the document (each /Sig field's /V) with its
metadata and /ByteRange. For cryptographic validity call
verifySignatures.
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.
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.
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).
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).
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.
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.
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.
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.
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.
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.
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.
Freehand ink annotation from one polyline (points = flat [x0,y0,x1,y1,…]).
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.
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.
Add a /PolyLine annotation — an open path through points (a flat
[x0, y0, x1, y1, …] array). rgb is packed 0xRRGGBB.
Add a /Caret annotation — a small upward wedge in [x0,y0,x1,y1] marking
an insertion point. rgb is packed 0xRRGGBB.
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).
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).
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.
Register a named destination name → targetPage (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.
The catalog's named destinations as {name, page} pairs.
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()).
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).
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.
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.
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).
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.
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).
Every document-level JavaScript as { name, script } pairs, in name
(lexical) order — the read side of addDocumentJavascript (decodes
both a literal /JS string and a /JS stream).
Remove the document-level JavaScript named name from /Names /JavaScript.
Returns true if one was removed, false if none had that name.
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).
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.
Create a new (visible, unlocked) layer; returns its id (0 on error).
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).
End the innermost optional-content sequence on page (EMC).
Replace the outline. Each entry: {level, page?, title} (page 0/undefined = no dest).
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).
Remove the linkIndex-th /Link annotation on page (links counted in
order, ignoring non-link annotations). Returns true if one was removed.
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.
Set the catalog /PageLayout. null removes the key. Returns false on an unknown name.
Set the catalog /PageMode. null removes the key. Returns false on an unknown name.
Set a choice field's selection (multi-select list boxes accept several values).
Create a text field on page covering rect = [x0, y0, x1, y1] (PDF
user space). Options: maxLen character cap, multiline, password,
and visual style.
Create a checkbox. export is the on-state name (default On).
Create a radio-button group: one logical field whose options are the
individual buttons. selected is the initially-chosen export value.
Create a drop-down combo box. editable permits values outside options.
Create a scrolling list box. multi allows selecting several options.
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.
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.
Set the AcroForm calculation order (/CO) — the sequence in which fields
with a calculate script recompute. Unknown names are skipped.
Delete a form field by name (removed from /Fields, /CO and every page's
annotations). Returns true if a field was removed.
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).
A live document handle. Call close when done.