Skip to content
Document Authoring DA  API Docs v2.0.0
npmGitHub

DocAuthSystem

DocAuthSystem:

A DocAuthSystem instance holds the internal WASM engine and loaded fonts. It is used to load or import documents and create DocAuthEditor instances.

Getting started guide

getFragmentContract(): FragmentContract

Returns the validation contract for structured fragments returned by this SDK version.

FragmentContract


validateFragment(value): FragmentValidationResult

Validates an opaque structured fragment against the current contract without changing the value. Returns validation failures as structured issues instead of throwing.

unknown

FragmentValidationResult


loadDocument(documentInput): Promise<DocAuthDocument>

Loads a document stored in the Document Authoring format. The document can be provided as a JSON string or a JavaScript object.

DocAuthDocumentInput

Promise<DocAuthDocument>

// Load from JSON string
const doc = await system.loadDocument('{"version":"7.0","content":[...]}');
// Load from object
const docData = { version: '7.0', content: [...] };
const doc = await system.loadDocument(docData);
// Load from server
const doc = await system.loadDocument(fetch('/api/documents/123'));
// Load and create editor
const doc = await system.loadDocument(savedDocJSON);
const editor = await system.createEditor(targetElement, { document: doc });

Use the optional participant load option to set the author label and access role for the document. If omitted, the document uses an owner with an empty author label. Hosts must bind the label to an authenticated user themselves; the SDK does not authenticate.

loadDocument(documentInput, options?): Promise<DocAuthDocument>

Loads a document stored in a native Document Authoring format. The input can be a JSON string, a JavaScript object, a Blob/Response carrying JSON, or a Promise resolving to one of those.

  • format: 'docjson' (the default) parses the canonical DocJSON wire format.
  • format: 'fragment' parses the wire format produced by DocAuthDocument.saveDocument with format: 'fragment' (or by DocAuthEditor.getSelectionContent with format: 'fragment'), and wraps it in a new document. The complete fragment is validated against the generated active contract before any model or resource import; invalid input rejects the returned promise. Section structure (page setup, headers/footers, etc.) is reconstructed from the fragment’s trailing section break, or defaulted if absent. Document-level state that doesn’t ride along in a fragment (comment threads, document settings, imported-DOCX metadata) is initialised empty.

DocAuthDocumentInput

LoadDocumentOptions

Optional. See LoadDocumentOptions.

Promise<DocAuthDocument>


importDOCX(docx, options?): Promise<DocAuthDocument>

Imports a DOCX document.

BlobInput

ImportDOCXOptions

Promise<DocAuthDocument>

// Import from file input
const fileInput = document.querySelector('input[type="file"]');
const file = fileInput.files[0];
const doc = await system.importDOCX(file);
// Import from URL
const doc = await system.importDOCX(fetch('/documents/template.docx'));
// Import with abort signal
const controller = new AbortController();
const doc = await system.importDOCX(file, {
abortSignal: controller.signal,
});
// Complete workflow: import DOCX, edit, export PDF
const doc = await system.importDOCX(fetch('/template.docx'));
const editor = await system.createEditor(targetElement, { document: doc });
// ... user edits document ...
const pdfBuffer = await editor.currentDocument().exportPDF();

import(blob, options?): Promise<DocAuthDocument>

Imports a document by automatically detecting its format from the binary content (and optionally the file name or file type).

Supported import formats: DOCX (including DOTX, DOCM), RTF, ODT, Markdown, TXT, DocJSON, and images (PNG, JPEG, BMP, GIF, WebP).

Throws if the format is unsupported or the file is corrupted.

BlobInput

ImportConfig

Promise<DocAuthDocument>

// Import with automatic format detection
const document = await system.import(file, { fileName: 'report.docx' });
const editor = await system.createEditor(target, { document });
// Import with explicit file type (skips auto-detection)
const document = await system.import(blob, { format: 'docx' });
// Import from URL
const response = await fetch('/documents/template.docx');
const document = await system.import(response, { fileName: 'template.docx' });

