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? }?) => DocxopenDocx(bytes: Uint8Array) => DocxfromBlob(blob: Blob) => Promise<Docx>toUint8Array(doc: Docx) => Uint8ArraytoBlob(doc: Docx) => Blobclone(doc: Docx) => Docx
Paragraphs & blocks
Append, insert, and remove body paragraphs, headings, and breaks.
appendParagraphinsertParagraphAtremoveParagraphappendHeadingappendPageBreakappendLineBreakappendSectionBreakclearBodyparagraphs
Inline & text
Find and replace, runs and their formatting, paragraph alignment, indents, spacing, borders, and shading.
replaceTextreplaceTextEverywherefindTextfindTextEverywhereappendTextRunsetParagraphTextparagraphTextsetRunFormatclearRunFormatgetRunFormatHIGHLIGHT_COLORSreadonly HighlightColor[] — the only w:highlight values run-format writers acceptsetParagraphAlignmentgetParagraphAlignmentsetParagraphIndentsetParagraphSpacingsetParagraphBorderssetParagraphShadinggetParagraphStylegetParagraphNumberingmergeAdjacentRunsmergeAdjacentRunsInBodysetRunOnOffsetRunValPropgetRunPropsetParagraphOnOffsetParagraphValPropgetParagraphPropsplitParagraphAtmergeParagraphIntoPreviousrunTextLengthisolateParagraphRunRange
Styles & numbering
The style table, bullet and numbered lists, and lifting styles from a designed template.
addStyleremoveStylelistStylesensureHeadingStylesfindStyleIdByNamesetParagraphStyleaddBulletListaddNumberedListapplyListToParagraphmergeStylesFromTemplatesetStyleOnOffsetStyleValPropgetStylePropsetNumberingLevelOnOffsetNumberingLevelValgetNumberingLevelProp
Tables
Build tables and edit rows, cell text, borders, shading, and alignment.
addTabletablesremoveTableremoveAllTablesunwrapTableappendTableRowremoveTableRowsetTableRowAsHeadersetTableRowHeightsetTableBorderssetTableCellTextgetTableCellTextsetTableCellShadingsetTableCellVerticalAlign
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[][]tableColumnCounttableColumnWidthstableCellBlocksinsertTableRow(table, index, { formatFrom? }?) => WmlTableRowdeleteTableRowsinsertTableColumn(table, index, { widthTwips?, formatFrom? }?) => voiddeleteTableColumnsdeleteTableCells(table, range, 'left' | 'up') => voidmergeTableCells(table, range: TableCellRange) => voidsplitTableCell(table, row, cell, { columns, rows }) => voidsplitTable(doc, table, row) => WmlTablesetTableWidthsetTableAlignmentsetTableIndentsetTableLayoutsetTableCellSpacingsetTableDefaultCellMarginssetTableAltTextsetTablePositionsetTableCellWidthsetTableCellMarginssetTableCellTextDirectionsetTableColumnWidthdistributeTableColumnsautoFitTable(table, 'contents' | 'window' | 'fixed') => voidsetTableRangeBorders(table, range, edges, border?) => voidsortTableRows(table, { keys, headerRow? }) => voidconvertTextToTable(doc, first, last, { separator, columns? }) => WmlTableevaluateTableFormula(table, row, cell, formula) => numberformatFieldNumber
Table styles
Word's built-in table styles (Plain, Grid and List Tables), Table Style Options, and table style formatting.
BUILT_IN_TABLE_STYLESaddBuiltInTableStyle(doc, styleId) => voidbuiltInTableStylesetTableStylegetTableStylesetTableLook(table, look: TableLook) => voidgetTableLooksetTableStyleFormatting(doc, styleId, region, formatting) => void
Images
Add inline images, list the ones in a file, and replace them by part name or alt text.
addImageaddImageRuninsertImageIntoimagesimageReferencesreplaceImagereplaceImageByAltTextremoveAllImagesimageDrawingsgetImageInfosetImageAltTextsetImageSizeEmu
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) => DrawingInfoimagePixelSize(bytes) => ImagePixelSize | undefinedimageNaturalSizeEmu(bytes) => { widthEmu, heightEmu } | undefinedsetDrawingWrap(doc, index, wrap: WrapStyle, position?) => voidsetDrawingPosition(doc, index, { horizontal?, vertical? }) => voidsetDrawingAnchorOptions(doc, index, AnchorOptions) => voidarrangeDrawing(doc, index, op: DrawingOrder) => voidsetDrawingTransform(doc, index, { rotation?, flipH?, flipV? }) => voidsetDrawingName(doc, index, name) => voidsetDrawingHidden(doc, index, hidden) => voidsetDrawingAspectLock(doc, index, locked) => voidsetDrawingHyperlink(doc, index, url | undefined) => voidremoveDrawing(doc, index) => voidsetPictureCrop(doc, index, PictureCrop) => voidsetPictureGeometry(doc, index, preset: string) => voidsetPictureOutline(doc, index, PictureOutline | undefined) => voidsetPictureEffects(doc, index, PictureEffects) => voidsetPictureColorAdjustments(doc, index, PictureColorAdjustments) => voidchangePicture(doc, index, bytes, contentType?) => voidresetPicture(doc, index, { size? }?) => voidaddChartRun(doc, spec: ChartSpec, { widthEmu, heightEmu, name?, altText? }) => WmlRunreadChart(doc, drawing: XmlElement) => ChartSpec | undefinedsetChart(doc, index, spec: ChartSpec) => void
Comments, notes, hyperlinks, bookmarks
Review and navigation content: add it, list it, rewrite links, or strip it out.
addCommentaddFootnoteaddEndnoteremoveAllCommentsremoveAllFootnotesremoveAllEndnotesaddHyperlinkaddInternalHyperlinkexternalHyperlinkssetHyperlinkUrlremoveAllHyperlinksaddBookmarkremoveBookmarkremoveAllBookmarksbookmarks
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.
appendFieldaddTableOfContentsappendMergeFieldacceptAllRevisionsrejectAllRevisions
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? … }?) => numbercomplexFields(doc) => FieldInfo[]insertFormField(doc, paragraph, offset, FormFieldOptions) => WmlRun[]formatDatePicture(date, picture, locale?) => stringquoteFieldArgument(value) => stringinsertHyperlink(doc, paragraph, offset, text, { url? | bookmark?, tooltip?, targetFrame? }) => XmlElementparagraphHyperlinks(doc, paragraph) => HyperlinkInfo[]editHyperlinkremoveHyperlinkinsertBookmark(doc, name, start: TextPoint, end?: TextPoint) => numberisValidBookmarkName(name) => booleanensureReferenceBookmark(doc, paragraph, run?) => stringinsertSymbol(doc, paragraph, offset, SymbolSpec, rPr?) => WmlRuninsertEquation(doc, paragraph, offset, linear, { display? }?) => XmlElementbuildEquation(linear, { display? }?) => XmlElementequationLinear(element) => stringparagraphEquations(paragraph) => XmlElement[]setEquation(doc, paragraph, index, linear) => XmlElementgetDropCap(doc, paragraph) => DropCapOptionssetDropCap(doc, paragraph, { position, lines?, distanceTwips?, font? }) => voidinsertSignatureLine(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) => voidremoveCoverPage(doc) => booleanhasCoverPage(doc) => booleansetDifferentFirstPage(doc, on) => voidheaderFooterParagraphs(doc, kind, type?) => WmlParagraph[]setHeaderFooterParagraphs(doc, kind, type, paragraphs) => voidremoveHeaderFooter(doc, kind, type?) => booleanensureHeaderFooterStyle(doc, kind) => stringinsertPageNumbers(doc, { position, align, style? }) => voidremovePageNumbers(doc) => numbersetPageNumberFormat(doc, { format?, start?, chapterStyle?, chapterSeparator? }) => voidgetPageNumberFormat(doc) => PageNumberFormatOptionsPAGE_NUMBER_FORMATSCHAPTER_SEPARATORSinsertDocumentContent(doc, source: Docx, blockIndex) => number
Document properties
Core and app properties, with shortcuts for the title and the author.
corePropertiessetCorePropertiesappPropertiessetAppPropertiestitleauthorsetTitlesetAuthorgetDocumentSettingsetDocumentSettingOnOffsetDocumentSettingVal
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?) => XmlElementaddWordArt(doc, paragraph, { text, width, height, font?, size?, bold?, italic? }, index?) => XmlElementaddDrawingCanvas(doc, paragraph, { width, height }, index?) => XmlElementaddShapeToGroup(doc, group, options) => XmlElementvmlShapes(doc) => XmlElement[]runShape(run) => XmlElement | undefinedshapeKindshapePresetSHAPE_PRESETSSHAPE_CATEGORIESchangeShapePresetgetShapePointssetShapePointsgetShapeLayoutsetShapeLayoutgetShapeWrapsetShapeWrapsetShapeOrdersetShapeMoveWithTextgetShapeFillsetShapeFillvmlImageDataFILL_PATTERNSgetShapeStrokesetShapeStrokegetShapeShadowsetShapeShadowshapeTextsetShapeTextgetTextBoxLayoutsetTextBoxLayoutlinkTextBoxeslinkedTextBoxgetWordArtsetWordArtgetShapeAltTextsetShapeAltTextgetShapeNamesetShapeNameremoveShapegroupShapesungroupShapesgroupMembers
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?) => WmlRunsmartArts(doc) => SmartArtRef[]runSmartArt(doc, run) => SmartArtRef | undefinedgetSmartArtsetSmartArtNodessetSmartArtLayoutsetSmartArtColorssetSmartArtStylesetSmartArtSizeremoveSmartArtSMARTART_LAYOUTSSMARTART_COLORSSMARTART_STYLES
Diagnostics
Validate the package and read a document back: outline, fields, statistics, plain text.
validatevalidatePackagestatisticsoutlinefieldstext
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[]) => numberrejectRevisions(doc: Docx, ids: readonly string[]) => numberinsertTrackedTextdeleteTrackedTextparagraphMarkRevisiontrackParagraphMarktrackRunFormatChangetrackParagraphFormatChangecompareDocuments(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[]setCommentTextremoveCommentgetRunLanguagesetRunLanguagewordCount(doc: Docx, options?: WordCountOptions) => WordCountcheckAccessibility(doc: Docx) => AccessibilityIssue[]contrastRatio
Document protection
Restrict editing (with an optional password), editable exceptions, and Always Open Read-Only.
documentProtectionprotectDocument(doc: Docx, options: ProtectOptions) => voidunprotectDocument(doc: Docx, password: string) => booleanverifyProtectionPasswordwriteProtectionsetWriteProtectioneditableRangesaddEditableRangeremoveEditableRange
View & custom properties
The view and zoom a document opens with, and custom document properties.
documentViewsetDocumentViewdocumentZoomsetDocumentZoomcustomPropertiessetCustomPropertyremoveCustomProperty
Low-level part access
The parsed side parts, for when the functions above do not reach far enough.
stylesPartnumberingPartcommentsPartfootnotesPartendnotesPartxmlPartNamesgetRawPartRootmarkRawPartDirtychildElementsOfappendChildElementmakePropsElementgetElementAttrsetElementAttrgetElementPropsetElementOnOffsetElementValProp
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 | undefinedcontentControlBlocks(block: WmlBlock) => readonly WmlBlock[] | undefinedwrappedRuns(inline: WmlInline) => readonly WmlRun[] | undefinedstoryView(doc, ref: StoryRef) => Docx | undefinedstoryKey(ref: StoryRef) => stringparseStoryKey(key: string) => StoryRef | undefinedsectionProperties(doc) => Array<XmlElement | undefined>resolveHeaderFooter(doc, section, kind, type) => { partName, section } | undefinedensureHeaderFooter(doc, section, kind, type) => stringisHeaderFooterLinked(doc, section, kind, type) => booleansetHeaderFooterLinked(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) => voidsetRunUnderline(run, underline: UnderlineValue | undefined) => voidsetRunFont(run, script, font: FontChoice | undefined) => voidsetRunShading(run, shading: ShadingOptions | undefined) => voidsetRunBorder(run, line: BorderLine | undefined) => voidsetParagraphBorder(p, side, line: BorderLine | undefined) => voidsetParagraphTabs(p, tabs: TabStop[]) => voidgetParagraphTabs(p) => TabStop[]buildRubyRun(base, ruby, options, rPr?) => WmlRunreadRuby(run) => RubyInfo | undefinedbuildEnclosedCharacterRuns(text, options, rPr?) => WmlRun[]addListDefinition(doc, levels: ListLevel[]) => numberrestartList(doc, numId, ilvl, start) => number | undefinedensureBuiltinStyle(doc, styleId) => booleanbuiltinStyles() => BuiltinStyleInfo[]updateStyleFormatting(doc, styleId, { run?, paragraph? }) => booleanTHEME_COLORSUNDERLINE_STYLESSHADING_PATTERNSBORDER_LINE_STYLESRUBY_ALIGNMENTSENCLOSURESNUMBER_FORMATS
Page-size & margin constants
Ready-made values for setPageSize and setPageMargins, plus the library version.
PAGE_SIZE_A4PAGE_SIZE_LETTERMARGINS_NORMALVERSION
Section layout
Columns, line numbers, page borders, vertical alignment, document grid and section breaks, per section.
sectionCount(doc) => numbersectionIndexAt(doc, blockIndex) => numbergetSectionProperties(doc, section?) => SectionPropertiessetSectionProperties(doc, patch, scope?) => voidinsertSectionBreak(doc, blockIndex, start?) => numberPAGE_BORDER_LINE_STYLESreadonly string[] — line styles for page bordersPAGE_BORDER_ARTreadonly 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) => voidgetTheme(doc) => ThemeInfo | undefinedsetThemeColors(doc, colors: ThemeColorScheme) => voidsetThemeFonts(doc, fonts: ThemeFontScheme) => voidsetThemeEffects(doc, effects: ThemeEffectScheme) => voidthemeColorValue(colors, themeColor, { shade?, tint? }?) => string | undefinedapplyStyleSet(doc, set: StyleSetDefinition) => voidcurrentStyleSet(doc) => StyleSetDefinition | undefinedsetDefaultParagraphSpacing(doc, { before, after, line }) => voidgetDefaultParagraphSpacing(doc) => DefaultParagraphSpacing | undefinedsetPageColor(doc, color: PageColor | undefined) => voidgetPageColor(doc) => PageColor | undefinedsetWatermark(doc, watermark: Watermark | undefined) => voidgetWatermark(doc) => WatermarkInfo | undefinedTHEMESTHEME_COLOR_SCHEMESTHEME_COLOR_SLOTSTHEME_FONT_SCHEMESTHEME_EFFECT_SCHEMESSTYLE_SETSPARAGRAPH_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?) => voidtableOfContentsInstructionremoveTableOfContentssetTocLevel(doc, paragraph, level | 'none') => voidtocLevelupdateTables(doc, { types?, pageOf? }?) => numberinsertNote(doc, paragraph, offset, 'footnote' | 'endnote', options?) => numbernoteMarksnoteTextsetNoteTextnotePropertiessetNotePropertiesconvertNotesbibliographySourcessetBibliographySourcesbibliographyStylesetBibliographyStylesuggestSourceTagcitationInstructioninsertCitationinsertBibliographyinsertCaption(doc, blockIndex, 'above' | 'below', options) => WmlParagraphcaptionLabelsaddCaptionLabelindexEntryInstructionmarkIndexEntrymarkAllIndexEntriesindexInstructioninsertIndexmarkAuthorityCitationinsertTableOfAuthoritiesCITATION_STYLESSOURCE_TYPESSOURCE_FIELDSBIBLIOGRAPHY_TITLESCAPTION_LABELSAUTHORITY_CATEGORIES
Mailings
Envelopes, labels, and mail merge: data source settings, merge fields and rules, previewing a recipient, and merging to a new document.
addEnveloperemoveEnvelopecreateLabelDocument(options) => DocxupdateLabelsmailMergeSettingssetMailMergeDocumentTypeparseRecipientCsvrecipientListToCsvattachRecipientListautoFieldMapmailMergeFieldMapsetMailMergeFieldMapsetRecipientInclusionrecipientInclusionmergeFieldInstructioninsertMergeFieldaddressBlockInstructioninsertAddressBlockgreetingLineInstructioninsertGreetingLineinsertMergeRulemergeFieldNamesmergeFieldErrorspreviewMailMerge(doc, list, index | undefined, options?) => voidmergeToNewDocument(doc, list, options?) => DocxENVELOPE_SIZESLABEL_PRODUCTSADDRESS_FIELDSADDRESS_NAME_FORMATSGREETING_NAME_FORMATS
Browser preview (@office-kit/docx-preview)
The companion package's single entry point.
previewToDOM(source, container, options?) => Promise<Handle>