* 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>
22 KiB
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")],
}),
],
},
],
});
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 | |
| 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 |
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,
}),
],
},
],
});
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, EXACTLY, EXACT, AUTO |
Note: The lineRule property has different values depending on the version of Word you are using. The EXACTLY value is only available in Word 2016 and above. Use EXACT for greater support, including LibreOffice etc. 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 |
| right | number | UniversalMeasure |
Optional | Indentation from the right margin, in twips |
| hanging | number | PositiveUniversalMeasure |
Optional | Hanging indent removed from the first line, 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/endare the bidi-aware equivalents ofleft/right. Preferstart/endfor 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
},
}),
],
},
],
});
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,
}),
],
},
],
});
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.
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,
}),
],
},
],
});
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,
}),
],
},
],
});
