API reference

Every public export of @office-kit/docx, plus the one function of @office-kit/docx-preview: 475 names in 31 groups. The library is functions and constants only, with no classes. Most functions take a Docx as their first argument, and the module has no side effects, so a bundler drops whatever you do not import.

A CI check compares this page with the built package, so it cannot fall behind. For parameter shapes, read the type declarations that ship with the package or the source. For code you can paste, see Getting started and the recipes.

Lifecycle

Create, open, clone, and serialise a document.

  • createDocx ({ paragraphs? }?) => Docx
  • openDocx (bytes: Uint8Array) => Docx
  • fromBlob (blob: Blob) => Promise<Docx>
  • toUint8Array (doc: Docx) => Uint8Array
  • toBlob (doc: Docx) => Blob
  • clone (doc: Docx) => Docx

Paragraphs & blocks

Append, insert, and remove body paragraphs, headings, and breaks.

  • appendParagraph
  • insertParagraphAt
  • removeParagraph
  • appendHeading
  • appendPageBreak
  • appendLineBreak
  • appendSectionBreak
  • clearBody
  • paragraphs

Inline & text

Find and replace, runs and their formatting, paragraph alignment, indents, spacing, borders, and shading.

  • replaceText
  • replaceTextEverywhere
  • findText
  • findTextEverywhere
  • appendTextRun
  • setParagraphText
  • paragraphText
  • setRunFormat
  • clearRunFormat
  • getRunFormat
  • HIGHLIGHT_COLORS readonly HighlightColor[] — the only w:highlight values run-format writers accept
  • setParagraphAlignment
  • getParagraphAlignment
  • setParagraphIndent
  • setParagraphSpacing
  • setParagraphBorders
  • setParagraphShading
  • getParagraphStyle
  • getParagraphNumbering
  • mergeAdjacentRuns
  • mergeAdjacentRunsInBody
  • setRunOnOff
  • setRunValProp
  • getRunProp
  • setParagraphOnOff
  • setParagraphValProp
  • getParagraphProp
  • splitParagraphAt
  • mergeParagraphIntoPrevious
  • runTextLength
  • isolateParagraphRunRange

Styles & numbering

The style table, bullet and numbered lists, and lifting styles from a designed template.

  • addStyle
  • removeStyle
  • listStyles
  • ensureHeadingStyles
  • findStyleIdByName
  • setParagraphStyle
  • addBulletList
  • addNumberedList
  • applyListToParagraph
  • mergeStylesFromTemplate
  • setStyleOnOff
  • setStyleValProp
  • getStyleProp
  • setNumberingLevelOnOff
  • setNumberingLevelVal
  • getNumberingLevelProp

Tables

Build tables and edit rows, cell text, borders, shading, and alignment.

  • addTable
  • tables
  • removeTable
  • removeAllTables
  • unwrapTable
  • appendTableRow
  • removeTableRow
  • setTableRowAsHeader
  • setTableRowHeight
  • setTableBorders
  • setTableCellText
  • getTableCellText
  • setTableCellShading
  • setTableCellVerticalAlign

Table layout

Word's Table Layout operations: rows, columns and cells at any position, merge and split, sizes, margins, sorting, text conversion and formulas.

  • tableCellPlacements (table) => TableCellPlacement[][]
  • tableColumnCount
  • tableColumnWidths
  • tableCellBlocks
  • insertTableRow (table, index, { formatFrom? }?) => WmlTableRow
  • deleteTableRows
  • insertTableColumn (table, index, { widthTwips?, formatFrom? }?) => void
  • deleteTableColumns
  • deleteTableCells (table, range, 'left' | 'up') => void
  • mergeTableCells (table, range: TableCellRange) => void
  • splitTableCell (table, row, cell, { columns, rows }) => void
  • splitTable (doc, table, row) => WmlTable
  • setTableWidth
  • setTableAlignment
  • setTableIndent
  • setTableLayout
  • setTableCellSpacing
  • setTableDefaultCellMargins
  • setTableAltText
  • setTablePosition
  • setTableCellWidth
  • setTableCellMargins
  • setTableCellTextDirection
  • setTableColumnWidth
  • distributeTableColumns
  • autoFitTable (table, 'contents' | 'window' | 'fixed') => void
  • setTableRangeBorders (table, range, edges, border?) => void
  • sortTableRows (table, { keys, headerRow? }) => void
  • convertTextToTable (doc, first, last, { separator, columns? }) => WmlTable
  • evaluateTableFormula (table, row, cell, formula) => number
  • formatFieldNumber

Table styles