createEditor(target, options?): Promise<DocAuthEditor>

Creates an editor in the specified HTML element. IMPORTANT: The position of the target element cannot be static or unset. If unsure, use relative.

Browser only: systems created through the Node.js entry (@nutrient-sdk/document-authoring/node) are headless, and calling this method on them throws.

HTMLElement

CreateEditorOptions

Promise<DocAuthEditor>

// Shared code for the examples below - ensure target element has proper positioning
const target = document.getElementById('editor');
target.style.position = 'relative';
target.style.height = '600px';
// Create editor with empty document
const editor = await system.createEditor(target);
// Create editor with existing document
const doc = await system.loadDocument(docJSON);
const editor = await system.createEditor(target, { document: doc });
// Complete workflow with event handling
const editor = await system.createEditor(target);
editor.on('content.change', async () => {
const doc = await editor.currentDocument().saveDocument();
localStorage.setItem('draft', JSON.stringify(doc));
});

detectFileKind(blob): Promise<DocAuthFileKind>

Which product a file belongs to, without opening it.

For a host with one file picker: neither DocAuthSystem.import nor DocAuthSystem.importSpreadsheet can answer this, because each is typed to return one thing. Ask first, then call the matching method and mount the matching editor.

BlobInput

Promise<DocAuthFileKind>

const kind = await system.detectFileKind(file);
if (kind === 'spreadsheet') {
const spreadsheet = await system.importSpreadsheet(file);
await system.createSpreadsheetEditor(target, { spreadsheet });
} else {
const doc = await system.import(file);
await system.createEditor(target, { document: doc });
}

DocAuthFileKind


importSpreadsheet(blob, options?): Promise<DocAuthSpreadsheet>

Imports a spreadsheet.

Requires the Spreadsheet Editing component in the license key; an .xlsx file also requires XLSX Support.

Use DocAuthSystem.detectFileKind to decide between this and DocAuthSystem.import.

A large spreadsheet can take minutes to open. Pass onProgress to show how far it has got, and abortSignal to let a user give up on it.

In Node.js, importing an .xlsx writes a temporary copy of the spreadsheet under os.tmpdir(), readable only by the user running the process, and deletes it when the import finishes.

BlobInput

ImportSpreadsheetConfig

Promise<DocAuthSpreadsheet>

// Import the file a user picks
const input = document.querySelector<HTMLInputElement>('input[type="file"]')!;
input.addEventListener('change', async () => {
const file = input.files?.[0];
if (!file) return;
const spreadsheet = await system.importSpreadsheet(file);
});
// Import from a URL, naming the file so detection does not have to guess
const spreadsheet = await system.importSpreadsheet(fetch('/books/quarterly.xlsx'), {
fileName: 'quarterly.xlsx',
});
// A <progress> bar for the current phase; `done` and `total` start again when the phase changes
const spreadsheet = await system.importSpreadsheet(file, {
onProgress: ({ phase, done, total }) => {
phaseLabel.textContent = phase;
// `total` is null when the file states no total for this phase: show the bar as indeterminate
if (total === null) progressBar.removeAttribute('value');
else progressBar.value = Math.min(1, done / total);
},
});
// Let the user give up on a slow import
const controller = new AbortController();
cancelButton.onclick = () => controller.abort();
const spreadsheet = await system.importSpreadsheet(file, { abortSignal: controller.signal });

ImportSpreadsheetConfig


loadSpreadsheet(input, options?): Promise<DocAuthSpreadsheet>

Loads a spreadsheet from the format it was saved in.

Requires the Spreadsheet Editing component in the license key.

The counterpart of DocAuthSystem.loadDocument: it reads only the Document Authoring spreadsheet format; use importSpreadsheet for other formats. Saving with DocAuthSpreadsheet.saveSpreadsheet and loading here is the lossless round trip.

DocAuthSpreadsheetInput

LoadSpreadsheetOptions

Promise<DocAuthSpreadsheet>

