or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

advanced-layout.mdcontent-elements.mddocument-creation.mddocument-export.mddocument-patching.mdindex.mdstyling-formatting.mdutility-functions.md
tile.json

index.mddocs/

Docx

Docx 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.

Package Information

  • Package Name: docx
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install docx

Core Imports

import { Document, Packer, Paragraph, TextRun } from "docx";

For CommonJS:

const { Document, Packer, Paragraph, TextRun } = require("docx");

Basic Usage

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);
});

Architecture

Docx is built around several key components:

  • Document Model: Core Document class representing the entire Word document with sections, properties, and content
  • Content Elements: Rich set of content classes (Paragraph, Table, TextRun, ImageRun) for document structure
  • Formatting System: Comprehensive formatting options including styles, fonts, alignment, and borders
  • Export Engine: Packer class providing multiple output formats (Buffer, Blob, Stream, etc.)
  • Template System: Patcher functionality for modifying existing Word documents
  • Type System: Full TypeScript integration with extensive interfaces and type definitions

Capabilities

Document Creation and Management

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;
  };
}

Document Creation

Content Elements

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);
}

Content Elements

Document Export

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;
}

Document Export

Styling and Formatting

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;

Styling and Formatting

Document Patching

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[];
}

Document Patching

Utility Functions

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;

Utility Functions

Advanced Layout Features

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;

Advanced Layout Features

Core Types

Measurement Types

type UniversalMeasure = `${"-" | ""}${number}${"mm" | "cm" | "in" | "pt" | "pc" | "pi"}`;
type PositiveUniversalMeasure = `${number}${"mm" | "cm" | "in" | "pt" | "pc" | "pi"}`;
type Percentage = `${"-" | ""}${number}%`;

Content Type Unions

type ParagraphChild =
  | TextRun
  | ImageRun
  | SymbolRun
  | Bookmark
  | PageBreak
  | ColumnBreak
  | SequentialIdentifier
  | FootnoteReferenceRun
  | InternalHyperlink
  | ExternalHyperlink
  | InsertedTextRun
  | DeletedTextRun
  | Math
  | SimpleField
  | CheckBox;

type FileChild =
  | Paragraph
  | Table
  | TableOfContents;

Output Types

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;