Word's built-in table styles (Plain, Grid and List Tables), Table Style Options, and table style formatting.

  • BUILT_IN_TABLE_STYLES
  • addBuiltInTableStyle (doc, styleId) => void
  • builtInTableStyle
  • setTableStyle
  • getTableStyle
  • setTableLook (table, look: TableLook) => void
  • getTableLook
  • setTableStyleFormatting (doc, styleId, region, formatting) => void

Images

Add inline images, list the ones in a file, and replace them by part name or alt text.

  • addImage
  • addImageRun
  • insertImageInto
  • images
  • imageReferences
  • replaceImage
  • replaceImageByAltText
  • removeAllImages
  • imageDrawings
  • getImageInfo
  • setImageAltText
  • setImageSizeEmu

Pictures, charts & arrangement

Picture Format and Arrange: wrapping, position, z-order, crop, shape, border, effects, color adjustments; Insert ▸ Chart with an embedded workbook. Drawings are addressed by their imageDrawings index.

  • readDrawing (doc, drawing: XmlElement) => DrawingInfo
  • imagePixelSize (bytes) => ImagePixelSize | undefined
  • imageNaturalSizeEmu (bytes) => { widthEmu, heightEmu } | undefined
  • setDrawingWrap (doc, index, wrap: WrapStyle, position?) => void
  • setDrawingPosition (doc, index, { horizontal?, vertical? }) => void
  • setDrawingAnchorOptions (doc, index, AnchorOptions) => void
  • arrangeDrawing (doc, index, op: DrawingOrder) => void
  • setDrawingTransform (doc, index, { rotation?, flipH?, flipV? }) => void
  • setDrawingName (doc, index, name) => void
  • setDrawingHidden (doc, index, hidden) => void
  • setDrawingAspectLock (doc, index, locked) => void
  • setDrawingHyperlink (doc, index, url | undefined) => void
  • removeDrawing (doc, index) => void
  • setPictureCrop (doc, index, PictureCrop) => void
  • setPictureGeometry (doc, index, preset: string) => void
  • setPictureOutline (doc, index, PictureOutline | undefined) => void
  • setPictureEffects (doc, index, PictureEffects) => void
  • setPictureColorAdjustments (doc, index, PictureColorAdjustments) => void
  • changePicture (doc, index, bytes, contentType?) => void
  • resetPicture (doc, index, { size? }?) => void
  • addChartRun (doc, spec: ChartSpec, { widthEmu, heightEmu, name?, altText? }) => WmlRun
  • readChart (doc, drawing: XmlElement) => ChartSpec | undefined
  • setChart (doc, index, spec: ChartSpec) => void

Headers, footers, sections

Headers and footers for default, first, and even pages, plus page size, margins, and orientation.

  • addHeader
  • addFooter
  • addPageNumberFooter
  • setPageSize
  • setPageMargins
  • setPageOrientation
  • headers
  • footers
  • removeAllHeaders
  • removeAllFooters

Fields & tracked changes

Complex fields such as a table of contents or a merge field, and bulk accept or reject of tracked insertions and deletions.

  • appendField
  • addTableOfContents
  • appendMergeField
  • acceptAllRevisions
  • rejectAllRevisions

Insert at a position

What Word's Insert tab places at a character offset of a paragraph: complex fields with computed results, links, bookmarks, symbols, equations, drop caps and signature lines.

  • insertField (doc, paragraph, offset, instruction, { result?, rPr?, lang?, context? }?) => WmlRun[]
  • buildComplexField (instruction, result, rPr?, beginChildren?) => WmlRun[]
  • updateFields (doc, { now?, page?, pageCount?, types? … }?) => number
  • complexFields (doc) => FieldInfo[]
  • insertFormField (doc, paragraph, offset, FormFieldOptions) => WmlRun[]
  • formatDatePicture (date, picture, locale?) => string
  • quoteFieldArgument (value) => string
  • insertHyperlink (doc, paragraph, offset, text, { url? | bookmark?, tooltip?, targetFrame? }) => XmlElement
  • paragraphHyperlinks (doc, paragraph) => HyperlinkInfo[]
  • editHyperlink
  • removeHyperlink
  • insertBookmark (doc, name, start: TextPoint, end?: TextPoint) => number
  • isValidBookmarkName (name) => boolean
  • ensureReferenceBookmark (doc, paragraph, run?) => string
  • insertSymbol (doc, paragraph, offset, SymbolSpec, rPr?) => WmlRun
  • insertEquation (doc, paragraph, offset, linear, { display? }?) => XmlElement
  • buildEquation (linear, { display? }?) => XmlElement
  • equationLinear (element) => string
  • paragraphEquations (paragraph) => XmlElement[]
  • setEquation (doc, paragraph, index, linear) => XmlElement
  • getDropCap (doc, paragraph) => DropCapOptions
  • setDropCap (doc, paragraph, { position, lines?, distanceTwips?, font? }) => void
  • insertSignatureLine (doc, paragraph, offset, SignatureLineOptions) => WmlRun