// The lossless round trip
const saved = await spreadsheet.saveSpreadsheet();
const reopened = await system.loadSpreadsheet(saved);
// Reopen from a server, reporting progress the same way an import does. `describe` turns a report into
// a status line; the SpreadsheetImportProgress examples show one that words each phase.
const spreadsheet = await system.loadSpreadsheet(fetch('/api/spreadsheets/123'), {
onProgress: (progress) => statusLabel.replaceChildren(describe(progress)),
});

createSpreadsheetFromPlaintext(text): Promise<DocAuthSpreadsheet>

Creates a spreadsheet with one blank sheet, optionally with some text in its first cell.

Requires the Spreadsheet Editing component in the license key.

The counterpart of DocAuthSystem.createDocumentFromPlaintext. The text is placed in the first cell as it is given; it is not parsed as rows and columns.

string

Promise<DocAuthSpreadsheet>

// An empty spreadsheet to start from
const spreadsheet = await system.createSpreadsheetFromPlaintext('');
const editor = await system.createSpreadsheetEditor(target, { spreadsheet });
// A1 holds the whole string, tab and newline included — it is not split into cells
const spreadsheet = await system.createSpreadsheetFromPlaintext('Name\tTotal\nAlice\t3');

createSpreadsheetEditor(target, options?): Promise<DocAuthSpreadsheetEditor>

Creates a spreadsheet editor in the specified HTML element. IMPORTANT: the position of the target element cannot be static or unset. If unsure, use relative.

Requires the Spreadsheet Editing component in the license key. In evaluation mode, the grid shows a watermark, and the editor stops accepting input when the evaluation period ends.

Browser only: systems created through the Node.js entry (@nutrient-sdk/document-authoring/node) are headless, and calling this method on them throws.

If no spreadsheet is given the editor opens on a blank one, so a grid is on screen straight away — which is what lets a host show something while a large file is still being read.

HTMLElement

CreateSpreadsheetEditorOptions

Promise<DocAuthSpreadsheetEditor>

// Open a file straight into an editor
const spreadsheet = await system.importSpreadsheet(file);
const editor = await system.createSpreadsheetEditor(target, { spreadsheet });
// Mount first, fill afterwards: the grid is visible while the file is still being read
const editor = await system.createSpreadsheetEditor(target);
const spreadsheet = await system.importSpreadsheet(file, {
// per phase: `done` and `total` start again when the phase changes
onProgress: ({ phase, done, total }) => showProgress(phase, total === null ? null : Math.min(1, done / total)),
});
editor.setCurrentSpreadsheet(spreadsheet);

DocAuthSpreadsheetEditor


createDocumentFromPlaintext(text, options?): Promise<DocAuthDocument>

Creates a document from plain text by interpreting patterns and replacing characters. E.g.:

  • \n creates a line break in a paragraph
  • \n\n separates paragraphs
  • \t is replaced with spaces

string

CreateDocumentFromPlaintextOptions

Promise<DocAuthDocument>

// Simple text document
const doc = await system.createDocumentFromPlaintext('Hello World');
// Multi-paragraph document
const text = `First paragraph.
Second paragraph with line break\nand continuation.`;
const doc = await system.createDocumentFromPlaintext(text);
// With custom page settings
const doc = await system.createDocumentFromPlaintext('My content', {
pageSize: 'A4',
pageMargins: { left: 72, right: 72, top: 72, bottom: 72 },
});
// Create document and editor in one flow
const doc = await system.createDocumentFromPlaintext('Initial content');
const editor = await system.createEditor(targetElement, { document: doc });

CreateDocumentFromPlaintextOptions for available options.


destroy(): void

Releases resources held by the system. IMPORTANT: The system and any editors created by this system can no longer be used after calling this.

void

// Clean up when done
editor.destroy();
system.destroy();
// Or use try-finally pattern
const system = await createDocAuthSystem();
try {
const editor = await system.createEditor(target);
// ... use editor ...
editor.destroy();
} finally {
system.destroy();
}