Univer Docs API
Univer Docs is responsible for document typesetting, and its concepts follow Microsoft Word closely.
Importing
import '@univerjs/docs/facade'import '@univerjs/docs-ui/facade'Operate documents
In a document unit, unitId is the unique identifier of the document, and documents do not have a subUnitId.
Text content is stored in the body.dataStream string, which contains no style information.
Style information is stored in a separate data structure, which refers back to the text through index references.
Line breaks, page breaks, sections, paragraphs, and tables are each marked by a special character in the text. Rendering converts these characters into the corresponding elements.
The following articles describe the design of the document data structures: Univer Document Architecture and Module Design and An Initial Exploration of Univer Document Typesetting Design.
Create document
Call univerAPI.createDocument(data) to create a document. The method returns the corresponding FDocument facade wrapper.
Its argument is an optional document data object that contains the initial data. Passing {} creates an empty document.
To work with the underlying univer instance instead of the Facade API, call univer.createUnit(UniverInstanceType.UNIVER_DOC, data).
const doc = univerAPI.createDocument(data)Get document unitId
const doc = univerAPI.getActiveDocument()const unitId = doc?.getId()Get document data
const doc = univerAPI.getActiveDocument()const saveData = doc.save()Dispose document
When a document is no longer needed, call dispose on the Univer instance to destroy it.
univer.dispose()Operate text
The calls in this section modify text in the rich-text area.
Insert text
Append the specified text to the end of the text area.
const doc = univerAPI.getActiveDocument()doc?.insertText(0, 'Univer')Delete text
Remove text by document offsets.
const doc = univerAPI.getActiveDocument()doc?.deleteRange({ startOffset: 0, endOffset: 1 })Modify style
Set a text style on a paragraph.
const doc = univerAPI.getActiveDocument()const paragraph = doc?.getParagraphs()[0]paragraph?.setStyle({ textStyle: { cl: { rgb: '#FF0000', }, },})Insert page break
\f is the page-break character. Inserting it into the document creates a page break.
const doc = univerAPI.getActiveDocument()doc?.insertText(0, '\f')Document statistics
The underlying DocumentDataModel computes statistics for the entire document or for selected ranges.
const doc = univerAPI.getActiveDocument()if (!doc) throw new Error('No active document')const statistics = await doc.getDocumentDataModel().getStatistics({ locale: univerAPI.Enum.LocaleType.EN_US,})console.log(statistics.words, statistics.charactersWithSpaces, statistics.paragraphs)getStatistics() returns the word, character, and paragraph counts. Pass ranges to count only the selected text, or pass an AbortSignal in signal to cancel calculations that are no longer required.
How is this guide?