Pages, headers & page numbers

Cover pages, header and footer content, page numbers and their format, and another document's content merged in (Insert ▸ Object ▸ Text from File).

  • insertCoverPage (doc, paragraphs) => void
  • removeCoverPage (doc) => boolean
  • hasCoverPage (doc) => boolean
  • setDifferentFirstPage (doc, on) => void
  • headerFooterParagraphs (doc, kind, type?) => WmlParagraph[]
  • setHeaderFooterParagraphs (doc, kind, type, paragraphs) => void
  • removeHeaderFooter (doc, kind, type?) => boolean
  • ensureHeaderFooterStyle (doc, kind) => string
  • insertPageNumbers (doc, { position, align, style? }) => void
  • removePageNumbers (doc) => number
  • setPageNumberFormat (doc, { format?, start?, chapterStyle?, chapterSeparator? }) => void
  • getPageNumberFormat (doc) => PageNumberFormatOptions
  • PAGE_NUMBER_FORMATS
  • CHAPTER_SEPARATORS
  • insertDocumentContent (doc, source: Docx, blockIndex) => number

Document properties

Core and app properties, with shortcuts for the title and the author.

  • coreProperties
  • setCoreProperties
  • appProperties
  • setAppProperties
  • title
  • author
  • setTitle
  • setAuthor
  • getDocumentSetting
  • setDocumentSettingOnOff
  • setDocumentSettingVal

Shapes, text boxes, WordArt & ink (VML)

Draw shapes from Word's gallery, text boxes, WordArt, ink strokes and drawing canvases as ECMA-376 VML (`w:pict`), and edit their fill, outline, shadow, layout, wrap, z-order, text and grouping. Shape handles are the VML elements.

  • addShape (doc, paragraph, { preset, width, height, left?, top?, wrap?, fill?, stroke?, text?, points?, ink? }, index?) => XmlElement
  • addWordArt (doc, paragraph, { text, width, height, font?, size?, bold?, italic? }, index?) => XmlElement
  • addDrawingCanvas (doc, paragraph, { width, height }, index?) => XmlElement
  • addShapeToGroup (doc, group, options) => XmlElement
  • vmlShapes (doc) => XmlElement[]
  • runShape (run) => XmlElement | undefined
  • shapeKind
  • shapePreset
  • SHAPE_PRESETS
  • SHAPE_CATEGORIES
  • changeShapePreset
  • getShapePoints
  • setShapePoints
  • getShapeLayout
  • setShapeLayout
  • getShapeWrap
  • setShapeWrap
  • setShapeOrder
  • setShapeMoveWithText
  • getShapeFill
  • setShapeFill
  • vmlImageData
  • FILL_PATTERNS
  • getShapeStroke
  • setShapeStroke
  • getShapeShadow
  • setShapeShadow
  • shapeText
  • setShapeText
  • getTextBoxLayout
  • setTextBoxLayout
  • linkTextBoxes
  • linkedTextBox
  • getWordArt
  • setWordArt
  • getShapeAltText
  • setShapeAltText
  • getShapeName
  • setShapeName
  • removeShape
  • groupShapes
  • ungroupShapes
  • groupMembers

SmartArt

Insert SmartArt diagrams (DrawingML diagrams: data model, layout, style and colour parts) and edit their bullets, layout, colours, style and size.

  • addSmartArt (doc, paragraph, { layout, nodes, width?, height?, colors?, style? }, index?) => WmlRun
  • smartArts (doc) => SmartArtRef[]
  • runSmartArt (doc, run) => SmartArtRef | undefined
  • getSmartArt
  • setSmartArtNodes
  • setSmartArtLayout
  • setSmartArtColors
  • setSmartArtStyle
  • setSmartArtSize
  • removeSmartArt
  • SMARTART_LAYOUTS
  • SMARTART_COLORS
  • SMARTART_STYLES

Diagnostics

Validate the package and read a document back: outline, fields, statistics, plain text.

  • validate
  • validatePackage
  • statistics
  • outline
  • fields
  • text

Review: tracked changes

