Easily generate .docx files with JS/TS with a nice declarative API. Works for Node and on the Browser.
npx @tessl/cli install tessl/npm-docx@9.5.0Docx is a comprehensive TypeScript library for programmatically creating and manipulating Microsoft Word documents (.docx files). It provides a declarative API that enables developers to generate complex documents with paragraphs, tables, images, headers, footers, and various formatting options. The library works seamlessly in both Node.js server environments and browser environments.
npm install docximport { Document, Packer, Paragraph, TextRun } from "docx";For CommonJS:
const { Document, Packer, Paragraph, TextRun } = require("docx");import { Document, Packer, Paragraph, TextRun } from "docx";
import * as fs from "fs";
// Create a document
const doc = new Document({
sections: [{
properties: {},
children: [
new Paragraph({
children: [
new TextRun("Hello World"),
new TextRun({
text: "This is bold text",
bold: true,
}),
],
}),
],
}],
});
// Generate the document
Packer.toBuffer(doc).then((buffer) => {
fs.writeFileSync("My Document.docx", buffer);
});Docx is built around several key components:
Document class representing the entire Word document with sections, properties, and contentParagraph, Table, TextRun, ImageRun) for document structurePacker class providing multiple output formats (Buffer, Blob, Stream, etc.)Core document creation functionality including sections, properties, and metadata management.
class Document {
constructor(options: IPropertiesOptions);
}
interface IPropertiesOptions {
readonly sections: readonly ISectionOptions[];
readonly title?: string;
readonly subject?: string;
readonly creator?: string;
readonly keywords?: string;
readonly description?: string;
readonly styles?: IStylesOptions;
readonly numbering?: INumberingOptions;
readonly background?: IDocumentBackgroundOptions;
readonly features?: {
readonly trackRevisions?: boolean;
readonly updateFields?: boolean;
};
}Rich content elements for building document structure including paragraphs, text runs, images, and tables.
class Paragraph {
constructor(options: string | IParagraphOptions);
addRunToFront(run: Run): Paragraph;
}
class TextRun {
constructor(options: IRunOptions | string);
}
class Table {
constructor(options: ITableOptions);
}Document export functionality with multiple output formats and customization options.
class Packer {
static pack<T>(file: Document, type: T, prettify?: PrettifyType, overrides?: any): Promise<OutputByType[T]>;
static toString(file: Document, prettify?: PrettifyType, overrides?: any): Promise<string>;
static toBuffer(file: Document, prettify?: PrettifyType, overrides?: any): Promise<Buffer>;
static toBase64String(file: Document, prettify?: PrettifyType, overrides?: any): Promise<string>;
static toBlob(file: Document, prettify?: PrettifyType, overrides?: any): Promise<Blob>;
static toArrayBuffer(file: Document, prettify?: PrettifyType, overrides?: any): Promise<ArrayBuffer>;
static toStream(file: Document, prettify?: PrettifyType, overrides?: any): Stream;
}Comprehensive styling and formatting system including text formatting, alignment, borders, and custom styles.
const AlignmentType = {
START: "start",
CENTER: "center",
END: "end",
BOTH: "both",
LEFT: "left",
RIGHT: "right",
JUSTIFIED: "both"
} as const;
const HeadingLevel = {
HEADING_1: "Heading1",
HEADING_2: "Heading2",
HEADING_3: "Heading3",
HEADING_4: "Heading4",
HEADING_5: "Heading5",
HEADING_6: "Heading6",
TITLE: "Title"
} as const;
const UnderlineType = {
SINGLE: "single",
WORDS: "words",
DOUBLE: "double",
THICK: "thick",
DOTTED: "dotted",
DASH: "dash",
WAVE: "wave",
NONE: "none"
} as const;Advanced functionality for modifying existing Word documents with new content while preserving structure.
function patchDocument<T extends PatchDocumentOutputType = PatchDocumentOutputType>(
options: PatchDocumentOptions<T>
): Promise<OutputByType[T]>;
function patchDetector(options: { readonly data: InputDataType }): Promise<readonly string[]>;
type IPatch = ParagraphPatch | FilePatch;
interface ParagraphPatch {
readonly type: "paragraph";
readonly children: readonly ParagraphChild[];
}
interface FilePatch {
readonly type: "file";
readonly children: readonly FileChild[];
}Helper functions for measurement conversion, ID generation, and value formatting.
function convertMillimetersToTwip(millimeters: number): number;
function convertInchesToTwip(inches: number): number;
function uniqueId(): string;
function hashedId(data: Buffer | string | Uint8Array | ArrayBuffer): string;
function uniqueUuid(): string;Advanced layout and formatting features including numbering systems, tab stops, page layout, and positioning controls for complex document structures.
const NumberFormat = {
DECIMAL: "decimal",
UPPER_ROMAN: "upperRoman",
LOWER_ROMAN: "lowerRoman",
UPPER_LETTER: "upperLetter",
LOWER_LETTER: "lowerLetter",
BULLET: "bullet"
} as const;
const TabStopType = {
LEFT: "left",
RIGHT: "right",
CENTER: "center",
DECIMAL: "decimal"
} as const;
const PageOrientation = {
PORTRAIT: "portrait",
LANDSCAPE: "landscape"
} as const;type UniversalMeasure = `${"-" | ""}${number}${"mm" | "cm" | "in" | "pt" | "pc" | "pi"}`;
type PositiveUniversalMeasure = `${number}${"mm" | "cm" | "in" | "pt" | "pc" | "pi"}`;
type Percentage = `${"-" | ""}${number}%`;type ParagraphChild =
| TextRun
| ImageRun
| SymbolRun
| Bookmark
| PageBreak
| ColumnBreak
| SequentialIdentifier
| FootnoteReferenceRun
| InternalHyperlink
| ExternalHyperlink
| InsertedTextRun
| DeletedTextRun
| Math
| SimpleField
| CheckBox;
type FileChild =
| Paragraph
| Table
| TableOfContents;type OutputByType = {
readonly base64: string;
readonly string: string;
readonly text: string;
readonly binarystring: string;
readonly array: readonly number[];
readonly uint8array: Uint8Array;
readonly arraybuffer: ArrayBuffer;
readonly blob: Blob;
readonly nodebuffer: Buffer;
};
type OutputType = keyof OutputByType;