Files
docx/docs/usage/paragraph.md
T
DolanandClaude Opus 5.5 2243d74c22 fix: write one w:pStyle for a paragraph with both heading and style (#3940)
A paragraph with both `heading` and `style` wrote a w:pStyle for each, and
CT_PPrBase has one, so the Open XML SDK validator rejected the document.
Word applies the last of the two, `style`, so `style` now takes the place
of `heading`, and Word shows the paragraph as it did. The layout module and
the table of contents' heading entries read the first w:pStyle, the
heading, and now read the style Word shows.

The ListParagraph that a bullet or numbered paragraph gets without a style
of its own goes in the same if/else.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 17:36:05 +08:00

30 KiB
Raw Permalink Blame History

Paragraph

Everything (text, images, graphs etc) in OpenXML is organized in paragraphs.

!> Paragraphs requires an understanding of Sections.

You can create Paragraphs in the following ways:

Shorthand

import { Document, Paragraph } from "docx";

const doc = new Document({
    sections: [
        {
            children: [new Paragraph("Short hand Hello World")],
        },
    ],
});

Children Method

This method is useful for adding different text with different styles, symbols, or adding images inline.

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

const doc = new Document({
    sections: [
        {
            children: [
                new Paragraph({
                    children: [new TextRun("Lorem Ipsum Foo Bar"), new TextRun("Hello World"), new SymbolRun("F071")],
                }),
            ],
        },
    ],
});

Explicit

import { Document, Paragraph } from "docx";

const doc = new Document({
    sections: [
        {
            children: [
                new Paragraph({
                    text: "Short hand notation for adding text.",
                }),
            ],
        },
    ],
});

After you create the paragraph, you must add the paragraph into a section:

import { Document, Paragraph } from "docx";

const paragraph = new Paragraph("Hello World");

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

Or the preferred convention, define the paragraph inside the section and remove the usage of variables:

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

const doc = new Document({
    sections: [
        {
            children: [
                new Paragraph({
                    children: [new TextRun("Lorem Ipsum Foo Bar"), new TextRun("Hello World")],
                }),
            ],
        },
    ],
});

Changing a Paragraph's Options

with makes a new paragraph with a paragraph's options and the ones you give, which take the place of its own. This is useful for paragraphs made elsewhere, such as by a parser of Markdown or LaTeX, that you want to lay out differently. The paragraph itself is left as it is, and the new one has the same children.

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

// Paragraphs made elsewhere, such as by a parser
const parsed = [
    new Paragraph("Hello"),
    new Paragraph({ children: [new TextRun({ text: "World!", bold: true })], spacing: { after: 480 } }),
];

const doc = new Document({
    sections: [
        {
            children: parsed.map((paragraph) =>
                paragraph.with({
                    indent: { left: 720, right: 720 },
                    // The paragraph's own spacing after it is kept
                    spacing: { ...paragraph.options.spacing, before: 240 },
                    alignment: AlignmentType.RIGHT,
                }),
            ),
        },
    ],
});

Each option you give replaces the paragraph's whole option, so spread the paragraph's own from its options to keep the parts you don't change, as with spacing above. An option given as undefined is removed. options holds the options the paragraph was made with: a paragraph made from a string, such as new Paragraph("Hello"), has it as its text.

Options

This is the list of options for a paragraph. A detailed explanation is below:

Property Type Mandatory? Possible Values
text string Optional
heading HeadingLevel Optional HEADING_1, HEADING_2, HEADING_3, HEADING_4, HEADING_5, HEADING_6, TITLE
border IBorderOptions Optional top, bottom, left, right, between. Each of these are of type IBorderPropertyOptions. Click here for Example
spacing ISpacingProperties Optional See below for ISpacingProperties
outlineLevel number Optional
alignment AlignmentType Optional START, CENTER, END, BOTH, MEDIUM_KASHIDA, DISTRIBUTE, NUM_TAB, HIGH_KASHIDA, LOW_KASHIDA, THAI_DISTRIBUTE, LEFT, RIGHT, JUSTIFIED
heading HeadingLevel Optional
bidirectional boolean Optional Lays the paragraph out right to left. See Right-to-left text
thematicBreak boolean Optional
pageBreakBefore boolean Optional
contextualSpacing boolean Optional
indent IIndentAttributesProperties Optional
keepLines boolean Optional
keepNext boolean Optional
children (TextRun or ImageRun or Hyperlink)[] Optional
style string Optional
tabStop { left?: ITabStopOptions; right?: ITabStopOptions; maxRight?: { leader: LeaderType; }; center?: ITabStopOptions } Optional
bullet { level: number } Optional
numbering { num: ConcreteNumbering; level: number; custom?: boolean } Optional
widowControl boolean Optional
frame IFrameOptions Optional
autoSpaceLatinAndEastAsianText boolean Optional Space between East Asian text and Latin letters. See East Asian text beside Latin letters and numbers
autoSpaceEastAsianText boolean Optional Space between East Asian text and numbers. See East Asian text beside Latin letters and numbers

Text

This is the text in a paragraph. You can also add text by using the Paragraph shorthand (mentioned above) or adding children.

Example:

import { Document, Paragraph } from "docx";

const doc = new Document({
    sections: [
        {
            children: [
                new Paragraph({
                    text: "Hello World",
                }),
            ],
        },
    ],
});

Heading

Example:

Setting a Heading 1 paragraph with "Hello World" as it's text:

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

const doc = new Document({
    sections: [
        {
            children: [
                new Paragraph({
                    text: "Hello World",
                    heading: HeadingLevel.HEADING_1,
                }),
            ],
        },
    ],
});

A paragraph has one style, so a paragraph with a style too is in that style, not the heading's, as Word shows it.

Border

Add borders to a Paragraph. Good for making the Paragraph stand out. Border top and border bottom can be used as a horizontal rule (also known as horizontal line).

IBorderPropertyOptions

top, bottom, left, right, between of the border

Property Type Notes
color string | ThemeColor Required
space number Required
style string Required
size number Required

Example:

Add border on the top and the bottom of the paragraph

import { Document, Paragraph } from "docx";

const doc = new Document({
    sections: [
        {
            children: [
                new Paragraph({
                    text: "I have borders on my top and bottom sides!",
                    border: {
                        top: {
                            color: "auto",
                            space: 1,
                            style: "single",
                            size: 6,
                        },
                        bottom: {
                            color: "auto",
                            space: 1,
                            style: "single",
                            size: 6,
                        },
                    },
                }),
            ],
        },
    ],
});

Colors of borders and shading can be hex values, or colors of the document's theme, such as { theme: "accent1", lighter: 40 }. See Themes.

Shading

Add color to an entire paragraph block

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

const doc = new Document({
    sections: [
        {
            children: [
                new Paragraph({
                    text: "shading",
                    shading: {
                        type: ShadingType.REVERSE_DIAGONAL_STRIPE,
                        color: "00FFFF",
                        fill: "FF0000",
                    },
                }),
            ],
        },
    ],
});

Widow Control

Allow First/Last Line to Display on a Separate Page

import { Document, Paragraph } from "docx";

const doc = new Document({
    sections: [
        {
            children: [
                new Paragraph({
                    text: "widow control",
                    widowControl: true,
                }),
            ],
        },
    ],
});

Spacing

Adding spacing between paragraphs

ISpacingProperties

Property Type Notes Possible Values
after number Optional
before number Optional
line number Optional
lineRule LineRuleType Optional AT_LEAST, EXACT, AUTO

With AUTO, the default, line is in 240ths of a line, so 240 is single spacing and 360 is one and a half lines. With EXACT or AT_LEAST, line is a height in twips, so 360 is 18pt.

Note: Use EXACT for an exact line height. LineRuleType.EXACTLY writes exactly, which isn't a value the OOXML schema allows (it allows auto, exact and atLeast), so Word ignores it. It's kept so existing code still compiles. Read this issue for more information: https://github.com/dolanmiu/docx/issues/1773.

Example:

Add spacing before the paragraph:

import { Document, Paragraph } from "docx";

const doc = new Document({
    sections: [
        {
            children: [
                new Paragraph("Paragraph without spacing"),
                new Paragraph({
                    text: "Paragraph with spacing before",
                    spacing: {
                        before: 200,
                    },
                }),
            ],
        },
    ],
});

Indentation

Set paragraph indentation from the page margins using the indent property.

IIndentAttributesProperties

Property Type Notes Description
start number | UniversalMeasure Optional Indentation from the leading edge (left in LTR, right in RTL), in twips
end number | UniversalMeasure Optional Indentation from the trailing edge (right in LTR, left in RTL), in twips
left number | UniversalMeasure Optional Indentation from the left margin, in twips. With hanging, it's where the lines after the first start
right number | UniversalMeasure Optional Indentation from the right margin, in twips
hanging number | PositiveUniversalMeasure Optional How far the first line starts before left, in twips
firstLine number | PositiveUniversalMeasure Optional Additional first-line indent, in twips
firstLineChars number Optional First-line indent in hundredths of a character width (e.g. 200 = 2 chars)

start/end are the bidi-aware equivalents of left/right. Prefer start/end for documents that may be rendered in RTL languages.

Example — first-line indent in twips:

import { Document, Paragraph } from "docx";

const doc = new Document({
    sections: [
        {
            children: [
                new Paragraph({
                    text: "Indented first line. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vehicula nec nulla vitae efficitur. Ut interdum mauris eu ipsum rhoncus, nec pharetra velit placerat.",
                    indent: {
                        firstLine: 720, // 720 twips = 0.5 inch
                    },
                }),
            ],
        },
    ],
});

Example — character-based first-line indent:

Use firstLineChars when you want Word to calculate the indent relative to the font's character width rather than a fixed measurement. The value is in hundredths of a character, so 200 means two characters.

import { Document, Paragraph } from "docx";

const doc = new Document({
    sections: [
        {
            children: [
                new Paragraph({
                    text: "First line indented by two characters. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vehicula nec nulla vitae efficitur. Ut interdum mauris eu ipsum rhoncus, nec pharetra velit placerat.",
                    indent: {
                        firstLineChars: 200,
                    },
                }),
            ],
        },
    ],
});

Example — left and hanging indent:

import { Document, Paragraph } from "docx";

const doc = new Document({
    sections: [
        {
            children: [
                new Paragraph({
                    text: "Hanging indent paragraph. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vehicula nec nulla vitae efficitur. Ut interdum mauris eu ipsum rhoncus, nec pharetra velit placerat.",
                    indent: {
                        left: 720,
                        hanging: 360, // first line hangs back 360 twips from the left indent
                    },
                }),
            ],
        },
    ],
});

Word's Paragraph dialog shows a hanging paragraph's Left indent where its first line starts, which is left minus hanging. So left: 0, hanging: 1077 (1.9 cm) shows there as Left −1.9 cm and Hanging 1.9 cm, with the first line out in the margin. For Word's Left 0 cm and Hanging 1.9 cm, where the first line starts at the margin and the lines after it 1.9 cm in, give left and hanging the same value:

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

const doc = new Document({
    sections: [
        {
            children: [
                new Paragraph({
                    text: "Shows in Word as Left 0 cm, Hanging 1.9 cm. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vehicula nec nulla vitae efficitur. Ut interdum mauris eu ipsum rhoncus, nec pharetra velit placerat.",
                    indent: {
                        left: convertMillimetersToTwip(19),
                        hanging: convertMillimetersToTwip(19),
                    },
                }),
            ],
        },
    ],
});

Outline Level

Example:

import { Document, Paragraph } from "docx";

const doc = new Document({
    sections: [
        {
            children: [
                new Paragraph({
                    text: "Hello World",
                    outlineLevel: 0,
                }),
            ],
        },
    ],
});

Styles

To create styles, please refer to the styling documentation

Headings and titles

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

const doc = new Document({
    sections: [
        {
            children: [
                new Paragraph({
                    text: "Hello World",
                    heading: HeadingLevel.TITLE,
                }),
            ],
        },
    ],
});

Text Alignment

To change the text alignment of a paragraph, add an AlignmentType option on the paragraph.for center, left, right or justified:

Example:

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

const doc = new Document({
    sections: [
        {
            children: [
                new Paragraph({
                    text: "Hello World",
                    heading: HeadingLevel.HEADING_1,
                    alignment: AlignmentType.CENTER,
                }),
            ],
        },
    ],
});

The above will create a heading 1 which is centered.

Justified text with breaks

When a paragraph is justified, incomplete lines ending in a soft line break are stretched to fill the full width by default. To prevent this, enable doNotExpandShiftReturn in the document's compatibility options:

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

const doc = new Document({
    compatibility: {
        doNotExpandShiftReturn: true,
    },
    sections: [
        {
            children: [
                new Paragraph({
                    children: [new TextRun("This justified paragraph won't stretch"), new TextRun({ text: "soft line breaks.", break: 1 })],
                    alignment: AlignmentType.JUSTIFIED,
                }),
            ],
        },
    ],
});

Right-to-left text

For languages written right to left, such as Arabic and Hebrew, set bidirectional on the paragraph. The paragraph is then laid out from the right of the page, so it is right-aligned without an alignment. rightToLeft on a TextRun only orders that run's characters. It does not change the paragraph's direction, so a paragraph without bidirectional stays left-aligned.

LEFT and RIGHT always mean those sides of the page. START and END follow the paragraph's direction, so in a right-to-left paragraph START is the right and END is the left.

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

const doc = new Document({
    sections: [
        {
            children: [
                new Paragraph({
                    bidirectional: true,
                    children: [new TextRun({ text: "مرحبا بالعالم (no alignment)", rightToLeft: true })],
                }),
                new Paragraph({
                    bidirectional: true,
                    alignment: AlignmentType.RIGHT,
                    children: [new TextRun({ text: "مرحبا بالعالم (RIGHT)", rightToLeft: true })],
                }),
                new Paragraph({
                    bidirectional: true,
                    alignment: AlignmentType.LEFT,
                    children: [new TextRun({ text: "مرحبا بالعالم (LEFT)", rightToLeft: true })],
                }),
                new Paragraph({
                    bidirectional: true,
                    alignment: AlignmentType.END,
                    children: [new TextRun({ text: "مرحبا بالعالم (END)", rightToLeft: true })],
                }),
            ],
        },
    ],
});

!> Word reads left and right in the XML as the start and end of the paragraph. So docx writes AlignmentType.RIGHT as left in a bidirectional paragraph, which Word puts on the right. This only happens when alignment and bidirectional are set on the same paragraph. If either one comes from a style or a template, LEFT and RIGHT act like START and END.

East Asian Text Beside Latin Letters and Numbers

Word can put a small space between Chinese, Japanese or Korean text and a Latin letter or a digit beside it. autoSpaceLatinAndEastAsianText turns the space beside Latin letters on or off (w:autoSpaceDE), and autoSpaceEastAsianText the space beside numbers (w:autoSpaceDN). Both are on unless the paragraph, or the formatting it takes from elsewhere such as its style or the document defaults, turns them off. Where they are on, whether the space appears depends on the Word that opens the document: Word for Mac on a Mac set to Korean adds it, other setups may not, and the useFELayout compatibility option has Word add it as well.

Set them to false in the document defaults to turn the space off in every Word, wherever nothing closer to the paragraph, such as its style, turns it back on. They can also be set on a paragraph, a paragraph style or a numbering level, for just those paragraphs. With externalStyles, document defaults given here take the place of all of the template's, such as its default fonts, language and paragraph spacing. To keep those, set the options on the paragraphs instead.

import { Document, Paragraph } from "docx";

const doc = new Document({
    styles: {
        default: {
            document: {
                paragraph: {
                    autoSpaceLatinAndEastAsianText: false,
                    autoSpaceEastAsianText: false,
                },
            },
        },
    },
    sections: [
        {
            // No space added between "docx" and "로", or between "2" and "쪽"
            children: [new Paragraph("docx로 만든 2쪽짜리 문서")],
        },
    ],
});

Thematic Break

To add a thematic break in the Paragraph:

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

const doc = new Document({
    sections: [
        {
            children: [
                new Paragraph({
                    text: "Amazing Heading",
                    heading: HeadingLevel.HEADING_1,
                    thematicBreak: true,
                }),
            ],
        },
    ],
});

The above example will create a heading with a horizontal line directly under it.

The line is the paragraph's bottom border. With a border, it's drawn with the paragraph's other borders, in place of border.bottom.

Page Break

To move to a new page (insert a page break):

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

const doc = new Document({
    sections: [
        {
            children: [
                new Paragraph({
                    children: [new TextRun("Amazing Heading"), new PageBreak()],
                }),
                new Paragraph("This text starts on the new page"),
            ],
        },
    ],
});

The above example will create a heading and start a new page immediately afterwards.

Page break before:

This option (available in word) will make sure that the paragraph will start on a new page (if it's not already on a new page).

import { Document, Paragraph } from "docx";

const doc = new Document({
    sections: [
        {
            children: [
                new Paragraph("Hello World"),
                new Paragraph({
                    text: "Hello World on another page",
                    pageBreakBefore: true,
                }),
            ],
        },
    ],
});

Page Break Before in Word

Example: https://github.com/dolanmiu/docx/blob/master/demo/paragraphs/page-break-before.ts

Page break control

Paragraphs have keepLines and keepNext properties that allow restricting page breaks within and between paragraphs. See this Microsoft article for more details.

import { Document, Paragraph } from "docx";

const doc = new Document({
    sections: [
        {
            children: [
                new Paragraph({
                    text: "Stay on the same page",
                    keepLines: true,
                    keepNext: true,
                }),
            ],
        },
    ],
});