Class: PdfDocument
sempdf / PdfDocument
Defined in: src/document.ts:5969
A mutable builder for creating new PDF documents from scratch. It manages pages, fonts, metadata, outlines, attachments, accessibility data, encryption, and serialization.
Constructors
Constructor
new PdfDocument(options?): PdfDocument;Defined in: src/document.ts:6082
Creates a new mutable PDF document builder.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | DocumentOptions | Options that control the operation. |
Returns
PdfDocument
Properties
| Property | Type | Default value | Description | Defined in |
|---|---|---|---|---|
_debugThreadSafe | boolean | false | When true, warns about potential concurrent access on reentrant calls. | src/document.ts:6075 |
_lockLevel | number | 0 | Reentrant call counter for thread-safety debugging. | src/document.ts:6072 |
Accessors
pageCount
Get Signature
get pageCount(): number;Defined in: src/document.ts:6207
The number of pages currently in the document.
Returns
number
remainingPages
Get Signature
get remainingPages(): number;Defined in: src/document.ts:7107
Returns the number of pages that have been added but not yet written via writeNextPage.
Returns
number
Methods
addNamedDestination()
addNamedDestination(name, target): void;Defined in: src/document.ts:6454
Adds a named destination that points to a page.
Parameters
| Parameter | Type | Description |
|---|---|---|
name | string | The name to assign or look up. |
target | PdfPage | The destination page, outline target, or structure element. |
Returns
void
addOutline()
addOutline(
title,
target,
options?): PdfOutlineItem;Defined in: src/document.ts:6544
Adds a top-level outline item to the document.
Parameters
| Parameter | Type | Description |
|---|---|---|
title | string | The outline title. |
target | string | PdfPage | The destination page, outline target, or structure element. |
options | OutlineOptions | Options that control the operation. |
Returns
The created outline item handle.
addPage()
addPage(options?): PdfPage;Defined in: src/document.ts:6193
Adds a page to the document and returns its page builder.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | PageOptions | Options that control the operation. |
Returns
The new page builder.
attachFile()
attachFile(
name,
data,
options?): void;Defined in: src/document.ts:6483
Embeds a file attachment in the document.
Parameters
| Parameter | Type | Description |
|---|---|---|
name | string | The name to assign or look up. |
data | BinaryData | The binary image or font data. |
options | AttachmentOptions | Options that control the operation. |
Returns
void
clone()
clone(): PdfDocument;Defined in: src/document.ts:6918
Creates a deep clone of this document. The clone is independently modifiable — it copies all pages, fonts, images, metadata, and the structure tree. Embedded font data is reused from the shared font cache (cross-document sharing).
Returns
PdfDocument
A new PdfDocument instance with a deep copy of the document model.
createLuminositySoftMask()
createLuminositySoftMask(options, build): SoftMaskHandle;Defined in: src/document.ts:6343
Creates a luminosity soft mask backed by a Form XObject. Pass the returned handle to ExtGStateOptions.softMask via PdfPage.setExtGState to apply the mask.
The mask sub-builder supports path operations only. Painted regions with high luminosity (white) become opaque; black becomes transparent.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | SoftMaskOptions | Mask BBox dimensions. |
build | (mask) => void | Callback that receives the mask sub-builder. |
Returns
A handle referencing the created soft-mask Form XObject.
embedTrueTypeFont()
embedTrueTypeFont(data, options?): PdfEmbeddedFont;Defined in: src/document.ts:6430
Embeds a TrueType font and registers it under the provided name.
Parameters
| Parameter | Type | Description |
|---|---|---|
data | BinaryData | The binary image or font data. |
options | EmbedTrueTypeFontOptions | Options that control the operation. |
Returns
The result of the operation.
encryptForRecipients()
encryptForRecipients(certificates): void;Defined in: src/document.ts:7013
Configures certificate-based (public-key) encryption for the document. Each recipient certificate is a DER-encoded X.509 certificate whose public key is used to encrypt a random 20-byte seed. The /SubFilter /adbe.pkcs7.s5 security handler stores the encrypted seeds in a /Recipients array so each recipient can decrypt the document with their private key.
For simplicity this method only implements encryption — existing encrypted files are not decrypted.
Parameters
| Parameter | Type | Description |
|---|---|---|
certificates | Uint8Array<ArrayBufferLike>[] | An array of DER-encoded X.509 certificate bytes. |
Returns
void
flattenForms()
flattenForms(): void;Defined in: src/document.ts:6573
Flattens form fields into static page content where possible.
Returns
void
fonts()
fonts(configuration): Promise<ConfiguredFonts>;Defined in: src/document.ts:6179
Loads and configures document fonts through the high-level font API.
Parameters
| Parameter | Type |
|---|---|
configuration | FontConfiguration |
Returns
Promise<ConfiguredFonts>
Example
const doc = createDocument();
await doc.fonts(liberation);
doc.addPage().text("Typography · café — ✓", { x: 56, y: 760 });getPage()
getPage(index, origin?): PdfPage;Defined in: src/document.ts:6221
Returns a PdfPage builder for an existing page, so already-created
pages (for example those produced by renderTemplate) can be drawn on with
the absolute coordinate APIs.
Parameters
| Parameter | Type | Default value | Description |
|---|---|---|---|
index | number | undefined | Zero-based page index. |
origin | "top-left" | "bottom-left" | "bottom-left" | Coordinate origin for the returned builder. Defaults to "bottom-left". |
Returns
A page builder writing into the existing page.
measureRichText()
measureRichText(runs, options): BlockTextMetrics;Defined in: src/document.ts:6318
Measures a paragraph of inline rich-text runs without drawing it.
Parameters
| Parameter | Type | Description |
|---|---|---|
runs | readonly InlineTextRun[] | The styled inline runs. |
options | MeasureRichTextOptions | Block options including width (no position needed). |
Returns
The measured block metrics in PDF points.
measureText()
measureText(text, options?): TextMetrics;Defined in: src/document.ts:6283
Measures a single line of text without drawing it, using the document's registered fonts and defaults. Returns the rendered width and the line height (font size). For wrapped multi-line text use measureTextBlock.
Parameters
| Parameter | Type | Description |
|---|---|---|
text | string | The text to measure (treated as a single line). |
options | MeasureTextOptions | Font and style options (no position needed). |
Returns
The measured width and height in PDF points.
measureTextBlock()
measureTextBlock(text, options): BlockTextMetrics;Defined in: src/document.ts:6298
Measures a wrapped text block without drawing it. Returns the width of the longest line, the total height, and the line count after wrapping.
Parameters
| Parameter | Type | Description |
|---|---|---|
text | string | The text to wrap and measure. |
options | MeasureTextBlockOptions | Block options including width (no position needed). |
Returns
The measured block metrics in PDF points.
registerFontFamily()
registerFontFamily(name, faces): string;Defined in: src/document.ts:6256
Registers a named font family so text APIs can select a face with the
bold and italic flags instead of tracking individual font handles.
Faces may be built-in FontNames or handles returned by
embedTrueTypeFont. Pass the family name as the font option on
subsequent PdfPage.text/PdfPage.textBlock calls.
Parameters
| Parameter | Type | Description |
|---|---|---|
name | string | The family name used as the font option. |
faces | FontFamilyInput | The faces that make up the family. |
Returns
string
The family name, for convenient inline use as a font value.
Example
const inter = doc.registerFontFamily("Inter", {
regular: doc.embedTrueTypeFont(regularBytes, { family: "Inter" }),
bold: doc.embedTrueTypeFont(boldBytes, { family: "Inter" }),
});
page.text("Heading", { x: 56, y: 760, font: inter, bold: true });renderTemplate()
renderTemplate(options): void;Defined in: src/document.ts:6377
Renders a template document into this PDF document.
Use the fonts option to register embedded font families before
rendering so they are available by name in template blocks and styles:
doc.renderTemplate({
blocks: [ ... ],
fonts: {
Inter: {
regular: interRegularBytes,
bold: interBoldBytes,
}
}
});Parameters
| Parameter | Type | Description |
|---|---|---|
options | TemplateDocumentOptions | Options that control the operation. |
Returns
void
save()
save(path): Promise<void>;Defined in: src/document.ts:7080
Serializes the document and writes it to a file path. Convenience alias for writeToFile for Node.js callers. In the browser, use toUint8Array or toBlob instead.
Parameters
| Parameter | Type | Description |
|---|---|---|
path | string | The file path to write to. |
Returns
Promise<void>
setCalculationOrder()
setCalculationOrder(fieldNames): void;Defined in: src/document.ts:6561
Sets the calculation order for form fields. The order determines the sequence in which field calculations run when a field value changes.
Parameters
| Parameter | Type | Description |
|---|---|---|
fieldNames | string[] | The ordered list of form field names. |
Returns
void
setPageLabel()
setPageLabel(target, options): void;Defined in: src/document.ts:6468
Sets the label style for a page-label range beginning at the target page.
Parameters
| Parameter | Type | Description |
|---|---|---|
target | PdfPage | The destination page, outline target, or structure element. |
options | PageLabelOptions | Options that control the operation. |
Returns
void
setTextDefaults()
setTextDefaults(defaults): void;Defined in: src/document.ts:6163
Updates the document-wide text defaults. Existing page builders observe the update as well, so fonts can be loaded asynchronously after creating the document but before drawing text.
Parameters
| Parameter | Type |
|---|---|
defaults | TextDefaults |
Returns
void
setTextShaper()
setTextShaper(shaper): void;Defined in: src/document.ts:6153
Sets a custom text shaper for complex script shaping (Devanagari, Khmer, Myanmar, Arabic, Thai, etc.). When provided, the shaper is called for each text run that requires shaping. If not provided, the default shaper handles basic ligature and joining-form substitution but will throw an UNSUPPORTED_SCRIPT error for scripts it does not support. External shapers such as harfbuzzjs or fontkit can be plugged in to enable full shaping support.
Parameters
| Parameter | Type | Description |
|---|---|---|
shaper | TextShaper | undefined | The custom text shaper to use, or undefined to revert to the default. |
Returns
void
Example
import { createDocument } from "@crstnmac/sempdf";
const doc = createDocument();
// Plug in harfbuzzjs for full complex-script shaping:
// import { createHarfBuzzShaper } from "harfbuzzjs-shaper";
// doc.setTextShaper(createHarfBuzzShaper(harfbuzzInstance));setXmpMetadata()
setXmpMetadata(metadata): void;Defined in: src/document.ts:6530
Sets or clears the document XMP metadata packet.
Parameters
| Parameter | Type | Description |
|---|---|---|
metadata | XmpMetadataInput | undefined | The XMP metadata input, or undefined to clear it. |
Returns
void
toArrayBuffer()
toArrayBuffer(): ArrayBuffer;Defined in: src/document.ts:6665
Serializes the document into an ArrayBuffer.
Returns
ArrayBuffer
The serialized PDF data as an ArrayBuffer.
toArrayBufferAsync()
toArrayBufferAsync(): Promise<ArrayBuffer>;Defined in: src/document.ts:6732
Async counterpart to toArrayBuffer.
Returns
Promise<ArrayBuffer>
The serialized PDF data as an ArrayBuffer.
toBlob()
toBlob(): Blob;Defined in: src/document.ts:6701
Serializes the document into a PDF Blob.
Returns
Blob
The serialized PDF data as a Blob.
toBlobAsync()
toBlobAsync(): Promise<Blob>;Defined in: src/document.ts:6741
Async counterpart to toBlob.
Returns
Promise<Blob>
The serialized PDF data as a Blob.
toModel()
toModel(): PdfDocumentModel;Defined in: src/document.ts:6758
Returns the internal document model used by the serializer.
Returns
PdfDocumentModel
The internal document model.
toUint8Array()
toUint8Array(): Uint8Array;Defined in: src/document.ts:6600
Serializes the document into PDF bytes.
Returns
Uint8Array
The serialized or collected bytes.
toUint8ArrayAsync()
toUint8ArrayAsync(): Promise<Uint8Array<ArrayBufferLike>>;Defined in: src/document.ts:7069
Async counterpart to toUint8Array.
Returns
Promise<Uint8Array<ArrayBufferLike>>
The serialized PDF data as a Uint8Array.
validateCompliance()
validateCompliance(): readonly PdfComplianceIssue[];Defined in: src/document.ts:6583
Validates the current document model against enabled compliance rules.
Returns
readonly PdfComplianceIssue[]
The compliance issues found in the current model.
writeNextPage()
writeNextPage(sink): Promise<PdfPage>;Defined in: src/document.ts:7094
Writes all previously added pages to the sink and returns a new PdfPage for the next page. When called repeatedly this streams pages as they are built, reducing peak memory for very large documents (1000+ pages).
Parameters
| Parameter | Type | Description |
|---|---|---|
sink | ByteSink | The sink that receives the serialized bytes. |
Returns
Promise<PdfPage>
A new page builder for continuing to add pages.
writeTo()
writeTo(sink): Promise<void>;Defined in: src/document.ts:6633
Streams the serialized document to a byte sink.
Parameters
| Parameter | Type | Description |
|---|---|---|
sink | ByteSink | The sink that receives written byte chunks. |
Returns
Promise<void>
writeToFile()
writeToFile(path): Promise<void>;Defined in: src/document.ts:7060
Serializes the document and writes it to a file path.
Parameters
| Parameter | Type | Description |
|---|---|---|
path | string | The file path to write to. |
Returns
Promise<void>
estimateSignatureSize()
static estimateSignatureSize(certificateBytes?): number;Defined in: src/document.ts:7051
Estimates the byte size needed for a detached-signature placeholder.
Parameters
| Parameter | Type | Description |
|---|---|---|
certificateBytes? | Uint8Array<ArrayBufferLike> | null | Optional certificate bytes for size estimation. |
Returns
number
The estimated placeholder size in bytes.