Documentation / API reference

API reference

Signatures, options, and behavior for the OnoDocs JavaScript and TypeScript SDK. Integration guide

Guides and samples on GitHub

Entry points

ModuleRuntime exportsResult
@onodocs/sdkopenDocument, core stage APIs, PackageOperationError, SemanticOperationError, QueryCardinalityError, sdkReleaseDateAnalysis in Node.js or the browser.
@onodocs/sdk/browseropenDocument, PackageOperationError, SemanticOperationError, QueryCardinalityError, sdkReleaseDateAnalysis, layout and immutable page publication.
@onodocs/sdk/servercreateRenderer, sdkReleaseDateHeadless Chromium image/PDF output and prepared page publication.
@onodocs/canvascreateDocument, openDocument, encode, decode, materializePageDisplayListToCanvasPage painting, views, selection, attachments and remote document loading.

All entry points include TypeScript declarations. The ? suffix marks optional arguments or properties. The SDK accepts DOCX, DOCM, DOTX and DOTM files.

openDocument

Use the default entry point to inspect content or the browser entry point to render pages.

openDocument(input: ArrayBuffer | Uint8Array | Blob, options?: OpenDocumentOptions): Promise<InspectedDocument>
openDocument(input: ArrayBuffer | Uint8Array | Blob, options?: BrowserOptions): Promise<BrowserDocument>

Both entry points accept DOCX, DOCM, DOTX and DOTM inputs, including File, which extends Blob. Macro content is not executed. Opening copies byte inputs and reads File/Blob input once. Fetch URLs in application code before opening.

OptionTypeMeaning
signalAbortSignalCancel opening.
revisionView"accepted" | "original" | "markup"Select the document revision view.
licenseKeystringOffline trial or commercial token. Omit for evaluation.
fontsFontSourcesBrowser/server only. Additional font sources; see font options.
defaultFontstringBrowser/server only. Default font family.
onProgress(progress: DocumentProgress) => voidObserve parsing, fonts, layout and ready stages and the current document source.

Opening rejects on failure or cancellation. Analysis does not create pages. Call dispose() when finished to release the retained source package. See the guide’s shared error and cleanup pattern.

Document objects

DocumentProgress contains stage (parsing, fonts, layout or ready), document: DocumentSource. Layout events may also supply phase, iteration, completed and total; these describe the current phase, not an overall percentage. Preview pages can change until opening completes.

InspectedDocument

MemberType / return valuePurpose
sourceAssemblyDocumentReadonly imported source facts and provenance; unchanged by text updates.
semanticSemanticDocumentCurrent readonly document meaning, content, and styles.
queryDocumentQuery<"document">Query rooted at the document.
licenseLicenseStatusCurrent evaluation, trial, or commercial status.
update(updates, options?)Promise<void>Replace text in supported targets.

save(options?) returns a Promise<Uint8Array> containing the current DOCX. edit(command) applies supported authoring commands; readReview() and review(command) expose document review. Call dispose() to release the document. Use the package TypeScript declarations for their complete options.

BrowserDocument

Includes every InspectedDocument member, plus:

MemberType / return valuePurpose
layoutLayoutDocumentReadonly physical layout.
geometryDocumentGeometryContent fragments and page hit testing.
pagesreadonly PageSource[]Published pages, indexed from zero.
disposedbooleanWhether rendering resources have been released.
dispose()voidDispose subscribed Canvas documents and release processing resources. Further painting is rejected; models remain inspectable.

Query results, semantic/layout models, pages, and geometry obtained before an update remain snapshots. Read them again after updating. The source model contains supported DOCX facts. Saving retains the source package and preserves unrelated content; the exposed model is not a full XML representation.

DocumentQuery

Queries are iterable and return matches in document traversal order. Kind selectors search descendants; overlapping selections do not duplicate elements.

MethodResult / scope
paragraphs(), runs(), tables(), contentControls(), bookmarks()A query of the selected kind.
stories()Story query from a document query.
rows()A table's own rows; nested-table rows are not flattened.
cells()A table or row's own cells.
children()Direct children of the selected elements.
descendants()All descendants of the selected elements.
within(element)Query scoped to the supplied DocumentElement.
get(id)Document query only: DocumentElement | undefined from the current snapshot.
closest(kind)Input elements or their nearest matching ancestors, without duplicates.
where(filter)Same-kind query narrowed by the filters below.
filter(predicate)Same-kind query narrowed by an application predicate.
findText(text: string | RegExp)QueryResults<DocumentTextRange>; see text ranges.

Filters

Applies toFilter
All element kindstext: string | { contains: string } | { startsWith: string } | { endsWith: string }
Paragraphstyle: string
Tableheaders: readonly string[]
Content controltag: string, title: string
Bookmarkname: string
Storystory: "body" | "header" | "footer" | "footnote" | "endnote" | "textbox"

