
@office-kit/docx is a JavaScript library for creating, reading, and editing Microsoft Word (.docx) documents in browsers and Node.js.
It can update an existing Word template, replace text across different document parts, and export the edited file while preserving unmodified OOXML content.
Features
- Create DOCX files with headings, paragraphs, lists, and tables.
- Format text, paragraph styles, page dimensions, and margins.
- Work with images, charts, shapes, headers, and footers.
- Replace text even when Word splits a match across formatting runs.
- Inspect comments, bookmarks, footnotes, and tracked changes.
- Edit table cells, rows, columns, and merged cells.
- Validate document packages and inspect text or metadata.
How To Use It
Installation
Install the core package through npm in a project that supports ESM imports.
npm install @office-kit/docx # Optional read-only preview npm install @office-kit/docx-preview # Optional command-based editor core npm install @office-kit/docx-editor
Basic Usage
Create a DOCX file when a button is clicked and download it from the browser. ensureHeadingStyles() defines the heading styles that appendHeading() uses.
<button type="button" id="download-docx">Download Word document</button>
import {
appendHeading,
appendParagraph,
createDocx,
ensureHeadingStyles,
toBlob,
} from "@office-kit/docx";
document.querySelector("#download-docx").addEventListener("click", () => {
const doc = createDocx({ paragraphs: [] });
ensureHeadingStyles(doc, 1);
appendHeading(doc, "Project Notes", 1);
appendParagraph(doc, "The design review is complete.");
const url = URL.createObjectURL(toBlob(doc));
const link = document.createElement("a");
link.href = url;
link.download = "project-notes.docx";
document.body.append(link);
link.click();
link.remove();
setTimeout(() => URL.revokeObjectURL(url), 10000);
});
Edit an Existing Word Template
Upload a DOCX template, replace {{name}} or {{company}}, and download the filled document. replaceTextEverywhere() examines the body, headers, footers, footnotes, endnotes, and comments. It recognizes matches split across formatting runs inside one paragraph.
<input id="docx-file" type="file" accept=".docx" />
import { fromBlob, replaceTextEverywhere, toBlob } from "@office-kit/docx";
const input = document.querySelector("#docx-file");
input.addEventListener("change", async () => {
const file = input.files?.[0];
if (!file) return;
try {
const doc = await fromBlob(file);
const fields = { name: "Marina Chen", company: "Northwind Studio" };
replaceTextEverywhere(doc, /\{\{(\w+)\}\}/g, (match) => {
return fields[match.captures[0] ?? ""] ?? "";
});
const url = URL.createObjectURL(toBlob(doc));
const link = document.createElement("a");
link.href = url;
link.download = "completed-template.docx";
document.body.append(link);
link.click();
link.remove();
setTimeout(() => URL.revokeObjectURL(url), 10000);
} catch (error) {
console.error("Unable to process the DOCX file:", error);
}
});
Create a Report with Tables and Lists
The core library accepts arrays of strings for simple bullet lists and tables. Set the document’s paper size and define heading styles before inserting report content.
import {
addBulletList,
addTable,
appendHeading,
createDocx,
ensureHeadingStyles,
PAGE_SIZE_A4,
setPageSize,
toUint8Array,
} from "@office-kit/docx";
const doc = createDocx({ paragraphs: [] });
setPageSize(doc, PAGE_SIZE_A4);
ensureHeadingStyles(doc, 1);
appendHeading(doc, "Monthly Summary", 1);
addBulletList(doc, ["Website redesign", "Product launch", "QA review"]);
addTable(doc, [
["Project", "Status"],
["Redesign", "Complete"],
["Launch", "In progress"],
]);
const bytes = toUint8Array(doc);
Reuse Styles from a Word Template
mergeStylesFromTemplate() copies style definitions from an existing DOCX. Place a file called report-template.docx in your application’s /templates/ directory before running this example.
By default, existing style IDs in the new document take precedence; { overwrite: true } uses the template’s definitions on conflicts.
This function copies styles, not the template’s entire page design or content.
import {
appendParagraph,
createDocx,
findStyleIdByName,
mergeStylesFromTemplate,
setParagraphStyle,
toUint8Array,
} from "@office-kit/docx";
const response = await fetch("/templates/report-template.docx");
if (!response.ok) throw new Error("Template could not be loaded");
const templateBytes = new Uint8Array(await response.arrayBuffer());
const doc = createDocx({ paragraphs: [] });
mergeStylesFromTemplate(doc, templateBytes);
const title = appendParagraph(doc, "Annual Review");
const styleId = findStyleIdByName(doc, "Report Title");
if (styleId) setParagraphStyle(title, styleId);
const output = toUint8Array(doc);
Render a Read-Only Browser Preview
@office-kit/docx-preview renders a Docx object or raw Uint8Array, ArrayBuffer, or Blob inside an HTML container.
Its browser renderer uses docx-preview and recognizes source-declared page breaks.
<div id="docx-preview"></div>
import { createDocx } from "@office-kit/docx";
import { previewToDOM } from "@office-kit/docx-preview";
const doc = createDocx({ paragraphs: ["A preview of the report."] });
const container = document.querySelector("#docx-preview");
const handle = await previewToDOM(doc, container);
window.addEventListener("pagehide", () => handle.dispose(), { once: true });
Preview Options
previewToDOM(source, container, options?) takes an HTML container and an optional configuration object. The promise resolves to a handle with an idempotent dispose() method.
classPrefix(string, default"wk-"): Prefix for generated CSS classes.inWrapper(boolean, defaulttrue): Use page wrappers in the preview.breakPages(boolean, defaulttrue): Respect page breaks stored in the DOCX file.renderFonts(boolean, defaulttrue): Inject declarations for embedded fonts.experimentalComments(boolean, defaultfalse): Enable experimental comment rendering.experimentalChanges(boolean, defaultfalse): Enable experimental tracked-change rendering.
Run Commands with the Optional Editor Core
@office-kit/docx-editor manages a document model, selection, and editing commands. An application must implement its own toolbar and editing interactions.
This snippet runs a formatting command and renders the current document into an HTML container.
<div id="word-editor-output"></div>
import {
commands,
openEditor,
renderDocumentHtml,
runCommand,
} from "@office-kit/docx-editor";
import { createDocx, toUint8Array } from "@office-kit/docx";
const source = createDocx({ paragraphs: ["Review text"] });
const model = openEditor(toUint8Array(source));
model.setSelection({
anchor: { block: 0 },
focus: { block: 0 },
});
runCommand(model, commands.toggleBoldCommand, undefined);
document.querySelector("#word-editor-output").innerHTML =
renderDocumentHtml(model.doc);
const outputBytes = toUint8Array(model.doc);
Validate the DOCX Package
validate(doc) returns validation issues with level, code, and message properties.
The function checks package consistency. Applications should handle invalid file input and exceptions from parsing separately.
import { createDocx, toUint8Array, validate } from "@office-kit/docx";
const doc = createDocx({ paragraphs: ["Hello, world."] });
const errors = validate(doc).filter((issue) => issue.level === "error");
if (errors.length > 0) {
console.error(errors);
} else {
const bytes = toUint8Array(doc);
console.log(`Generated ${bytes.length} bytes`);
}
Public API Reference
The core package exposes standalone functions and constants through @office-kit/docx.
Lifecycle
Create, load, copy, and export Word documents.
createDocx({ paragraphs? }?) => Docx: Create a Word document.openDocx(bytes: Uint8Array): Open an existing DOCX from bytes.fromBlob(blob: Blob): Read a browserBloborFileas a DOCX. ReturnsPromise<Docx>.toUint8Array(doc: Docx): Serialize the document toUint8Array.toBlob(doc: Docx): Serialize the document toBlob.clone(doc: Docx): Copy a document before independent edits.
Paragraphs & blocks
Manage body paragraphs, headings, and section or line breaks.
appendParagraph,insertParagraphAt,removeParagraph,appendHeading,appendPageBreak,appendLineBreak.appendSectionBreak,clearBody,paragraphs.
Inline & text
Inspect, find, replace, and format text and paragraphs.
replaceText,replaceTextEverywhere,findText,findTextEverywhere,appendTextRun,setParagraphText.paragraphText,setRunFormat,clearRunFormat,getRunFormat,HIGHLIGHT_COLORS,setParagraphAlignment.getParagraphAlignment,setParagraphIndent,setParagraphSpacing,setParagraphBorders,setParagraphShading,getParagraphStyle.getParagraphNumbering,mergeAdjacentRuns,mergeAdjacentRunsInBody,setRunOnOff,setRunValProp,getRunProp.setParagraphOnOff,setParagraphValProp,getParagraphProp,splitParagraphAt,mergeParagraphIntoPrevious,runTextLength.isolateParagraphRunRange.
Styles & numbering
Manage custom styles, list formatting, and numbering definitions.
addStyle,removeStyle,listStyles,ensureHeadingStyles,findStyleIdByName,setParagraphStyle.addBulletList,addNumberedList,applyListToParagraph,mergeStylesFromTemplate,setStyleOnOff,setStyleValProp.getStyleProp,setNumberingLevelOnOff,setNumberingLevelVal,getNumberingLevelProp.
Tables
Create and inspect tables, rows, cells, and table formatting.
addTable,tables,removeTable,removeAllTables,unwrapTable,appendTableRow.removeTableRow,setTableRowAsHeader,setTableRowHeight,setTableBorders,setTableCellText,getTableCellText.setTableCellShading,setTableCellVerticalAlign.
Table layout
Control row and column structure, merges, dimensions, sorting, and formulas.
tableCellPlacements,tableColumnCount,tableColumnWidths,tableCellBlocks,insertTableRow,deleteTableRows.insertTableColumn,deleteTableColumns,deleteTableCells,mergeTableCells,splitTableCell,splitTable.setTableWidth,setTableAlignment,setTableIndent,setTableLayout,setTableCellSpacing,setTableDefaultCellMargins.setTableAltText,setTablePosition,setTableCellWidth,setTableCellMargins,setTableCellTextDirection,setTableColumnWidth.distributeTableColumns,autoFitTable,setTableRangeBorders,sortTableRows,convertTextToTable,evaluateTableFormula.formatFieldNumber.
Table styles
Apply and configure built-in or custom table styles.
BUILT_IN_TABLE_STYLES,addBuiltInTableStyle,builtInTableStyle,setTableStyle,getTableStyle,setTableLook.getTableLook,setTableStyleFormatting.
Images
Insert, locate, resize, and replace images.
addImage,addImageRun,insertImageInto,images,imageReferences,replaceImage.replaceImageByAltText,removeAllImages,imageDrawings,getImageInfo,setImageAltText,setImageSizeEmu.
Pictures, charts & arrangement
Edit drawing placement, image effects, crop, and embedded charts.
readDrawing,imagePixelSize,imageNaturalSizeEmu,setDrawingWrap,setDrawingPosition,setDrawingAnchorOptions.arrangeDrawing,setDrawingTransform,setDrawingName,setDrawingHidden,setDrawingAspectLock,setDrawingHyperlink.removeDrawing,setPictureCrop,setPictureGeometry,setPictureOutline,setPictureEffects,setPictureColorAdjustments.changePicture,resetPicture,addChartRun,readChart,setChart.
Headers, footers, sections
Manage header and footer content plus basic page setup.
addHeader,addFooter,addPageNumberFooter,setPageSize,setPageMargins,setPageOrientation.headers,footers,removeAllHeaders,removeAllFooters.
Comments, notes, hyperlinks, bookmarks
Insert or remove review annotations, notes, links, and bookmarks.
addComment,addFootnote,addEndnote,removeAllComments,removeAllFootnotes,removeAllEndnotes.addHyperlink,addInternalHyperlink,externalHyperlinks,setHyperlinkUrl,removeAllHyperlinks,addBookmark.removeBookmark,removeAllBookmarks,bookmarks.
Fields & tracked changes
Insert fields and resolve tracked revisions.
appendField,addTableOfContents,appendMergeField,acceptAllRevisions,rejectAllRevisions.
Insert at a position
Insert fields, links, symbols, equations, bookmarks, and signatures at character offsets.
insertField,buildComplexField,updateFields,complexFields,insertFormField,formatDatePicture.quoteFieldArgument,insertHyperlink,paragraphHyperlinks,editHyperlink,removeHyperlink,insertBookmark.isValidBookmarkName,ensureReferenceBookmark,insertSymbol,insertEquation,buildEquation,equationLinear.paragraphEquations,setEquation,getDropCap,setDropCap,insertSignatureLine.
Pages, headers & page numbers
Configure cover pages, page numbering, and header/footer contents.
insertCoverPage,removeCoverPage,hasCoverPage,setDifferentFirstPage,headerFooterParagraphs,setHeaderFooterParagraphs.removeHeaderFooter,ensureHeaderFooterStyle,insertPageNumbers,removePageNumbers,setPageNumberFormat,getPageNumberFormat.PAGE_NUMBER_FORMATS,CHAPTER_SEPARATORS,insertDocumentContent.
Document properties
Read and write document metadata and settings.
coreProperties,setCoreProperties,appProperties,setAppProperties,title,author.setTitle,setAuthor,getDocumentSetting,setDocumentSettingOnOff,setDocumentSettingVal.
Shapes, text boxes, WordArt & ink (VML)
Work with Word shapes, text boxes, drawing groups, and WordArt.
addShape,addWordArt,addDrawingCanvas,addShapeToGroup,vmlShapes,runShape.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 and change SmartArt layouts, content, colors, and sizes.
addSmartArt,smartArts,runSmartArt,getSmartArt,setSmartArtNodes,setSmartArtLayout.setSmartArtColors,setSmartArtStyle,setSmartArtSize,removeSmartArt,SMARTART_LAYOUTS,SMARTART_COLORS.SMARTART_STYLES.
Diagnostics
Validate DOCX packages and inspect statistics, text, fields, and document outline.
validate,validatePackage,statistics,outline,fields,text.
Review: tracked changes
Inspect tracked changes, accept or reject revisions, and compare documents.
revisions,acceptRevisions,rejectRevisions,insertTrackedText,deleteTrackedText,paragraphMarkRevision.trackParagraphMark,trackRunFormatChange,trackParagraphFormatChange,compareDocuments.
Review: comments, proofing, accessibility
Work with comments, language settings, word counts, and accessibility checks.
comments,setCommentText,removeComment,getRunLanguage,setRunLanguage,wordCount.checkAccessibility,contrastRatio.
Document protection
Configure editing restrictions and protected regions.
documentProtection,protectDocument,unprotectDocument,verifyProtectionPassword,writeProtection,setWriteProtection.editableRanges,addEditableRange,removeEditableRange.
View & custom properties
Control saved view settings, zoom, and custom metadata.
documentView,setDocumentView,documentZoom,setDocumentZoom,customProperties,setCustomProperty.removeCustomProperty.
Low-level part access
Work with XML and related OOXML parts through exported helpers.
stylesPart,numberingPart,commentsPart,footnotesPart,endnotesPart,xmlPartNames.getRawPartRoot,markRawPartDirty,childElementsOf,appendChildElement,makePropsElement,getElementAttr.setElementAttr,getElementProp,setElementOnOff,setElementValProp.
Stories & section headers
Read and edit headers, footers, notes, and other document stories.
storyBody,contentControlBlocks,wrappedRuns,storyView,storyKey,parseStoryKey.sectionProperties,resolveHeaderFooter,ensureHeaderFooter,isHeaderFooterLinked,setHeaderFooterLinked.
Character & paragraph formatting
Apply Word-level character, paragraph, and style formatting.
setRunColor,setRunUnderline,setRunFont,setRunShading,setRunBorder,setParagraphBorder.setParagraphTabs,getParagraphTabs,buildRubyRun,readRuby,buildEnclosedCharacterRuns,addListDefinition.restartList,ensureBuiltinStyle,builtinStyles,updateStyleFormatting,THEME_COLORS,UNDERLINE_STYLES.SHADING_PATTERNS,BORDER_LINE_STYLES,RUBY_ALIGNMENTS,ENCLOSURES,NUMBER_FORMATS.
Page-size & margin constants
Ready-to-use page dimensions, margins, and version constant.
PAGE_SIZE_A4,PAGE_SIZE_LETTER,MARGINS_NORMAL,VERSION.
Section layout
Configure section properties, breaks, columns, and page borders.
sectionCount,sectionIndexAt,getSectionProperties,setSectionProperties,insertSectionBreak,PAGE_BORDER_LINE_STYLES.PAGE_BORDER_ART.
Design: themes, style sets, page background
Configure themes, style sets, page background, and watermarks.
setTheme,getTheme,setThemeColors,setThemeFonts,setThemeEffects,themeColorValue.applyStyleSet,currentStyleSet,setDefaultParagraphSpacing,getDefaultParagraphSpacing,setPageColor,getPageColor.setWatermark,getWatermark,THEMES,THEME_COLOR_SCHEMES,THEME_COLOR_SLOTS,THEME_FONT_SCHEMES.THEME_EFFECT_SCHEMES,STYLE_SETS,PARAGRAPH_SPACING_PRESETS.
References
Create and manage citations, notes, contents pages, indexes, and captions.
insertTableOfContents,tableOfContentsInstruction,removeTableOfContents,setTocLevel,tocLevel,updateTables.insertNote,noteMarks,noteText,setNoteText,noteProperties,setNoteProperties.convertNotes,bibliographySources,setBibliographySources,bibliographyStyle,setBibliographyStyle,suggestSourceTag.citationInstruction,insertCitation,insertBibliography,insertCaption,captionLabels,addCaptionLabel.indexEntryInstruction,markIndexEntry,markAllIndexEntries,indexInstruction,insertIndex,markAuthorityCitation.insertTableOfAuthorities,CITATION_STYLES,SOURCE_TYPES,SOURCE_FIELDS,BIBLIOGRAPHY_TITLES,CAPTION_LABELS.AUTHORITY_CATEGORIES.
Mailings
Prepare mail merge fields, recipients, envelopes, labels, and merged documents.
addEnvelope,removeEnvelope,createLabelDocument,updateLabels,mailMergeSettings,setMailMergeDocumentType.parseRecipientCsv,recipientListToCsv,attachRecipientList,autoFieldMap,mailMergeFieldMap,setMailMergeFieldMap.setRecipientInclusion,recipientInclusion,mergeFieldInstruction,insertMergeField,addressBlockInstruction,insertAddressBlock.greetingLineInstruction,insertGreetingLine,insertMergeRule,mergeFieldNames,mergeFieldErrors,previewMailMerge.mergeToNewDocument,ENVELOPE_SIZES,LABEL_PRODUCTS,ADDRESS_FIELDS,ADDRESS_NAME_FORMATS,GREETING_NAME_FORMATS.
Browser preview (@office-kit/docx-preview)
Render Word files into a browser container and release the preview when it is no longer needed.
previewToDOM(source, container, options?): Returns aPromise<Handle>with adispose()method.
Alternatives & Related Resources
- Lightweight MS Office Document to HTML Parser – Envelope
- Extract Text From Documents (PDF, DOC, XLS, PPT, etc) – docsToText
FAQs
Q: Why does a heading look like ordinary text after export?
A: appendHeading() assigns a Word heading style. Call ensureHeadingStyles(doc) when creating a document that does not yet define that style.
Q: Why is a template placeholder not replaced?
A: replaceTextEverywhere() matches across Word formatting runs inside a paragraph. It does not match a token broken across two paragraphs. Check the token spelling and regular expression as well.
Q: How do I generate different DOCX files from one template?
A: Open the template once and call clone(template) for each recipient. Replace that recipient’s tokens in the copy and serialize the result.
Q: What happens when I try to load a non-DOCX file?
A: openDocx() and fromBlob() expect valid DOCX input. Handle parsing errors with try/catch and check the output with validate() before distributing generated documents.
Q: Can the library convert Word documents to PDF?
A: No. PDF rendering and legacy binary .doc input are outside the project’s scope.