List, accept, and reject revisions; record insertions, deletions, and formatting changes as tracked; compare two documents.

  • revisions (doc: Docx) => RevisionInfo[]
  • acceptRevisions (doc: Docx, ids: readonly string[]) => number
  • rejectRevisions (doc: Docx, ids: readonly string[]) => number
  • insertTrackedText
  • deleteTrackedText
  • paragraphMarkRevision
  • trackParagraphMark
  • trackRunFormatChange
  • trackParagraphFormatChange
  • compareDocuments (original: Docx, revised: Docx, options: CompareOptions) => Docx

Review: comments, proofing, accessibility

Read and edit comments, set the proofing language, count words as Word does, and check accessibility.

  • comments (doc: Docx) => CommentInfo[]
  • setCommentText
  • removeComment
  • getRunLanguage
  • setRunLanguage
  • wordCount (doc: Docx, options?: WordCountOptions) => WordCount
  • checkAccessibility (doc: Docx) => AccessibilityIssue[]
  • contrastRatio

Document protection

Restrict editing (with an optional password), editable exceptions, and Always Open Read-Only.

  • documentProtection
  • protectDocument (doc: Docx, options: ProtectOptions) => void
  • unprotectDocument (doc: Docx, password: string) => boolean
  • verifyProtectionPassword
  • writeProtection
  • setWriteProtection
  • editableRanges
  • addEditableRange
  • removeEditableRange

View & custom properties

The view and zoom a document opens with, and custom document properties.

  • documentView
  • setDocumentView
  • documentZoom
  • setDocumentZoom
  • customProperties
  • setCustomProperty
  • removeCustomProperty

Low-level part access

The parsed side parts, for when the functions above do not reach far enough.

  • stylesPart
  • numberingPart
  • commentsPart
  • footnotesPart
  • endnotesPart
  • xmlPartNames
  • getRawPartRoot
  • markRawPartDirty
  • childElementsOf
  • appendChildElement
  • makePropsElement
  • getElementAttr
  • setElementAttr
  • getElementProp
  • setElementOnOff
  • setElementValProp

Stories & section headers

Headers, footers, footnotes, endnotes and comments as typed block content, and which header/footer each section shows.

  • storyBody (doc, ref: StoryRef) => WmlBody | undefined
  • contentControlBlocks (block: WmlBlock) => readonly WmlBlock[] | undefined
  • wrappedRuns (inline: WmlInline) => readonly WmlRun[] | undefined
  • storyView (doc, ref: StoryRef) => Docx | undefined
  • storyKey (ref: StoryRef) => string
  • parseStoryKey (key: string) => StoryRef | undefined
  • sectionProperties (doc) => Array<XmlElement | undefined>
  • resolveHeaderFooter (doc, section, kind, type) => { partName, section } | undefined
  • ensureHeaderFooter (doc, section, kind, type) => string
  • isHeaderFooterLinked (doc, section, kind, type) => boolean
  • setHeaderFooterLinked (doc, section, kind, type, linked) => void

Character & paragraph formatting

Theme colours, every underline style, theme fonts, run shading and borders, per-side paragraph borders, tab stops, phonetic guides, enclosed characters, list definitions, and Word's built-in styles.

  • setRunColor (run, color: ColorValue | undefined) => void
  • setRunUnderline (run, underline: UnderlineValue | undefined) => void
  • setRunFont (run, script, font: FontChoice | undefined) => void
  • setRunShading (run, shading: ShadingOptions | undefined) => void
  • setRunBorder (run, line: BorderLine | undefined) => void
  • setParagraphBorder (p, side, line: BorderLine | undefined) => void
  • setParagraphTabs (p, tabs: TabStop[]) => void
  • getParagraphTabs (p) => TabStop[]
  • buildRubyRun (base, ruby, options, rPr?) => WmlRun
  • readRuby (run) => RubyInfo | undefined
  • buildEnclosedCharacterRuns (text, options, rPr?) => WmlRun[]
  • addListDefinition (doc, levels: ListLevel[]) => number
  • restartList (doc, numId, ilvl, start) => number | undefined
  • ensureBuiltinStyle (doc, styleId) => boolean
  • builtinStyles () => BuiltinStyleInfo[]
  • updateStyleFormatting (doc, styleId, { run?, paragraph? }) => boolean
  • THEME_COLORS
  • UNDERLINE_STYLES
  • SHADING_PATTERNS
  • BORDER_LINE_STYLES
  • RUBY_ALIGNMENTS
  • ENCLOSURES
  • NUMBER_FORMATS

Page-size & margin constants

Ready-made values for setPageSize and setPageMargins, plus the library version.

  • PAGE_SIZE_A4
  • PAGE_SIZE_LETTER
  • MARGINS_NORMAL
  • VERSION