All filter properties are optional. String matching is exact and case sensitive; text objects select the specified operation. Table headers match the first row exactly, in order and case sensitively. Multiple properties and chained filters combine with AND. Unknown filter keys throw.

Result selection

MethodReturn value / behavior
all()readonly T[]
map(project)U[]; project each value and its index.
count()number
first(), at(index: number)T | undefined
one()T; throws QueryCardinalityError unless exactly one result exists.
optional()T | undefined; throws QueryCardinalityError for multiple results.
for...ofIterates each result.

Result selection also applies to findText results. Negative at indices count from the end; noninteger indices throw.

Document elements

All elements expose readonly kind, id, text, source, children, and parent (undefined at the root). Source locations may be undefined; when present they contain factIndex, ordinal (bigint), and provenance.

Kind / typeAdditional members
document / DocumentRootRoot node.
story / DocumentStorystory, scopeId
paragraph / DocumentParagraphnodeId, style: string | null
run / DocumentRunnodeId, semantic, link: DocumentLink | undefined
table / DocumentTablesemantic, rows: readonly DocumentRow[], textRows: readonly (readonly string[])[]
row / DocumentRowsemantic, cells: readonly DocumentCell[], parent: DocumentTable
cell / DocumentCellsemantic, parent: DocumentRow
contentControl / DocumentContentControlnodeId, tag: string | null, title: string | null
bookmark / DocumentBookmarkname, run (start target, not an enclosing range).

textRows includes the first row. Nested-table text stays within its containing cell. Merged cells retain the document’s structure, so rows are not padded into a rectangular grid. A reused header is one semantic story with multiple physical occurrences.

A run’s link is { kind: "external", target, tooltip } or { kind: "bookmark", target }. The target is a URL or bookmark name. Applications own link navigation. Elements contain parent references and bigint metadata; use map to select the text and fields you want to export as JSON.

DocumentTextRange

interface DocumentTextRange {
  readonly kind: "textRange";
  readonly paragraph: DocumentParagraph;
  readonly start: number;
  readonly end: number;
  readonly text: string;
}

findText searches contiguous text across runs within a paragraph. Ranges use half-open [start, end) JavaScript UTF-16 offsets. String searches are case sensitive. Regular expressions preserve flags, do not alter the caller’s lastIndex, and omit zero-length matches. Each selected contiguous interval is searched independently. Searches do not join paragraphs or read text inside raster images. Semantic text may differ from generated field appearances after layout.

Text updates

update(updates: DocumentTextUpdate | readonly DocumentTextUpdate[], options?: { signal?: AbortSignal }): Promise<void>

interface DocumentTextUpdate {
  readonly target: string | DocumentEditableElement | DocumentTextRange;
  readonly text: string;
}

Available on inspected, browser, and server documents. The target is a run, paragraph, cell, content control, its query ID, or a search range. DocumentEditableElement is the union of those four element types. Element targets must contain ordinary text in one paragraph. Text inherits the first selected run’s formatting. Tabs and newlines are supported. Range replacements preserve text outside the range and its formatting; an empty range inserts text. Offsets use the original paragraph’s UTF-16 positions and cannot split surrogate pairs.

const customer = doc.query.contentControls().where({ tag: "customer" }).one();
await doc.update({ target: customer, text: "Willow Design" });

Batches reject overlapping or missing targets, generated fields, and multi-paragraph replacements without changing document content. Disjoint ranges in one run can be updated together. Unchanged updates preserve snapshots, formatting, and attachments. Updates execute in submission order. Browser updates rebuild layout and refresh views; existing HTML attachments are removed and can be reattached with fresh anchors.

For server updates, obtain target elements, IDs, or ranges by inspecting the same input with the analysis entry point. Exported page images and PDFs reflect updates. Use save() to export the current DOCX. The editor supports ordinary structural edits, and browser/server saves refresh supported fields. See editing, templates, review and forms for the supported workflows and limits.

DocumentView

Create presentation with const canvasDocument = createDocument(doc) from @onodocs/canvas. It accepts any DocumentSource, including remote pages. Canvas exposes pages, disposed, mount, refresh and dispose. Optional { container, viewOptions } passed to createDocument creates canvasDocument.view. Sources with subscriptions refresh automatically.

For HTTP endpoints, use await openDocument(url, options) from @onodocs/canvas. It returns the same CanvasDocument. Options include container, viewOptions, signal and request for fetch headers, credentials and caching. Requests use GET. Canvas loads the manifest at url and pages at url/pages/:index, preserving query parameters. See the working backend viewer.

