Document

Overview

Document is a class in Aspose.PDF FOSS for TypeScript.

This class declares 109 methods for Document objects in TypeScript programs. Available methods include: AddAttachment, AddBatesNumbering, AddDocumentTimestamp, AddFont, AddFontFile, AddHeaderFooter, AddImagePages, AddMarkdown, AddPage, AddValidationData, AddWatermark, Append, and 95 additional methods. All public members are accessible to any TypeScript application after installing the Aspose.PDF FOSS for TypeScript package. Properties: DisplayDocTitle, DocumentTimestamps, Form, IsLinearized, IsTagged, Lang, and 16 more.

Properties

NameTypeAccessDescription
Pages: Page[]ReadOne Page per page, in document order.
dir: stringReadGets the dir.
sniff: booleanReadGets the sniff.
PermissionsPermissions | undefinedReadGets the permissions.
recovery: RecoveryReportRead/WriteSet when Open had to recover from a damaged cross-reference structure; undefined after a clean parse.
num: numberReadGets the num.
dict: PdfDictReadGets the dict.
offset: numberReadGets the offset.
FormFormReadGets the form.
OptionalContentOptionalContentReadGets the optional content.
IsTaggedbooleanReadGets the is tagged.
IsLinearizedbooleanReadGets the is linearized.
Langstring | undefinedRead/WriteGets the lang.
DisplayDocTitlebooleanRead/WriteGets the display doc title.
sniff: booleanReadGets the sniff.
SignaturesSignatureField[]ReadGets the signatures.
DocumentTimestampsSignatureField[]ReadGets the document timestamps.
page: PageReadGets the page.
number: numberReadGets the number.
page: PageReadGets the page.
number: numberReadGets the number.
title: stringReadDocument title.
pages: Page[]ReadGets the pages.
skipped: string[]ReadGets the skipped.
uncolored: falseReadGets the uncolored.
uncolored: trueReadGets the uncolored.

Methods

