Files
docx/docs/usage/document.md
T
DolanandClaude Opus 5.5 3f5a17cd10 feat(layout): break table rows across pages, lay out footnotes and columns, and write the numbers of pages (#3592)
* feat(layout): break table rows across pages between the lines of their cells

Word and LibreOffice break a table row that doesn't fit across the pages
unless it is kept whole (cantSplit), but the layout moved every row to the
next page whole, which put the headings after a table of long rows on the
wrong page. Rows now break between the lines of their cells, with the
header rows repeated above the rest, and without widow control inside
them, as LibreOffice does. Rows kept whole, of an exact height, or whose
text fits but not their set height, still move whole. A row that would
break with merged cells, a table in it, or a height set taller than its
text stops the layout, as nothing checks how those break yet.

LibreOffice's lines are whole twips tall, so lines are rounded to twips:
that matches its line pitch for 80 of 90 font sizes measured, against none
before. The tables demo is at 12 points, as LibreOffice's lines of Times
New Roman at 10 points are a twip taller than the font's metrics.

A new layout demo, tables-across-pages, has rows of each kind across page
breaks. All 185 headings of the 7 demos are on LibreOffice's page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NijyutGmb3bNR3dNRWJken

* feat(layout): lay out footnotes at the bottom of their pages, and endnotes after the text

The layout stopped at the first footnote, so most reports lost every page
number after it. Now a page's footnotes take room at its bottom, below
their separator, with the space between them, but not before the
separator or after the last, as LibreOffice lays them out. A line whose
one-line footnote doesn't fit below it moves to the next page with it, as
in LibreOffice. LibreOffice continues a longer footnote on the next page,
splitting even one widow control would keep together, and which of its
lines stay isn't followed yet, so the layout stops there, and at a
footnote in a table row that breaks across pages.

Endnotes follow the text, after their separator, as Word and LibreOffice
lay them out. Footnotes are numbered 1, 2, 3 and endnotes i, ii, iii, and
their numbers are as narrow as superscript and as tall as their font.

A new layout demo, footnotes-and-endnotes, has 40 footnotes over 8 pages.
All 18 of its headings are on LibreOffice's page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NijyutGmb3bNR3dNRWJken

* feat(layout): lay out sections in columns

The layout stopped at the first section in columns. Now each page's
columns are filled in turn, each as wide as the section gives, before the
next page: text moves to the next column when it doesn't fit, or is kept
with what is there, and a column break starts the next column, or a new
page in the last. A section in columns that starts on the same page as
the text before it starts its columns below that text.

Word and LibreOffice even out a section's columns before a continuous
section break, so the next section starts below the longest, and which
lines go in which column isn't followed yet, so the layout stops there,
as it does at a footnote in columns and at a table's header rows repeated
at the top of a column.

scripts/compare-layout.sh reads LibreOffice's text in reading order, so a
page's columns come one after the other rather than side by side. A new
layout demo, columns, has sections of one, two and three columns. All 227
headings of the 9 demos are on LibreOffice's page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NijyutGmb3bNR3dNRWJken

* feat(layout): write the numbers of pages into NUMPAGES and SECTIONPAGES fields

paginate counted the pages, but nothing wrote the count, so "Page 3 of"
footers were written without their number, which applications that show
fields as they are written show blank. Now docx/layout works out the
number of pages of the document, when it lays all of it out, and of each
section whose pages are its own, laying the pages out again until the
numbers, which can change how lines wrap, stay the same.

EstimatedPageNumbers gains pageCount and sectionPageCounts, and docx
writes them into the NUMPAGES and SECTIONPAGES fields of the body, and
of the headers and footers once the body is written, with the page
references in them. A header or footer shows the number of pages of the
sections it is on only when they all have the same. A section that
shares a page with another, or has a blank page before or after it, is
left blank, as is a field in a number format of its own. Like PAGEREF
fields, those with a numeric picture (\#) are left as they are.

scripts/compare-layout.ts checks the numbers of pages written into the
demos against the pages of LibreOffice's PDFs: both demos with them match.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NijyutGmb3bNR3dNRWJken

* fix(layout): keep a paragraph with the next on a new page when they fit there

Whether what is kept together fits in a fresh column was measured from
where the page's columns start, which is partway down the page below a
continuous section break. When the column is the last, the kept
paragraphs go on a new page, whose text starts at the top, so a heading
that would fit there with the next paragraph stayed at the bottom of the
page, and the paragraph moved on alone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NijyutGmb3bNR3dNRWJken

* fix(layout): stop at a section whose columns differ in width

A paragraph is broken into lines at the width of the column it starts
in, and a paragraph that goes on into a column of another width kept
those lines, so its height, and the pages after it, were wrong. Breaking
the rest of a paragraph again needs to know where each line starts in
its text, so a section with columns of different widths stops the
layout, and the page numbers after it are left blank.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NijyutGmb3bNR3dNRWJken

* fix: fail the layout comparison when LibreOffice didn't lay out a document

The comparison skipped a document without the text of LibreOffice's
pages, as when LibreOffice fails to convert it, and reported its
headings as matching, so CI could pass without comparing it. Now it
fails, and names the documents LibreOffice didn't lay out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NijyutGmb3bNR3dNRWJken

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 12:50:47 +01:00

312 lines
17 KiB
Markdown

# Document
> The `Document` object is the starting point of your `.docx` journey, this is the literal Word Document. You add all your content such as `Paragraphs` to this `Document`, and at the end export it however you like.
To create a new document, it is very easy:
```ts live
import { Document, Paragraph } from "docx";
const doc = new Document({
sections: [
{
children: [new Paragraph("Hello World")],
},
],
});
```
## Document Properties
You can add metadata properties to the Word document:
```ts live
import { Document, Paragraph } from "docx";
const doc = new Document({
creator: "Dolan Miu",
description: "My extremely interesting document",
title: "My Document",
subject: "Report",
keywords: "report, annual, finance",
sections: [
{
children: [new Paragraph("Hello World")],
},
],
});
```
These properties appear in Word's File > Info panel and in file properties.
## Options by Category
### Metadata Properties
| Property | Type | Description |
| -------------- | -------- | ----------------------------- |
| title | `string` | Document title |
| subject | `string` | Document subject |
| creator | `string` | Author name |
| keywords | `string` | Keywords for searching |
| description | `string` | Document description/comments |
| lastModifiedBy | `string` | Last person to modify |
| revision | `number` | Revision number |
### Content Options
| Property | Type | Description |
| --------- | ------------------------------------------- | ----------------- |
| sections | `ISectionOptions[]` | Document sections |
| comments | `ICommentsOptions` | Document comments |
| footnotes | `Record<string, { children: Paragraph[] }>` | Footnotes |
### Styling Options
| Property | Type | Description |
| -------------- | ------------------- | ------------------------------------------------------------- |
| styles | `IStylesOptions` | Custom styles |
| externalStyles | `string` | External XML styles |
| numbering | `INumberingOptions` | Numbering definitions |
| fonts | `FontOptions[]` | Embedded fonts |
| defaultTabStop | `number` | Default tab stop (twips) |
| theme | `IThemeOptions` | The document's [theme](usage/themes.md): its colors and fonts |
### Document Behavior
| Property | Type | Description |
| -------------------------- | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| background | `IDocumentBackgroundOptions` | Document background |
| features | `{ trackRevisions?: boolean; updateFields?: boolean }` | Feature flags |
| evenAndOddHeaderAndFooters | `boolean` | Different odd/even headers |
| hyphenation | `IHyphenationOptions` | Hyphenation settings |
| pageNumbers | `PageNumberEstimator` | Writes the page numbers of tables of contents and page references, and the numbers of pages, with `estimatePageNumbers` from [`docx/layout`](usage/layout.md) |
### Compatibility
| Property | Type | Description |
| ------------------------ | ----------------------- | -------------------------- |
| compatibility | `ICompatibilityOptions` | Compatibility settings |
| compatabilityModeVersion | `number` | Word version compatibility |
### Full list of options:
| Property | Type | Notes |
| -------------------------- | -------------------------------------------------------- | -------- |
| sections | `ISectionOptions[]` | Optional |
| title | `string` | Optional |
| subject | `string` | Optional |
| creator | `string` | Optional |
| keywords | `string` | Optional |
| description | `string` | Optional |
| lastModifiedBy | `string` | Optional |
| revision | `number` | Optional |
| externalStyles | `string` | Optional |
| styles | `IStylesOptions` | Optional |
| numbering | `INumberingOptions` | Optional |
| comments | `ICommentsOptions` | Optional |
| footnotes | `Record<string, { children: Paragraph[] }>` | Optional |
| background | `IDocumentBackgroundOptions` | Optional |
| features | `{ trackRevisions?: boolean; updateFields?: boolean; }` | Optional |
| compatabilityModeVersion | `number` | Optional |
| compatibility | `ICompatibilityOptions` | Optional |
| customProperties | ` ICustomPropertyOptions`[] | Optional |
| evenAndOddHeaderAndFooters | `boolean` | Optional |
| defaultTabStop | `number` | Optional |
| fonts | ` FontOptions[]` | Optional |
| hyphenation | `IHyphenationOptions` | Optional |
| theme | `IThemeOptions` | Optional |
| pageNumbers | `PageNumberEstimator` | Optional |
### Change background color of Document
Set the hex value in the document like so:
```ts live
import { Document, Paragraph } from "docx";
const doc = new Document({
background: {
color: "C45911",
},
sections: [
{
children: [new Paragraph("Hello World")],
},
],
});
```
Or use a color of the document's theme, lighter or darker if you like, so the page changes color with the theme. See [Themes](usage/themes.md#text-tables-and-borders-in-the-themes-colors):
```ts live
import { Document, Paragraph } from "docx";
const doc = new Document({
background: {
color: { theme: "accent2", lighter: 80 },
},
sections: [
{
children: [new Paragraph("Hello World")],
},
],
});
```
`themeColor`, `themeTint` and `themeShade` are deprecated: give `color` a theme color instead.
### Custom Properties
Add custom metadata properties that appear in Word's document properties:
```ts live
import { Document, Paragraph } from "docx";
const doc = new Document({
customProperties: [
{
name: "Department",
value: "Engineering",
},
{
name: "Project Code",
value: "PRJ-2024-001",
},
{
name: "Approved",
value: "true",
},
{
name: "Version",
value: "2.5",
},
],
sections: [
{
children: [new Paragraph("Hello World")],
},
],
});
```
Custom property values are text (`string`), so write numbers and true/false values as text, as above.
### Document Features
Enable special features like track changes or field updating:
```ts live
import { Document, Paragraph } from "docx";
const doc = new Document({
features: {
trackRevisions: true, // Enable track changes
updateFields: true, // Update fields (like TOC) when opened
},
sections: [
{
children: [new Paragraph("Hello World")],
},
],
});
```
?> Set `updateFields: true` when using Table of Contents so it updates automatically when the document is opened.
### Units for positioning
Various parts of the API require positioning arguments. The units are "20ths of a point" from the [OOXML](http://officeopenxml.com/index.php) specification.
See [Lars Corneliussen's blog post](https://startbigthinksmall.wordpress.com/2010/01/04/points-inches-and-emus-measuring-units-in-office-open-xml/) for more information and how to convert units.
## Compatibility
Compatibility Settings are optional settings used to preserve visual fidelity of documents created in earlier word processing applications. Some of these settings provide ability for specific behaviors, described in detail below; and others simply instruct applications to mimic the behavior of an existing word processing application.
```ts live
import { Document, Paragraph } from "docx";
const doc = new Document({
compatibility: {
version: 15,
doNotExpandShiftReturn: true,
},
sections: [
{
children: [new Paragraph("Hello World")],
},
],
});
```
### Compatibility Options
| Property | Type | Notes | Possible Values |
| ----------------------------------- | --------- | -------- | ---------------------------- |
| version | `number` | Optional | `15`, `16`, `17` |
| useSingleBorderforContiguousCells | `boolean` | Optional | `true`, `false`, `undefined` |
| wordPerfectJustification | `boolean` | Optional | `true`, `false`, `undefined` |
| noTabStopForHangingIndent | `boolean` | Optional | `true`, `false`, `undefined` |
| noLeading | `boolean` | Optional | `true`, `false`, `undefined` |
| spaceForUnderline | `boolean` | Optional | `true`, `false`, `undefined` |
| noColumnBalance | `boolean` | Optional | `true`, `false`, `undefined` |
| balanceSingleByteDoubleByteWidth | `boolean` | Optional | `true`, `false`, `undefined` |
| noExtraLineSpacing | `boolean` | Optional | `true`, `false`, `undefined` |
| doNotLeaveBackslashAlone | `boolean` | Optional | `true`, `false`, `undefined` |
| underlineTrailingSpaces | `boolean` | Optional | `true`, `false`, `undefined` |
| doNotExpandShiftReturn | `boolean` | Optional | `true`, `false`, `undefined` |
| spacingInWholePoints | `boolean` | Optional | `true`, `false`, `undefined` |
| lineWrapLikeWord6 | `boolean` | Optional | `true`, `false`, `undefined` |
| printBodyTextBeforeHeader | `boolean` | Optional | `true`, `false`, `undefined` |
| printColorsBlack | `boolean` | Optional | `true`, `false`, `undefined` |
| spaceWidth | `boolean` | Optional | `true`, `false`, `undefined` |
| showBreaksInFrames | `boolean` | Optional | `true`, `false`, `undefined` |
| subFontBySize | `boolean` | Optional | `true`, `false`, `undefined` |
| suppressBottomSpacing | `boolean` | Optional | `true`, `false`, `undefined` |
| suppressTopSpacing | `boolean` | Optional | `true`, `false`, `undefined` |
| suppressSpacingAtTopOfPage | `boolean` | Optional | `true`, `false`, `undefined` |
| suppressTopSpacingWP | `boolean` | Optional | `true`, `false`, `undefined` |
| suppressSpBfAfterPgBrk | `boolean` | Optional | `true`, `false`, `undefined` |
| swapBordersFacingPages | `boolean` | Optional | `true`, `false`, `undefined` |
| convertMailMergeEsc | `boolean` | Optional | `true`, `false`, `undefined` |
| truncateFontHeightsLikeWP6 | `boolean` | Optional | `true`, `false`, `undefined` |
| macWordSmallCaps | `boolean` | Optional | `true`, `false`, `undefined` |
| usePrinterMetrics | `boolean` | Optional | `true`, `false`, `undefined` |
| doNotSuppressParagraphBorders | `boolean` | Optional | `true`, `false`, `undefined` |
| wrapTrailSpaces | `boolean` | Optional | `true`, `false`, `undefined` |
| footnoteLayoutLikeWW8 | `boolean` | Optional | `true`, `false`, `undefined` |
| shapeLayoutLikeWW8 | `boolean` | Optional | `true`, `false`, `undefined` |
| alignTablesRowByRow | `boolean` | Optional | `true`, `false`, `undefined` |
| forgetLastTabAlignment | `boolean` | Optional | `true`, `false`, `undefined` |
| adjustLineHeightInTable | `boolean` | Optional | `true`, `false`, `undefined` |
| autoSpaceLikeWord95 | `boolean` | Optional | `true`, `false`, `undefined` |
| noSpaceRaiseLower | `boolean` | Optional | `true`, `false`, `undefined` |
| doNotUseHTMLParagraphAutoSpacing | `boolean` | Optional | `true`, `false`, `undefined` |
| layoutRawTableWidth | `boolean` | Optional | `true`, `false`, `undefined` |
| layoutTableRowsApart | `boolean` | Optional | `true`, `false`, `undefined` |
| useWord97LineBreakRules | `boolean` | Optional | `true`, `false`, `undefined` |
| doNotBreakWrappedTables | `boolean` | Optional | `true`, `false`, `undefined` |
| doNotSnapToGridInCell | `boolean` | Optional | `true`, `false`, `undefined` |
| selectFieldWithFirstOrLastCharacter | `boolean` | Optional | `true`, `false`, `undefined` |
| applyBreakingRules | `boolean` | Optional | `true`, `false`, `undefined` |
| doNotWrapTextWithPunctuation | `boolean` | Optional | `true`, `false`, `undefined` |
| doNotUseEastAsianBreakRules | `boolean` | Optional | `true`, `false`, `undefined` |
| useWord2002TableStyleRules | `boolean` | Optional | `true`, `false`, `undefined` |
| growAutofit | `boolean` | Optional | `true`, `false`, `undefined` |
| useFELayout | `boolean` | Optional | `true`, `false`, `undefined` |
| useNormalStyleForList | `boolean` | Optional | `true`, `false`, `undefined` |
| doNotUseIndentAsNumberingTabStop | `boolean` | Optional | `true`, `false`, `undefined` |
| useAlternateEastAsianLineBreakRules | `boolean` | Optional | `true`, `false`, `undefined` |
| allowSpaceOfSameStyleInTable | `boolean` | Optional | `true`, `false`, `undefined` |
| doNotSuppressIndentation | `boolean` | Optional | `true`, `false`, `undefined` |
| doNotAutofitConstrainedTables | `boolean` | Optional | `true`, `false`, `undefined` |
| autofitToFirstFixedWidthCell | `boolean` | Optional | `true`, `false`, `undefined` |
| underlineTabInNumberingList | `boolean` | Optional | `true`, `false`, `undefined` |
| displayHangulFixedWidth | `boolean` | Optional | `true`, `false`, `undefined` |
| splitPgBreakAndParaMark | `boolean` | Optional | `true`, `false`, `undefined` |
| doNotVerticallyAlignCellWithSp | `boolean` | Optional | `true`, `false`, `undefined` |
| doNotBreakConstrainedForcedTable | `boolean` | Optional | `true`, `false`, `undefined` |
| ignoreVerticalAlignmentInTextboxes | `boolean` | Optional | `true`, `false`, `undefined` |
| useAnsiKerningPairs | `boolean` | Optional | `true`, `false`, `undefined` |
| cachedColumnBalance | `boolean` | Optional | `true`, `false`, `undefined` |