canvasDocument.mount(container: HTMLElement, options?: ViewOptions): DocumentView

interface ViewOptions {
  readonly zoom?: number | "fit-width";
  readonly gap?: number;
  readonly title?: string;
}

zoom is a numeric scale or fit-width. Scale 1 uses 96 CSS pixels per inch; fit-width tracks the container. gap is the gap between page shells in CSS pixels, not twips. title labels the view.

MemberReturn value / meaning
elementHTMLElement; the view’s DOM root.
disposedboolean
whenRendered()Promise<void>; wait for the visible pages and nearby pages to finish painting.
setZoom(zoom)void; accepts a number or "fit-width".
toClient(pageIndex, point)DocumentPoint; page twips to viewport CSS pixels.
fromClient(point){ pageIndex, point } | undefined; viewport CSS pixels to page twips.
hitTest(point)DocumentHit | undefined; accepts viewport CSS pixels.
scrollTo(anchor, options?)boolean; reveal a page or a chosen physical fragment. Options use native ScrollIntoViewOptions. Returns false if the page is unavailable.
attach(element, options)DocumentAttachment; see attachments.
dispose()void; remove this view and its attachments.

DocumentPoint is { x: number, y: number }. Points passed to view hit testing and fromClient use the same coordinate system as event.clientX/clientY.

HTML attachments

view.attach(element: HTMLElement, options: AttachmentOptions): DocumentAttachment
OptionType / meaning
anchor (required)ViewAnchor: DocumentFragment or an object containing a page’s index and size
placement"overlay" (default), inside-{top|center|bottom}-{left|center|right}, or outside-{top|right|bottom|left}.
size{ width: number, height: number } in twips. Omit to fill the anchor, reduced by inside inset.
offset{ x: number, y: number } in twips, applied after placement.
insetInside placement only. Inward spacing in twips.
gapOutside placement only. Distance from the selected edge in twips; the control is centered along that edge.

Resolve content elements and text ranges to a chosen physical fragment through doc.geometry.fragments(anchor). Content anchors preserve transforms and clipping; page anchors use the full page. Attachments follow zoom and resize but do not reflow text.

Attaching moves the HTML element into the view. Use a dedicated element or a framework portal. DocumentAttachment.element returns that element; disposed reports its state; dispose() removes it and restores its original inline style. Reattaching the same HTML element disposes its previous attachment, including in another view. Application inputs do not change document text or appear in exported images.

Pages

The SDK exposes PageSource with index, size, interaction and load(signal?): Promise<PageDisplayList>. Canvas exposes DocumentPage with the same index, size and interaction, plus the render method below.

MemberType / meaning
indexnumber; zero-based page index.
size{ width: number, height: number } in twips.
render(canvas, options?)Promise<void>; paint to HTMLCanvasElement. Options: { dpi?: number; signal?: AbortSignal }. Await completion before reading or exporting canvas pixels.

Use standard canvas APIs to export an image. Page geometry uses 1440 twips per inch; output DPI controls raster resolution independently of view zoom.

Geometry and hit testing

MethodReturn value
doc.geometry.fragments(anchor)readonly DocumentFragment[]; anchor is a DocumentElement or DocumentTextRange.
doc.geometry.hitTest(pageIndex, point)DocumentHit | undefined; point uses page twips.

A fragment contains pageIndex, rectangle, transform, bounds, and clips. Bounds enclose the unclipped geometry; retain the supplied transforms and clips when interpreting a fragment. Content may span lines, pages, or repeated stories. Row fragments cover the row’s own cells as one rectangle per physical occurrence.

interface DocumentHit {
  readonly elementId: string;
  readonly fragment: DocumentFragment;
  readonly caret?: {
    readonly paragraphId: string;
    readonly offset: number;
    readonly point: DocumentPoint;
  };
}
const hit = view.hitTest({ x: event.clientX, y: event.clientY });
if (hit) {
  const element = doc.query.get(hit.elementId);
  const cell = element ? doc.query.within(element).closest("cell").optional() : undefined;
}

Resolve hit IDs through doc.query.get when the processing SDK is available. Canvas hit results use published IDs and work independently of the semantic model. Text hits resolve to a run or paragraph; table whitespace resolves to a cell or table. The optional caret uses the same UTF-16 offsets as text queries. Generated field appearances omit a caret when no source position can be represented. Raster drawings without a semantic hit identity and blank page space return no element. Invalid page indices throw.

Server rendering

createRenderer(options?: RendererOptions): Promise<ServerRenderer>

interface RendererOptions {
  readonly executablePath?: string;
  readonly channel?: "chrome" | "msedge" | "chromium";
}

