Core API
Core API
This guide shows how to open, edit, assemble, and save PDF documents with the
Document and Page classes — the entry points for every operation in
Aspose.PDF FOSS for TypeScript. Document loads, creates, assembles, and
saves whole PDF files; Page, reached through doc.Pages, exposes
per-page text, image, annotation, and content-stream operations.
Document Lifecycle
Document.OpenFile() opens a PDF from a file path; Document.Open() accepts
an in-memory Uint8Array. Pages can be inspected and edited in place, and
Document.WriteTo() writes the result back out — optionally with
xref-stream and object-stream compression.
import { Document } from '@asposefoss/pdf';
// Open from disk (or Document.Open(uint8array) for in-memory data)
const doc = Document.OpenFile('input.pdf');
// Inspect and edit pages
const pages = doc.Pages;
console.log(pages.length);
pages[0].Rotate = 90;
doc.RemovePage(2); // 1-based page number
doc.Reorder([3, 1, 2]);
// Metadata
doc.SetMetadata({ title: 'Report', author: 'Jane', custom: { Dept: 'R&D' } });
// Save
doc.WriteTo('output.pdf'); // or: const bytes = doc.Save();
doc.WriteTo('small.pdf', { compressed: true }); // xref stream + object streams
Splitting, Merging, and Extracting Pages
Document.Split() returns one Document per page. Document.ExtractPages()
takes a 1-based, repeats-allowed page list and returns a new Document with
just those pages. Document.Append() and Document.InsertPage() copy pages
across documents, and Document.Merge() combines several documents into one.
const parts = doc.Split(); // one Document per page
const chapter = doc.ExtractPages([3, 4, 5]); // subset (1-based, repeats allowed) as a new Document
docA.Append(docB); // copy all of docB's pages onto docA
docA.InsertPage(1, docB.Pages[0]); // copy a single page across documents
Creating a New Document
Document.New() starts a blank document at a given PageFormat.
Page.AddText() places positioned text, and Document.AddPage() appends
further pages, including a rotated format such as PageFormat.A4.landscape().
import { Document, PageFormat } from '@asposefoss/pdf';
const doc = Document.New(PageFormat.A4); // one blank A4 page
doc.Pages[0].AddText('Hello', 72, 720, { fontSize: 14 });
doc.AddPage(PageFormat.A4.landscape()); // append more as you go
doc.WriteTo('scratch.pdf');Watermarks and Page Numbers
Page.AddText() also supports rotation, color, and opacity, which is enough
to render a page number and a diagonal watermark without any additional
classes.
const doc = Document.OpenFile('in.pdf');
const page = doc.Pages[0];
// Page number, right-aligned near the bottom-right corner.
const w = page.Rect[2] - page.Rect[0];
page.AddText(`Page ${page.Number}`, w - 40, 20, { fontSize: 10, align: 'right' });
// Semi-transparent diagonal watermark, centered on the page.
page.AddText('DRAFT', page.Rect[2] / 2, page.Rect[3] / 2, {
font: 'Times-Bold', fontSize: 64, color: [0.7, 0.7, 0.7], opacity: 0.4, rotate: 45, align: 'center',
});
doc.WriteTo('out.pdf');Content Stream Introspection
parseContentStream() decodes a page’s raw /Contents stream into a list of
operator/operand pairs, and serializeContentStream() converts an edited
operator list back into bytes.
import { parseContentStream, serializeContentStream } from '@asposefoss/pdf';
const ops = parseContentStream(doc.Pages[0].Contents);
// ops: { operator: string, operands: PdfObject[], inlineImage?: {...} }[]
for (const op of ops) {
if (op.operator === 'Tj') console.log('text op:', op.operands);
}
const bytes = serializeContentStream(ops); // round-trips operators + operands
Multi-Column Text Flow
Page.AddTextBlock() flows a long string of text into a rectangular region
and returns any text that did not fit, which can be fed into a second call
to continue the flow into another column.
const rest = page.AddTextBlock(longText, [72, 600, 200, 150], {
font: 'Times-Roman', fontSize: 11, align: 'justify', valign: 'top', leading: 14,
});
if (rest) page.AddTextBlock(rest, [300, 600, 200, 150]); // continue into a 2nd column
Tips and Best Practices
- Use
Document.OpenFile()for file paths andDocument.Open()for in-memoryUint8Arraydata. - Page numbers passed to methods like
RemovePage()andExtractPages()are 1-based, whiledoc.Pagesis a 0-based array. - Pass
{ compressed: true }toDocument.WriteTo()to enable xref-stream and object-stream compression on output. Document.ExtractPages()accepts repeated page numbers, so the same source page can appear more than once in the result.- Read
page.Rectto compute positions relative to the page’s actual width and height rather than hardcoding coordinates.
Common Issues
| Issue | Cause | Fix |
|---|---|---|
Document.Open() / OpenFile() throws InvalidPasswordError | The PDF is password-protected and no password (or the wrong one) was supplied | Pass { password: '...' } to Document.OpenFile() / Document.Open() |
RemovePage() removes the wrong page | Page numbers passed to RemovePage() are 1-based, not 0-based | Pass a 1-based page number, distinct from doc.Pages array indexing |
WriteTo() output is larger than expected | The default save does not use xref/object-stream compression | Pass { compressed: true } to Document.WriteTo() |
FAQ
Does Document.Open() accept both file paths and in-memory data?
Document.OpenFile() opens from a file path; Document.Open() accepts a
Uint8Array of in-memory bytes.
Is page numbering 0-based or 1-based?
Both, depending on the API: doc.Pages is a plain 0-based array, but methods
such as RemovePage() and ExtractPages() take 1-based page numbers.
Can I encrypt a document while saving it?
Yes — pass an encrypt option to WriteTo() / Save() with
algorithm: 'aes256' | 'aes128' | 'rc4' and optional user/owner passwords.
How do I reduce output file size?
Pass { compressed: true } to Document.WriteTo() to enable xref-stream
and object-stream compression.
Can I inspect a page’s raw content-stream operators?
Yes — parseContentStream(doc.Pages[0].Contents) returns the operator list,
and serializeContentStream() converts an edited list back into bytes.
API Reference Summary
| Class / Method | Description |
|---|---|
Document | Central entry point for creating, loading, and saving PDF documents |
Document.OpenFile() / Document.Open() | Load a PDF from a file path or in-memory bytes |
Document.New() | Start a blank document with a given PageFormat |
Document.WriteTo() / Document.Save() | Write the document to a file path or return bytes |
Document.Split() / Document.Merge() / Document.ExtractPages() | Split, merge, and extract pages across documents |
Document.Append() / Document.InsertPage() | Copy pages from one document into another |
Page | A single PDF page; exposes text, image, annotation, and content-stream methods |
Page.AddText() / Page.AddTextBlock() | Add positioned or flowed text to a page |
parseContentStream() / serializeContentStream() | Parse and re-serialize a page’s raw content-stream operators |