SignatureDescription
GetTables(options: TableExtractOptions & TableStitchOptions)Table[]Extract tables from every page and stitch continuations across page boundaries into single logical tables.
New(format: PageFormat)DocumentCreate a new document from scratch: zero pages when format is omitted, or one blank page of that size when given.
Split(options: SplitOptions)Document[]Split into one new single-page Document per page, in page order.
ExtractPages(numbers: number[], options: ExtractPagesOptions)DocumentCopy the given 1-based pages into a new self-contained Document, in the order given (repeats allowed, like Reorder).
Reorder(order: number[])Rearrange pages: new page i = old page order[i-1] (1-based).
Open(buf: Uint8Array, opts: OpenOptions)DocumentCalls Open(buf, opts) on this Document instance.
OpenFile(fileName: string, opts: OpenOptions)DocumentOpen a PDF from a file path (synchronous), delegating to Open.
resolve(o: PdfObject | undefined)PdfObjectResolve a value: if it’s a ref, fetch the object; otherwise return as-is.
catalog()PdfDictCalls catalog on this Document instance.
allocObject(obj: PdfObject)PdfRef@internal Allocate a fresh indirect object, returning its ref.
replaceObject(num: number, obj: PdfObject)@internal Replace the object stored at num in place, so every existing indirect reference to it sees the new value (used to rewrite a shared stream — whose raw is immutable — without repointing each referrer).
deleteObject(num: number)@internal Delete an indirect object from the live map.
markModified()@internal Record that the in-memory model has diverged from originalBytes, so the next signature must be a full rewrite, and invalidate any cached signed output.
ExportFdf(opts: ExportFormDataOptions)Uint8ArrayExport the current form-field values as an FDF data file.
ExportXfdf(opts: ExportFormDataOptions)Uint8ArrayExport the current form-field values as an XFDF data file.
ImportFdf(bytes: Uint8Array, opts: ImportOptions)ImportReportImport field values from an FDF data file.
ImportXfdf(bytes: Uint8Array, opts: ImportOptions)ImportReportImport field values from an XFDF data file.
GetMetadata()MetadataCalls GetMetadata on this Document instance.
GetXmp()XmpMetadataThe document-level XMP packet at /Root /Metadata as structured data; an empty object when there is no metadata stream.
ToMarkdown(options: MarkdownExportOptions)stringRender every page to one Markdown document.
ToMarkdownAssets(options: MarkdownExportOptions)MarkdownExportResultRender every page to Markdown plus the image files it references.
ToHtml(options: HtmlOptions)stringRender every page to one standalone HTML document.
ToDocx(options: DocxOptions)Uint8ArrayRender every page to a .docx (Office Open XML).
ToEpub(options: EpubOptions)Uint8ArrayRender every page to one EPUB 3 archive.
ToTiff(options: TiffExportOptions)Uint8ArrayRasterize a page selection into ONE multi-page TIFF.
AddImagePages(data: Uint8Array, options: AddImagePagesOptions)AddImagePagesResultAppend one page per frame of an image file, sized to each frame.
GetStructTree()StructTreeRoot | nullThe document’s logical structure tree, or null when untagged.
ValidatePdfUa()ValidationReportValidate the document against a curated, machine-checkable subset of PDF/UA-1 (ISO 14289-1) rules.
ValidatePdfA(level: PdfALevel)ValidationReportValidate the document against a curated, machine-decidable subset of PDF/A (ISO 19005, parts 1-3, levels b/u/a).
ValidatePdfX(level: PdfXLevel)ValidationReportValidate the document against a curated, machine-decidable subset of PDF/X (ISO 15930, levels 1a/3/4/4p).
ConvertToPdfA(level: PdfALevel, opts: ConvertOptions)ConversionReportRemediate the document toward PDF/A level (b/u), then re-validate.
ConvertToPdfX(level: PdfXLevel, opts: PdfXConvertOptions)ConversionReportRemediate the document toward PDF/X level, then re-validate.
ConvertToPdfUa(opts: PdfUaConvertOptions)ConversionReportRemediate the document toward PDF/UA-1 (mechanical fixes only), then re-validate.
objectEntries()Generator<[PdfRef, PdfObject]>@internal Every indirect object with a gen-0 ref.
headerVersion()string | undefined@internal The effective PDF version: catalog /Version when present, else the %PDF-x.y header from the opened bytes, else undefined (in-memory).
CreateStructTree()StructTreeRootBuild (or return the existing) document structure tree, marking the document Tagged (/MarkInfo /Marked true).
AutoTag(opts: AutoTagOptions)AutoTagReportInfer and author a /StructTreeRoot from page layout (headings by font-size clustering, paragraphs, and — with opts.alt — figures).
pageForRef(r: PdfRef)Page | undefined@internal Map a page object ref to its Page handle, or undefined.
pageNumberOf(o: PdfObject)number | undefined@internal Resolve a destination’s page object to its 1-based page number, or undefined.
GetOutlines()OutlineItem[]The document outline (bookmark) tree; [] when there is no /Outlines.
pageRef(page: number)PdfRef@internal The indirect ref for a 1-based page number; throws when that page is not an indirect object.
SetOutlines(items: OutlineItem[])Replace the document outline with items; an empty array removes it.
GetPageLabels()PageLabel[]The logical page-label ranges from /Root /PageLabels, ascending; [] when there is no /PageLabels.
SetPageLabels(labels: PageLabel[])Replace /Root /PageLabels with labels; an empty array removes it.
PageLabelFor(pageIndex: number)stringResolve a 0-based page index to its rendered label (prefix + numeral).
GetNamedDestinations()NamedDestination[]All named destinations, merging the /Names /Dests name tree and the legacy /Dests dict (legacy wins on a clash), sorted by name.
SetNamedDestination(name: string, dest: PageDest)Upsert namedest into the /Names /Dests name tree (creating the containers as needed), writing a single flat node — no balanced-tree rebalancing.
RemoveNamedDestination(name: string)Remove name from both the name tree and the legacy /Dests dict, pruning the now-empty containers.
GetOpenAction()OpenAction | undefinedWhat this document does when it is opened: go to a view (kind: 'dest') or run an action (kind: 'action').
SetOpenDestination(dest: PageDest)Open the document at dest, written as a destination.
SetOpenAction(action: PdfAction)Run action when the document is opened, written as an action dict.
RemoveOpenAction()Remove the catalog /OpenAction.
GetJavaScripts()DocumentJavaScript[]Document-level JavaScript: every entry of the /Names /JavaScript tree, sorted by name.
SetJavaScript(name: string, script: string)Upsert a document-level script, run by the viewer when the document opens.
RemoveJavaScript(name: string)booleanRemove a document-level script.
GetAttachments()Attachment[]All document-level embedded files (the /Names /EmbeddedFiles tree), sorted by name.
AddAttachment(name: string, bytes: Uint8Array, opts: AttachmentOptions)AttachmentEmbed bytes as an attachment named name, upserting it into the /Names /EmbeddedFiles name tree (overwriting a same-named entry).
RemoveAttachment(name: string)booleanRemove the named attachment from the name tree (and /AF).
GetCollection()CollectionSettings | undefinedThe /Root /Collection portfolio presentation settings, or undefined.
SetCollection(settings: CollectionSettings)Write (or replace) the /Root /Collection portfolio settings.
RemoveCollection()booleanRemove /Root /Collection.
ensureInfo()PdfDict@internal The /Info dictionary, created and linked from the trailer when absent.
SetMetadata(update: MetadataUpdate)Calls SetMetadata(update) on this Document instance.
SetXmp(update: XmpUpdate)Set/replace the document XMP packet from update (merged over the current packet; null deletes a field), mirroring shared fields back into /Info.
ClearMetadata()Remove all document metadata: drop the /Info dictionary and the catalog’s /Root /Metadata XMP packet, so /Info and XMP stay consistent (the mirror counterpart of SetMetadata <-> SetXmp).
Optimize(opts: OptimizeOptions)OptimizeReportLosslessly shrink the document in place: subset already-embedded fonts to the glyphs actually shown, merge byte-identical streams, and recompress stream payloads.
ConvertToGrayscale(opts: GrayscaleOptions)GrayscaleReportConvert the document’s colour to DeviceGray in place: page content, form XObjects, tiling patterns, Type 3 glyph procedures, image XObjects, shadings and annotations.
Save(options: SaveOptions)Uint8ArraySerialize the live document to PDF bytes (mark-sweep from /Root, renumbered).
AddFont(bytes: Uint8Array, opts: AddFontOptions)EmbeddedFontParse and register a font program (TrueType/OpenType sfnt bytes), returning a handle to pass as the font option to {@link Page.AddText} / {@link Page.AddTextBlock}.
AddFontFile(fileName: string, opts: AddFontOptions)EmbeddedFontRead a font program from disk (synchronous) and register it; the file path counterpart of {@link AddFont}, mirroring {@link WriteTo}.
RegisterFontFolder(dir: string, opts: { sniff?: boolean })Search dir, recursively, when resolving a font by name.
RegisterSystemFonts()Also search the platform’s own font directories.
ResolveFontByName(family: string | string[], opts: LoadFontOptions)FontMatch | undefinedWhat family resolves to, without loading or embedding anything.
LoadFontByName(family: string | string[], opts: LoadFontOptions)EmbeddedFont | undefinedThe face matching family, registered and ready to draw with.
LoadFontFamily(family: string | string[], opts: AddFontOptions)FontFamily | undefinedThe four faces of family, ready to hand to AddMarkdown({ style: { font } }).
Sign(signer: Signer, opts: SignOptions)Promise<void>Add an (invisible) digital signature.
Certify(signer: Signer, opts: CertifyOptions)Promise<void>Add a certification (author) signature with a DocMDP transform: the signature carries a /Reference DocMDP entry and the catalog gains /Perms /DocMDP pointing at it, declaring which later changes are permitted (opts.permissions, default no-changes).
AddValidationData(opts: ValidationDataOptions)Promise<void>Embed long-term-validation (LTV) data in a /DSS (PAdES-B-LT): for each existing signature, store its certificate chain plus the OCSP/CRL bytes returned by the opts.getOCSP/opts.getCRL callbacks, indexed by a /VRI entry, and append the store as an incremental update (existing signatures preserved verbatim).
AddDocumentTimestamp(tsa: TimestampProvider, opts: DocumentTimestampOptions)Promise<void>Append a document timestamp (/DocTimeStamp, ETSI.RFC3161) as an incremental update, enabling PAdES-B-LTA archival on top of B-LT.
VerifySignatures(opts: VerifyOptions)Promise<SignatureReport[]>Verify every signature in the document: recompute each /ByteRange digest, verify the detached CMS, and diff what changed after each signature.
VerifyDocumentTimestamps()Promise<DocumentTimestampReport[]>Verify every document timestamp (/DocTimeStamp) in the document: check each token’s message-imprint binding to the /ByteRange and the TSA’s CMS signature, returning one {@link DocumentTimestampReport} per field.
WriteTo(fileName: string, options: SaveOptions)Serialize and write to a file path (synchronous), mirroring OpenFile.
getObject(num: number)PdfObjectCalls getObject(num) on this Document instance.
InsertPage(at: number, source: Page | PageFormat){ page: Page; number: number }Insert a page so it becomes 1-based page at (1..Pages.length+1): a blank page (of source when it is a {@link PageFormat}, else {@link PageFormat.A4}), or a deep copy of source when it is a {@link Page} (from this or another Document, keeping that page’s own size).
AddPage(source: Page | PageFormat){ page: Page; number: number }Append a page: a blank page (of source when it is a {@link PageFormat}, else {@link PageFormat.A4}), or a deep copy of source when it is a {@link Page}.
NewFlow(options: FlowOptions)FlowCreate a {@link Flow} layout container bound to this document.
`AddMarkdown(src: string | MdDocument, options: MarkdownFlowOptions & FlowOptions & {
/** Document title. Non-empty. Default: the document’s title is untouched. */
title?: string;
}){ pages: Page[]; skipped: string[] }`Render a whole Markdown document, appending freshly sized pages to the end of this document.
NewFloatingBox(options: FloatBoxOptions)FloatingBoxCreate a {@link FloatingBox} bound to this document.
NewTilingPattern(width: number, height: number, draw: (g: VectorGraphics) => void, opts: TilingPatternOptions & { uncolored?: false })ColoredTilingPatternCreate a reusable tiling pattern (PDF PatternType 1): draw paints one tile into a builder scoped to tile space, and the pattern repeats on an xStep x yStep lattice wherever it is used.
NewTilingPattern(width: number, height: number, draw: (g: VectorGraphics) => void, opts: TilingPatternOptions & { uncolored: true })UncoloredTilingPatternCalls NewTilingPattern(width, height, draw, opts) on this Document instance.
NewTilingPattern(width: number, height: number, draw: (g: VectorGraphics) => void, opts: TilingPatternOptions)TilingPatternCalls NewTilingPattern(width, height, draw, opts) on this Document instance.
NewTemplate(width: number, height: number)TemplateCreate a reusable template: a Form XObject you draw once and place on any number of pages, allocated as a single object however often it is used.
InsertPages(at: number, other: Document, options: InsertPagesOptions)number[]Insert every page of other so the first becomes 1-based page at (1..Pages.length+1), shifting existing pages down.
Append(other: Document, options: InsertPagesOptions)number[]Append every page of other to the end of this document.
Merge()DocumentBuild a new document from copies of all docs, in order.
Redact(page: number, rects: Rect[], opts: RedactOptions)Redact regions on a single page (1-based page number); see Page.Redact.
RedactText(find: string | RegExp, opts: RedactOptions)numberRedact every occurrence of find across all pages; see Page.RedactText.
MarkRedactText(find: string | RegExp, opts: MarkRedactTextOptions)numberMark every occurrence of find across all pages; see Page.MarkRedactText.
ApplyRedactions(opts: ApplyRedactionsOptions)numberApply every /Redact mark across all pages; see Page.ApplyRedactions.
ReplaceText(find: string | RegExp, replacement: string)numberReplace every occurrence of find with replacement across all pages; see Page.ReplaceText.
Overlay(src: Page | Document, opts: OverlayOptions)Stamp a single source page onto many pages of this document as one shared Form XObject — letterheads, watermarks, backgrounds.
AddWatermark(opts: WatermarkOptions)Stamp a repeating text or image watermark across a page range.
AddHeaderFooter(opts: HeaderFooterOptions)Stamp header and/or footer text across a page range.
AddBatesNumbering(opts: BatesOptions)numberStamp a Bates sequence across a page range (bottom-right, {bates}, 10pt by default).
NUp(cols: number, rows: number, opts: NUpOptions)DocumentImpose this document’s pages cols×rows per sheet into a new Document (this one is unmodified, like Split/ExtractPages).
Booklet(opts: BookletOptions)DocumentImpose this document’s pages as a saddle-stitch booklet into a new Document (this one is unmodified, like NUp/Split/ExtractPages).
FlattenAnnotations()numberFlatten annotations on every page into static page content; see Page.FlattenAnnotations.
FlattenForm()numberFlatten the interactive form into static page content: generate every field’s appearance, bake each widget into its page at its /Rect, then drop the document /AcroForm.
RemovePage(target: number | Page)Calls RemovePage(target) on this Document instance.