Install playwright-core alongside the SDK and install a Chromium-family browser separately. Reuse one renderer across requests. Each open document owns a separate browser context.

ServerRenderer memberReturn value
disposedboolean; whether the renderer is closing or closed.
openDocument(input, options?)Promise<RenderedDocument>; input: ArrayBuffer or Uint8Array; options: BrowserOptions excluding onProgress.
dispose()Promise<void>; close the browser and all remaining documents.

RenderedDocument

manifest({ signal }?) returns Promise<DocumentManifest> with page sizes and interaction data. page(index, { signal }?) returns Promise<PageDisplayList>. Publish them through your application’s authenticated routes and display with Canvas in the frontend. Pass { format: "json" } to either method to receive a Promise<string> response body, and send it with Content-Type: application/json. Canvas openDocument(url, options?) loads the manifest at that URL and pages at its /pages/:index suffix. It accepts container, viewOptions, signal and request (fetch options such as headers and credentials, shared by all requests). It returns Promise<CanvasDocument> and reports unsuccessful HTTP status codes as errors. Requests default to no-store. After updates, replace the complete snapshot; do not mix old and new pages. See the combined deployment guide.

MemberType / return value
pagesreadonly PageSize[]; width and height in twips.
disposedboolean; whether the document context is closing or closed.
update(updates, options?)Promise<void>; same text-update contract.
licenseStatus()Promise<LicenseStatus>
renderPage(index, options?)Promise<Uint8Array>; PNG or JPEG bytes.
pdf(options?)Promise<Uint8Array>; options: { dpi?: number, signal?: AbortSignal }.
dispose()Promise<void>; close this document’s context.

save(options?) returns current Word bytes. edit(command) forwards authoring operations through the same document model. Exported PDF has the current supported field values.

RenderPageOptions

OptionType / meaning
format"png" | "jpeg"; default PNG.
dpiPositive finite output resolution; default 96 DPI.
qualityNumber from 0 to 1; JPEG encoding quality, default 0.92.
signalAbortSignal for cancellation.

PDF output defaults to 150 DPI. PDF exports preserve document page sizes, including mixed sizes. They include searchable text, links, bookmarks and supported tagged structure. Supported graphics remain vector while visible native text is rasterized. PDF/UA certification is not established. HTML attachments are excluded.

Document contexts make no outbound requests. Supply fonts as data URLs or install them on the rendering host. Cancelling an executing operation closes the document context; reopen it to retry. Cancelling a queued operation leaves the active operation and document intact. Operations on one document are serialized; your application controls concurrency across documents. Dispose documents and the renderer in finally blocks in production.

FontSources

type FontSources = string | FontVariantSources | Readonly<Record<string, string | FontVariantSources>>;

interface FontVariantSources {
  readonly regular: string;
  readonly bold?: string;
  readonly italic?: string;
  readonly boldItalic?: string;
  readonly collectionIndex?: number | Readonly<Partial<Record<"regular" | "bold" | "italic" | "boldItalic", number>>>;
  readonly fallbackFaces?: readonly string[];
  readonly familyFaces?: Readonly<Partial<Record<"roman" | "swiss", string>>>;
}

Strings identify font sources. Use a family-name map to provide multiple families and variant objects for their faces. Embedded DOCX fonts load automatically. See the guide’s font deployment notes.

LicenseStatus

Pass licenseKey when opening a document. Browser/analysis documents expose license; server documents expose asynchronous licenseStatus(). Verification is offline; browser verification requires HTTPS or a secure local context.

modeAdditional property
"evaluation"reason: missing-key, invalid-key, verification-unavailable, not-yet-valid, trial-expired, release-not-covered, demo-expired, or origin-not-covered.
"trial"license: signed trial claims.
"demo"license: a website demonstration token valid for at most 24 hours at its exact browser origin.
"commercial"license: signed commercial claims.

Evaluation keeps analysis results available and watermarks rendered output. sdkReleaseDate is the SDK’s exported release-date string. See licensing terms.

Low-level models and stages

The default entry point also re-exports the engine’s stage APIs and readonly contracts. These are for applications that provide their own services or need an intermediate result.

APIPurpose
parseDocumentSourceCreate typed imported source facts.
createSemanticDocumentResolve document meaning from source facts.
parseDocumentForRenderingPrepare semantic content and owned rendering resources.
createLayoutDocumentRealize page layout with explicit layout services.
createPageDisplayListCompile one layout page to paint commands.
materializePageDisplayListToCanvasExported by @onodocs/canvas. Replay paint commands through the canvas adapter.

Use openDocument for managed loading and rendering. Treat stage outputs as read-only. Use layout output for page geometry. The complete low-level signatures are included in the package’s TypeScript declarations; download the SDK from the public releases to inspect them.