Files
docx/docs/usage/styling-with-js.md
T
DolanandClaude Opus 5.5 c169dd1a83 feat: live examples in the docs, which run, draw the document next to the code, and can be edited and downloaded (#3556)
* feat: live examples in the docs, which run, draw the document next to the code, and can be edited and downloaded

The docs' code examples were plain snippets, often fragments that couldn't run. A code block marked ```ts live is now
an example readers can see and change: the page runs it with docx, draws the document it makes next to the code with
docx-preview, and offers the .docx to download. Clicking the code opens an editor (Monaco) that knows docx's types,
the pages are drawn again as the code changes, and View closes the editor. Split, Code and Preview show the code and
the pages side by side, or one of them. The demos a page includes are live too.

Every example in the docs that builds or patches a document is now live: 443 of them, each a whole file with its
imports, so it runs as written. Code about other things, such as installing, bundlers or servers, stays plain.

Running them showed docs that were wrong, fixed here:
- Landscape: docx swaps a landscape page's width and height itself, so the docs' swapped sizes made a tall page
  marked as landscape
- Comments: `comments.children` takes plain objects, not `new Comment(...)`
- Custom properties are text only
- APIs that no longer exist: MathText, Row, `.then` on Packer.toStream, patchDocument(buffer, ...),
  createParagraph().heading1(), a border's `value`, TextRun's `.break()`
- The templates and patcher examples read files that aren't in the repository. They now patch the templates in
  demo/assets, or make their own

`npm run build.docs` copies docx's browser builds into docs/live-examples/lib, so the docs use the docx they
describe, and the Pages workflow runs it. The folder is gitignored, and cspell and ESLint skip it.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TmyffPd5QMJYjXiMBQ3EnZ

* docs: the bullet examples draw a bullet, and the patcher's usage writes the patched document

"ὠ" is U+1F60, a Greek omega, since \u takes four hex digits, so the two live bullet examples on
the numbering page drew it as each item's bullet. They use "•" now. The patcher's usage example
now awaits patchDocument and writes the document it makes, as the example after it does.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TmyffPd5QMJYjXiMBQ3EnZ

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 13:00:29 +01:00

11 KiB

Styling with JS

Example

import { AlignmentType, Document, HeadingLevel, Paragraph, TextRun } from "docx";

const para = new Paragraph({
    text: "To whom it may concern:",
    heading: HeadingLevel.HEADING_2,
    alignment: AlignmentType.CENTER,
});

const name = new TextRun({
    text: "Name:",
    bold: true,
    font: "Calibri",
    allCaps: true,
});

const doc = new Document({
    sections: [
        {
            children: [para, new Paragraph({ children: [name] })],
        },
    ],
});

Available Options

Run formatting

  • bold, italics, smallCaps, allCaps, strike, doubleStrike, subScript, superScript: Set the formatting property to true
  • underline({type="single", color=null}): Set the underline style and color
  • emphasisMark({type="dot"}): Set the emphasis mark style
  • color(color): Set the text color, using 6 hex characters for RRGGBB (no leading #)
  • size(halfPts): Set the font size, measured in half-points
  • font(name) or font({ascii, cs, eastAsia, hAnsi, hint}): Set the run's font, or font({ theme: "headings" }) or font({ theme: "body" }) for one of the fonts of the document's theme
  • style(name): Apply a named run style
  • characterSpacing(value): Set the character spacing adjustment (in TWIPs)

Paragraph formatting

  • heading1, heading2, heading3, heading4, heading5, title: apply the appropriate style to the paragraph
  • left, center, right, justified: set the paragraph's alignment
  • thematicBreak, pageBreak: Insert a thick rule or a page break beneath the paragraph
  • leftTabStop(position): Add a left tab stop (measured in TWIPs from the left)
  • maxRightTabStop: Add a right tab stop at the far right
  • bullet: Use the default bullet style
  • setNumbering(numbering, indentLevel): Use a custom numbering format for the paragraph
  • style(name): Apply a named paragraph style
  • indent(start, hanging=0): Set the paragraph's indent level (in TWIPs)
  • spacing({before=0, after=0, line=0}): Set the line and before/after on the paragraph. Before/after is measured in TWIPs, line is measured in 240ths of a line

Paragraph styles have all the run formatting methods, except style(), and left(), center(), right(), justified(), thematicBreak(), leftTabStop(position), maxRightTabStop(), indent(start, hanging=0), and spacing({before=0, after=0, line=0}) methods.

Detailed guide

There are 4 items in docx that can be styled:

  • Characters: Attributes that can change within a paragraph. e.g., bold, italics, etc.
  • Paragraphs: Attributes like indent, text alignment, line spacing, etc.
  • Tables: Border styles, table formats, etc.
  • List items: These are the numbers and bullets that are automatically inserted

There are a few different ways of styling this content in docx, which somewhat resemble the HTML/CSS approach. In order of greatest to lowest priority:

  1. Direct formatting (inline formatting)
  2. Declarative Styles (similar to external CSS)
  3. Document defaults (similar to a * rule in CSS)

Unlike CSS, less specific rules don't necessarily override parent rules. The rules are a bit wonky, but if you're interested, see the [advanced formatting section](#Advanced formatting).

Direct formatting (inline formatting)

This is the type of formatting that your uncle uses when he types out documents: N ... a ... m ... e ... : Then he grabs the mouse, highlights Name: and moves over to the B for bold. This manner of formatting results in markup that is similar to writing <span style="bold: true">Name:</span> if you were typing out HTML. docx (the format) allows you to specify this for any of the four types of items. docx (the library) only supports this type of formatting for paragraphs and characters, using a fluent api. Thus you could do:

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

const name = new TextRun({
    text: "Name:",
    bold: true,
    font: "Calibri",
    allCaps: true,
});

const doc = new Document({
    sections: [
        {
            children: [new Paragraph({ children: [name, new TextRun(" Clippy")] })],
        },
    ],
});

Or for paragraph formatting:

import { AlignmentType, Document, HeadingLevel, Paragraph } from "docx";

const para = new Paragraph({
    text: "To whom it may concern:",
    heading: HeadingLevel.HEADING_2,
    alignment: AlignmentType.CENTER,
});

const doc = new Document({
    sections: [
        {
            children: [para],
        },
    ],
});

Declarative Styles (similar to external CSS)

docx files contain a styles section separate from the main content, much like how HTML includes CSS files. Unlike CSS, docx distinguishes between styles meant for tables (which show up in the table formatting toolbar), styles for lists (which show up under bullets and numbering), and styles for runs and paragraphs, which show up as dropdowns offering standard styles, like "Heading 1", "Caption", or any custom styles defined in that document. . docx allows you to define these styles using a fluent interface as well.

To add styles, define your custom styles in the document:

import { Document, HeadingLevel, Paragraph, UnderlineType } from "docx";

// The first argument is an ID you use to apply the style to paragraphs
// The second argument is a human-friendly name to show in the UI
const doc = new Document({
    creator: "Clippy",
    title: "Sample Document",
    description: "A brief example of using docx",
    styles: {
        paragraphStyles: [
            {
                id: "myWonkyStyle",
                name: "My Wonky Style",
                basedOn: "Normal",
                next: "Normal",
                quickFormat: true,
                run: {
                    italics: true,
                    color: "999999",
                },
                paragraph: {
                    spacing: {
                        line: 276,
                    },
                    indent: {
                        left: 720,
                    },
                },
            },
            {
                id: "Heading2",
                name: "Heading 2",
                basedOn: "Normal",
                next: "Normal",
                quickFormat: true,
                run: {
                    size: 26,
                    bold: true,
                    color: "999999",
                    underline: {
                        type: UnderlineType.DOUBLE,
                        color: "FF0000",
                    },
                },
                paragraph: {
                    spacing: {
                        before: 240,
                        after: 120,
                    },
                },
            },
        ],
    },
    sections: [
        {
            children: [
                new Paragraph({
                    text: "A heading in the Heading 2 style",
                    heading: HeadingLevel.HEADING_2,
                }),
                new Paragraph({
                    text: "A paragraph in My Wonky Style",
                    style: "myWonkyStyle",
                }),
            ],
        },
    ],
});

Note: If you are using the .headingX or .title methods of paragraphs, you must make sure to define HeadingX or Title styles for these. Otherwise they'll show up un-styled :(. If you are using the .bullet or .setNumbering methods, you need to define a ListParagraph style or the numbers may not show up.

Document defaults

Setting document defaults acts like a * rule in CSS: it applies to every paragraph and run in the document, but at a low priority level. Other styles affecting this property will override these defaults.

The Normal style

Paragraphs that don't name a style use the default paragraph style, Normal, which the headings and other built-in styles are based on. docx writes a Normal with no formatting of its own, so paragraphs take the document defaults. To format it, give a paragraph style with the id Normal. It takes the place of docx's and stays the default:

import { Document, Paragraph } from "docx";

const doc = new Document({
    styles: {
        paragraphStyles: [{ id: "Normal", name: "Normal", run: { font: "Calibri", size: 22 } }],
    },
    sections: [
        {
            children: [new Paragraph("A paragraph in the Normal style, in 11 point Calibri")],
        },
    ],
});

Advanced formatting

Style inheritance

Styles may define a basedOn attribute that references another style of the same type. In this case, any unspecified properties are inherited from the parent style.

Interactions between the 4 items

In addition to the 3-layer hierarchy spelled above, there is some interaction between the 4 items that you can style. For instance numbering styles may also specify some styling for paragraphs (typically indentation and tab stops); paragraphs may specify character formatting (e.g., heading font sizes); etc.

The elements that each style may affect are summarized in the table below. So, e.g., table styles may specify table formatting, paragraph formatting, and character formatting.

Style type Table Paragraph List item Characters
Document defaults X X
Table X X X
Paragraph X X X
Numbering X X
Character X
Direct formatting X X X X

To determine the value of a styling property, you must first identify whether it's a table, paragraph, list item, or character property. E.g., numbering definition is a list item property. Then you need to find the last row in the table for which that property has an "X" and the document has formatting of that type. So if a particular run was in a paragraph whose style specified color as FF0000, but it also had a character style specifying color as 00DD00, then the character style (lower down on the table) would trump, and the character would have color 00DD00.

Toggle properties

The following properties are treated in a special manner; they're called toggle properties:

  • Bold
  • All caps
  • Small caps
  • Italics
  • Single strike-through
  • Hidden
  • Imprint
  • Emboss
  • Character outline
  • Character shadow

For these properties, the rules state the following conflict resolution in case the property is specified at multiple points for the same item:

  • Direct formatting trumps all if specified (either true or false)
  • Otherwise, if the property is true in document defaults, the property is set to true
  • Otherwise, the property's value is an XOR of its effective table, paragraph, and character values. (So specifying bold true on a table style and a paragraph style would result in non-bold text if a paragraph inside the table had that style)

Examples

Declarative styles

Importing Images from file system path

Example

Source: https://github.com/dolanmiu/docx/blob/master/demo/styles/default-styles.ts