Section layout

Columns, line numbers, page borders, vertical alignment, document grid and section breaks, per section.

  • sectionCount (doc) => number
  • sectionIndexAt (doc, blockIndex) => number
  • getSectionProperties (doc, section?) => SectionProperties
  • setSectionProperties (doc, patch, scope?) => void
  • insertSectionBreak (doc, blockIndex, start?) => number
  • PAGE_BORDER_LINE_STYLES readonly string[] — line styles for page borders
  • PAGE_BORDER_ART readonly string[] — art border names (ST_Border)

Design: themes, style sets, page background

The theme part (colours, fonts, effects), style sets, default paragraph spacing, page colour and watermarks.

  • setTheme (doc, theme: ThemeDefinition) => void
  • getTheme (doc) => ThemeInfo | undefined
  • setThemeColors (doc, colors: ThemeColorScheme) => void
  • setThemeFonts (doc, fonts: ThemeFontScheme) => void
  • setThemeEffects (doc, effects: ThemeEffectScheme) => void
  • themeColorValue (colors, themeColor, { shade?, tint? }?) => string | undefined
  • applyStyleSet (doc, set: StyleSetDefinition) => void
  • currentStyleSet (doc) => StyleSetDefinition | undefined
  • setDefaultParagraphSpacing (doc, { before, after, line }) => void
  • getDefaultParagraphSpacing (doc) => DefaultParagraphSpacing | undefined
  • setPageColor (doc, color: PageColor | undefined) => void
  • getPageColor (doc) => PageColor | undefined
  • setWatermark (doc, watermark: Watermark | undefined) => void
  • getWatermark (doc) => WatermarkInfo | undefined
  • THEMES
  • THEME_COLOR_SCHEMES
  • THEME_COLOR_SLOTS
  • THEME_FONT_SCHEMES
  • THEME_EFFECT_SCHEMES
  • STYLE_SETS
  • PARAGRAPH_SPACING_PRESETS

References

Word's References tab: tables of contents and figures, footnotes and endnotes, citations and bibliography, captions, index, and tables of authorities — with computed field results.

  • insertTableOfContents (doc, at, options?) => void
  • tableOfContentsInstruction
  • removeTableOfContents
  • setTocLevel (doc, paragraph, level | 'none') => void
  • tocLevel
  • updateTables (doc, { types?, pageOf? }?) => number
  • insertNote (doc, paragraph, offset, 'footnote' | 'endnote', options?) => number
  • noteMarks
  • noteText
  • setNoteText
  • noteProperties
  • setNoteProperties
  • convertNotes
  • bibliographySources
  • setBibliographySources
  • bibliographyStyle
  • setBibliographyStyle
  • suggestSourceTag
  • citationInstruction
  • insertCitation
  • insertBibliography
  • insertCaption (doc, blockIndex, 'above' | 'below', options) => WmlParagraph
  • captionLabels
  • addCaptionLabel
  • indexEntryInstruction
  • markIndexEntry
  • markAllIndexEntries
  • indexInstruction
  • insertIndex
  • markAuthorityCitation
  • insertTableOfAuthorities
  • CITATION_STYLES
  • SOURCE_TYPES
  • SOURCE_FIELDS
  • BIBLIOGRAPHY_TITLES
  • CAPTION_LABELS
  • AUTHORITY_CATEGORIES

Mailings

Envelopes, labels, and mail merge: data source settings, merge fields and rules, previewing a recipient, and merging to a new document.

  • addEnvelope
  • removeEnvelope
  • createLabelDocument (options) => Docx
  • updateLabels
  • mailMergeSettings
  • setMailMergeDocumentType
  • parseRecipientCsv
  • recipientListToCsv
  • attachRecipientList
  • autoFieldMap
  • mailMergeFieldMap
  • setMailMergeFieldMap
  • setRecipientInclusion
  • recipientInclusion
  • mergeFieldInstruction
  • insertMergeField
  • addressBlockInstruction
  • insertAddressBlock
  • greetingLineInstruction
  • insertGreetingLine
  • insertMergeRule
  • mergeFieldNames
  • mergeFieldErrors
  • previewMailMerge (doc, list, index | undefined, options?) => void
  • mergeToNewDocument (doc, list, options?) => Docx
  • ENVELOPE_SIZES
  • LABEL_PRODUCTS
  • ADDRESS_FIELDS
  • ADDRESS_NAME_FORMATS
  • GREETING_NAME_FORMATS

Browser preview (@office-kit/docx-preview)

The companion package's single entry point.

  • previewToDOM (source, container, options?) => Promise<Handle>