ReadonlypermissionsEncryption/permission info, or null if the document is not encrypted.
ReadonlysourceIdentifier of the document's source (e.g. uri%... or data%...); used in error messages.
Whether page, outline, or link edits are waiting to be materialized.
Whether dispose has been called; further operations reject.
Whether the document is encrypted (equivalently, permissions is non-null).
Pages of the document. With progressive loading, unloaded pages have isLoaded === false.
Subscribes to a document event (see PdfDocumentEventMap) and returns an unsubscribe function.
For missingFonts, queries already discovered while the document was
opening are replayed to the new listener on a microtask, so late
subscribers do not miss them.
The event name to subscribe to.
The callback to invoke when the value changes.
A function that removes the listener.
Routes a cross-page synchronization batch to its arrangement pages and
emits one annotationsChanged event after the applied operations. This is
a notification batch, not a rollback transaction: a later failure can
leave earlier PDFium mutations applied. Use page methods for independent
local CRUD on one page.
The changes to apply.
Options that customize the operation.
The resulting Promise.
Creates an independent, fully materialized document from the current logical state. The caller owns the returned document and must dispose it.
Pending page, outline, and Link edits are applied to the returned document,
whose hasPendingChanges is therefore false. The source document
on which this method is called is not materialized or otherwise modified;
its pending state remains unchanged.
catalog: "preserve" chooses the sole imported source as its base when
possible and preserves that source's catalog. catalog: "rebuild" imports
the arranged pages into a new empty PDF and omits objects not reachable
from those pages, whether they originated in the source PDF or from
subsequent edits. Rebuilding does not inherit existing physical
document-level outlines, metadata, name trees, signatures, or AcroForm
configuration. Pending logical page, outline, and Link edits are still
applied to the returned document.
Options that customize the operation.
The resulting Promise.
Creates page objects from declarative path, text, and image content in one worker round trip. The returned pages are not added to the document's logical pages arrangement; pass the desired final array to setPages.
Coordinates and matrices use PDF page space: points, a bottom-left origin, and a y-axis pointing up. Fonts previously registered with PdfrxEngine.addFontData are embedded when a text run names their face. Image and emoji buffers are transferred to the worker and detached.
One or more complete page specifications.
Newly created, currently unplaced pages in specification order.
const document = await engine.createNew();
const pages = await document.createPagesFromContents([{
width: 595,
height: 842,
objects: [{
kind: 'text',
runs: [{ text: 'Quarterly report', fontFace: null, x: 48, y: 790, fontSize: 24 }],
}],
}]);
document.setPages(pages);
const pdfBytes = await document.encodePdf();
Existing arranged pages remain unchanged until setPages is called, so generated pages can be inserted, reordered, or discarded synchronously. Multiple calls may accumulate source pages before one final arrangement.
Creates one unplaced page per image in a single worker round trip. The returned pages do not change the document's logical pages arrangement; place them with setPages.
JPEG bytes are decoded natively by PDFium. Other encoded formats use the
supplied PdfCreatePagesFromImagesOptions.decode callback or the
runtime's createImageBitmap support. Page dimensions default to the image
pixel dimensions at 72 DPI and can be controlled with
PdfCreatePagesFromImagesOptions.dpi or
PdfCreatePagesFromImagesOptions.pageSize.
Images to turn into pages, in the returned page order.
Image decoding and page-sizing options.
Newly created, currently unplaced pages.
Closes the document and releases its native handles (and the form
environment). Idempotent; after disposal all page operations resolve to
null/empty or reject. Runs the onDispose hook supplied at open time.
The resulting Promise.
Builds and applies a batch of convenient raw PDF-object edits.
Raw targets and object numbers address the physical PDF object graph, not pending edits created by setPages, setPage, setOutline, or Link-annotation CRUD. Raw editing does not materialize those edits automatically. Call materialize explicitly before inspecting raw objects and constructing a related edit batch; otherwise the batch can target the old page tree, outline, annotations, or object numbers. Calling encodePdf first is also sufficient because it calls materialize.
The callback only records operations. If it throws or rejects, the worker is never called and the document is unchanged. By default, the completed batch is then applied directly in one worker command. This avoids copying the PDF, but it is not a rollback boundary: if PDFium applies some operations and a later operation fails, the earlier changes can remain.
Pass { atomic: true } for complete all-or-nothing behavior. That mode
applies the batch to an independent materialized copy and makes this
PdfDocument adopt the copy only after every operation succeeds. It keeps
the original native document on failure, at the cost of copying and
reloading the entire PDF (with time and peak-memory costs proportional to
document size).
Atomic success replaces the native document and reconstructs pages.
Existing PdfPage references continue to address the same page indices, but
callers should prefer reading document.pages again afterward.
Raw edits do not describe their GUI impact. A viewer displaying this
document must therefore be refreshed explicitly—for @pdfrx/viewer, use
PdfrxViewer.refreshPages(),
PdfrxViewer.refreshDocument(),
or
PdfrxViewer.reloadDocument()
according to the scope and whether PDFium itself must be reconstructed.
The edit value.
Options that customize the operation.
The resulting Promise.
await document.editRawObjects(
(editor) => {
const preferences = editor.createDictionary({
HideToolbar: { kind: 'boolean', value: true },
DisplayDocTitle: { kind: 'boolean', value: true },
});
editor.setDictionaryValue(
editor.catalog(),
'ViewerPreferences',
preferences.reference,
);
},
{ atomic: true },
);
// The engine cannot infer which viewer caches the raw edit affects.
await viewer.refreshDocument();
Serializes the current logical state to PDF bytes, including pending page, outline, and Link-annotation edits. In-place encoding writes them into this document with materialize first; copy and compact encoding materialize only a temporary document.
Options that customize the operation.
The resulting Promise.
Exports a versioned, structured-cloneable snapshot across the current
arrangement. This stays on PdfDocument because snapshots can span pages;
use PdfPage.loadAnnotations for a single-page read. A physical
source page placed more than once is exported once, using its first
arrangement page number, because all placements share the same stable ids
and annotation state.
The resulting Promise.
Reads the document catalog as a structured value.
Indirect references remain references, so cyclic PDF graphs are never expanded.
Stream data is decoded; set includeRawStreamData to also receive its encoded bytes.
This reads the physical PDF object graph in the worker, not pending logical
state created by setPages, setPage, setOutline, or
Link-annotation CRUD. When hasPendingChanges is true, call
materialize first (or use in-place encodePdf) before
interpreting affected page-tree dictionaries, page references, outlines,
annotations, or other catalog data.
Options that customize the operation.
The resolved Promise.
Returns the current value of the named field, or undefined if it is not found.
The name to look up.
The resolved Promise.
Reads one indirect PDF object as a structured value.
Indirect references remain references, so cyclic PDF graphs are never expanded.
Stream data is decoded; set includeRawStreamData to also receive its encoded bytes.
Object numbers and references belong to the physical PDF object graph in the worker. Pending edits from setPages, setPage, setOutline, or Link-annotation edits exist only in logical state and can disagree with that graph. Call materialize first (or use in-place encodePdf) before reading affected objects or retaining object numbers for later edits.
The object number.
Options that customize the operation.
The resolved Promise.
True if other is a PdfDocument backed by the same native handle.
Note this compares handles, not document contents.
The other value (unknown).
Whether the condition is satisfied.
Loads all content annotations (ink, shapes, text markup, notes, free text —
not widgets/links/popups) across the current page arrangement, including
imported pages. Each result is tagged with its 1-based arrangement
pageNumber. Use PdfPage.loadAnnotations when only one page is
needed. If the same physical source page is placed more than once, its
shared annotations appear once per placement. Returns [] for a disposed
document.
Options that customize the operation.
The resolved Promise.
Loads all AcroForm fields across the document's currently loaded pages, grouped by fully-qualified name (widgets that share a name — e.g. a radio group — merge into one field). Returns an empty array for documents without a form. Reflects live values, including ones changed by setFormFieldValue or interactive editing.
The resolved Promise.
Loads highlights across the current page arrangement. Use PdfPage.loadHighlights for one page. Each result includes its 1-based arrangement page number; imported and duplicate placements follow the same semantics as loadAnnotations.
Options that customize the operation.
The resolved Promise.
Loads the logical document outline as a tree of PdfOutlineNode. Returns the staged replacement when present; otherwise reads the physical PDF outline from the worker.
The resolved Promise.
Loads remaining pages in chunks of roughly loadUnitDurationMs worth of work.
onPageLoadProgress can return false to stop loading further pages.
OptionalonPageLoadProgress: (loadedPageCount: number, totalPageCount: number) => boolean | Promise<boolean>
The callback invoked when the corresponding event occurs.
The loadUnitDurationMs value (number).
The resolved Promise.
Writes every pending page, outline, and Link-annotation edit into the physical PDF. In-place encodePdf calls this automatically. createMaterializedCopy instead materializes only its returned independent document.
The resulting Promise.
Maps a zero-based physical page index in this document's native PDF to its
current 1-based position in pages, or returns null when that
physical page is not present.
"Source" here means the page owned by this document before the lightweight
arrangement in pages is applied. It is the same distinction exposed
by PdfPage.sourceDocument and the internal
PdfPage.sourcePageIndex: PDFium reports outlines, links, and form
notifications against the native PDF page tree, while setPages
creates a separate in-memory order of placement proxies.
This is how destinations from the PDF itself — outline entries and internal links, which PDFium reports as physical page indices — are translated into page numbers callers can navigate to after setPages.
Two caveats are inherent rather than fixable: a page placed twice can only
resolve to one position (the first wins), and a page removed from the
arrangement has no position at all, so destinations into it become null.
The 0-based physical page index.
The resulting number or null.
Turns the Unicode contents of a FreeText spec into a stable PDF
appearance. Call this after constructing the spec and before passing that
same object to PdfPage.addAnnotation or
PdfPage.updateAnnotation.
This step is necessary because a PDF cannot simply inherit browser text rendering. Han characters can require different glyphs for Japanese, Simplified Chinese, Traditional Chinese, and Korean, while modern color emoji must be rasterized and embedded as image runs. The method also measures the resolved fonts and wraps the text to the annotation rectangle.
The supplied spec is mutated in place: fontFace, appearanceLines, and
appearanceRuns are replaced.
language is optional. Kana and Hangul identify Japanese and Korean
without a hint, and a browser automatically contributes
navigator.languages / navigator.language. Pass an explicit BCP-47
value when Han-only text is ambiguous, when the document language should
override the browser locale, or when running on a server. Server
integrations commonly use document metadata, the signed-in user's
locale, or a parsed Accept-Language preference.
The spec value (PdfAnnotationSpec).
Options that customize the operation.
The resulting Promise.
const spec: PdfAnnotationSpec = {
subtype: 'freeText',
rect: { left: 40, bottom: 700, right: 260, top: 750 },
// Han-only text is ambiguous without a language or browser locale.
contents: '契約内容 😀',
fontSize: 14,
};
await document.prepareFreeTextAppearance(spec, { language: 'ja' });
await document.pages[0]!.addAnnotation(spec);
In a browser whose locale represents the intended reader, the explicit option can be omitted:
await document.prepareFreeTextAppearance(spec);
The default services work in browsers and server runtimes: browser-native
emoji is preferred, with a lazily downloaded, version-pinned Noto Emoji PNG
fallback. @pdfrx/viewer also supplies its browser font resolver and exact
Canvas measurement. Direct engine integrations can pass services for
private or offline fonts/assets, persistent server caches, or a different
text/emoji renderer.
If subtype is not freeText, or rect/contents is absent, the method
returns without changing the spec.
For runtime behavior and complete customization examples, read the Text, language, and emoji appearance guide. To turn the analyzed runs into ordinary PDF page text and images, see the practical multilingual Unicode page-content pipeline.
Reloads page metadata (e.g. after document modification).
OptionalpageNumbersToReload: number[]
The pageNumbersToReload value (number[]).
The resulting Promise.
Resolves a destination against the current arrangement. When an ID occurs more than once, one matching placement is selected; callers that need to distinguish repeated pages should use PdfPage.duplicate.
The dest value (PdfDest).
The resolved PdfResolvedDest or null.
Restores a document-wide snapshot while preserving ids and emitting one
annotationsChanged notification batch. The PDFium mutations are
sequential, not transactional: a later failure can leave earlier changes
applied.
The current immutable session snapshot.
Options that customize the operation.
The resulting Promise.
Sets the value of the field identified by fully-qualified name, routed
through the form-fill module so the widget appearance regenerates and the
change is visible on the next render. When formCalculationEnabled is
set (the default), dependent calculated fields (AFSimple_Calculate) are
recomputed afterwards. Fires one formFieldsChanged event using the
supplied mutation origin (api by default). The interpretation of value
depends on the field type — see PdfFormFieldValue.
The name to look up.
The value to use.
Options that customize the operation.
The resulting Promise.
Applies several field values as one form transaction, runs calculations
once, and emits one formFieldsChanged event containing the complete
direct + calculated before/after diff.
The values to use.
Options that customize the operation.
The resulting Promise.
Stages an immutable replacement for the document outline. No worker or PDF object mutation occurs until materialize or in-place encodePdf. createMaterializedCopy applies the staged outline only to the returned document and leaves this document pending.
The outline value.
Replaces a single slot (1-based), keeping every other page in place — the
common case for GUI editing (doc.setPage(3, doc.pages[2]!.rotatedCW90())).
Like setPages, this touches no PDF data.
Setting a page that is already present elsewhere reuses its logical identity, so ID-based destinations cannot distinguish the two placements. Use PdfPage.duplicate; see that method for examples and details.
The 1-based page number.
The page to process.
Options that customize the operation.
Replaces the page arrangement — the one way to reorder, rotate, remove, duplicate, and import pages, and the cheap, synchronous counterpart to materialize.
Nothing is sent to the worker and the PDF is not rebuilt: the pages are proxies (including those returned by PdfPage.rotatedTo) over pages that stay loaded, so reordering and rotating are immediate and free, and undo is just setting the previous array back. Page numbers are assigned automatically from the array order. This is what GUI page editing wants; call encodePdf (or materialize) when pending edits finally have to become a real PDF.
Pages may come from other documents — those must stay open for as long as they are referenced. Page numbers are reassigned to match the new order, so callers can pass pages in any arrangement.
Reusing the same PdfPage in more than one slot also reuses its logical identity, making ID-based destinations unable to distinguish those placements. Use PdfPage.duplicate when each occurrence must have its own destination identity; see that method for examples and details.
Fires pageStatusChanged for every slot.
The pages to process, in document order.
Options that customize the operation.
Whether setFormFieldValue recomputes dependent calculated fields (
AFSimple_Calculate) after a change. Defaulttrue.