Files
docx/docs/usage/layout.md
T
Dolan f78a5ce3dd feat(layout): lay out table borders of different styles that meet, and borders beside space between cells, as Word does (#3677)
* feat(layout): lay out table borders of different styles that meet, and borders beside space between cells, as Word does

Word's PDF of word-stops-table-borders.docx (lay-stops2's batch) settles the
table border stops of the work's line 6:

- Where two cells' borders meet, Word draws the heavier, by the weights
  MS-OI29500 gives for 17.4.66, but makes room for the wider of the two
  whichever it draws (TB1 to TB3; TB3d: a dotted border of 1.5 points below
  a single one of half a point takes 1.5 points, below the single one Word
  draws). Beside text, where Word draws the narrower and half the wider is
  more than the margin, which it keeps the text from hasn't been seen, so
  that still stops.
- Wave and 3D borders take their room at each width Word offers (TB4a to
  TB4v).
- With space between cells, each cell's borders left and right of it take
  their width from its text, and the table's none (TB5a to TB5l). A row's
  own space is the table's, at its edges too (TB6c, TB6d), and space given
  as a share of the table's width is none (TB6a, TB6b). Where such a table
  breaks across pages, its bottom border is below the last of it on the
  page and its top border above the rest of it on the next, between rows
  and in them (TB7a to TB7c).

Paragraph and run borders with a medium or large gap take the room they take
beside a table's cells (word-table-formats.docx BS, word-stops-text.docx PB4b).

* fix(layout): leave a deleted row's space between cells out of the rows' comparison

A deleted row takes no room, nor does the space around it (word-tracked-tables.docx MK14h), so a table whose kept rows
all have the same space between their cells no longer stops for a deleted row with other space, and its space is the
first kept row's.

* fix(layout): stop at a row's own borders in a table with space between its cells

A row's own table borders (w:tblPrEx), which #3686 gives its cells, meet
space between cells, whose table borders go around the space
(word-stops-table-borders.docx TB5). Where Word puts a row's own hasn't
been seen, so the layout stops there rather than guessing.
2026-10-05 13:42:12 +01:00

106 KiB
Raw Blame History

Layout

!> Layout requires an understanding of Table of Contents and Bookmarks.

docx/layout lays out a document's pages as Word would, when the document is written, to work out the page each heading and bookmark is on. docx then writes those page numbers into the document's tables of contents and page references.

Without it, their page numbers are blank until Word updates the fields, because they depend on how the document is laid out. Word only updates them when the document asks it to (updateFields) and the reader says yes, or when the reader updates the table. LibreOffice never fills in a table of contents' page numbers, so documents it converts to PDF have none.

It is opt-in. The page numbers are estimates: Word still works them out again when it updates the fields, such as when the reader updates the table.

It can also give what is on each page, with layoutDocument: the lines of each paragraph, with their text and where they are, the rows of tables, the footnotes and endnotes, and which header and footer each page shows.

Importing

Layout comes with the docx package. Import it from docx/layout, and everything else from docx:

import { Document, TableOfContents } from "docx";
import { estimatePageNumbers, layoutDocument } from "docx/layout";

In a page without a bundler, load dist/layout.umd.cjs after dist/index.umd.cjs (or dist/layout.iife.js after dist/index.iife.js). It adds a docxLayout global, such as docxLayout.estimatePageNumbers and docxLayout.layoutDocument.

Example

Give the document estimatePageNumbers as its pageNumbers:

import { Bookmark, Document, HeadingLevel, PageReference, Paragraph, TableOfContents, TextRun } from "docx";
import { estimatePageNumbers } from "docx/layout";

const text = "The harbour was rebuilt after the storm, and this report sets out what it cost and what is left to do. ".repeat(12);

const doc = new Document({
    // Without updateFields, Word shows the page numbers as they are written, and doesn't ask to update them
    pageNumbers: estimatePageNumbers,
    sections: [
        {
            children: [
                new TableOfContents("Contents", { hyperlink: true, headingStyleRange: "1-3" }),
                new Paragraph({ children: [new TextRun("The costs are on page "), new PageReference("costs"), new TextRun(".")] }),
                ...[1, 2, 3, 4].flatMap((chapter) => [
                    new Paragraph({ heading: HeadingLevel.HEADING_1, children: [new TextRun(`Chapter ${chapter}`)] }),
                    new Paragraph(text),
                    new Paragraph({ heading: HeadingLevel.HEADING_2, children: [new TextRun(`Section ${chapter}.1`)] }),
                    new Paragraph(text),
                ]),
                new Paragraph({
                    heading: HeadingLevel.HEADING_1,
                    children: [new Bookmark({ id: "costs", children: [new TextRun("Costs")] })],
                }),
                new Paragraph(text),
            ],
        },
    ],
});

The page numbers are written into:

  • the entries of each Table of Contents filled in from the headings
  • each PageReference. One that shows its position relative to the bookmark (useRelativePosition) writes "above" or "below" when it is on the bookmark's page, by whether the bookmark is before or after it in the text, even in another column or table cell, and "on page" and the page as it shows it when it isn't, such as "on page 4", "on page iv" or "on page 1-2", as Word writes it. A bookmark in a footnote or endnote is on the page of the note's reference, as Word has it, even in the part of a footnote that goes on to the next page or in an endnote at the end of the document, and one that shows its position relative to it writes "on page" and that page, even on the same page. One in a footnote or endnote writes "on page" and its bookmark's page too, wherever the bookmark is, as Word writes it
  • the number of pages of the document (PageNumber.TOTAL_PAGES) and of each section (PageNumber.TOTAL_PAGES_IN_SECTION), in the text, headers and footers. A section's is left blank when it shares a page with another section, or has a blank page before or after it

A page reference or number of pages in a format of its own, such as a template's PAGEREF Results \* roman or Word's NUMPAGES \* Arabic \* MERGEFORMAT, or a SimpleField such as new SimpleField("PAGEREF Results \\* roman"), is written in that format, as Word writes it: \* Arabic, \* Roman (IV), \* roman (iv), \* ALPHABETIC (D), \* alphabetic (d), \* Ordinal (4th) or \* ArabicDash (- 4 -), or a picture of digits, such as \# "00" (04) or \# "#,##0" (1,234), in capitals with \* Upper (IV, 4TH or ON PAGE 4), \* Lower or \* FirstCap. A page reference in a format of its own writes the number of its bookmark's page without its chapter number, such as ii for page 1-2, and one that shows its position relative to the bookmark writes the number too.

Word writes the numbers of the page and section a PAGE or SECTION field is on itself (PageNumber.CURRENT, PageNumber.CURRENT_SECTION, and a PageNumberElement), so docx leaves them empty, but the lines they are in are laid out with the numbers Word writes: the page's number as the page shows it, such as iv or 2-5, or in one of the formats above, and the section's, counted from 1. In a footnote or endnote, they are those of the page and section of its reference, as Word has them.

The numbers of captions, such as the 2 of "Figure 2", are written too. Each SequentialIdentifier is a SEQ field, which counts the SEQ fields of its identifier, such as "Figure", up to it, so its number doesn't depend on the layout. It is counted as Word counts it: the SEQ fields of the text, in text boxes and hidden text too, in order, with an identifier in any capitals, or in quotes, counted as the same one. The switches written after the identifier, such as new SequentialIdentifier("Figure \\r 5"), are followed: \r 5 starts the count again from 5, \c repeats the number before, or writes 0 before the first, \n is the next number, \s 1 starts the count again after each Heading 1, or heading of a higher level, and \h hides the number, unless it is given a format. A \* ARABIC, \* ROMAN, \* ALPHABETIC, \* Ordinal (4th) or \* ArabicDash (- 4 -) writes it in that format, and \* roman and \* alphabetic in small letters. A heading's caption number is left out of its entry in the table of contents, as Word leaves it out.

Opening the document in Word

Without pageNumbers, docx writes page references, tables of contents and SEQ fields as fields for Word to update, so Word asks "This document contains fields that may refer to other files. Do you want to update the fields in this document?" when it opens the document. With pageNumbers, they are written as they are, so Word shows them as they are written, and doesn't update them or ask. Leave updateFields off, and Word opens the document without asking.

A page number docx/layout couldn't work out, after it stopped (see What it leaves blank), is left blank, and stays blank in Word until the fields are updated: by the reader, such as by updating the table of contents, or by turning updateFields on. A wrong page number is worse than a blank one. The same goes for what docx/layout doesn't write at all:

  • a page reference that shows its position relative to the bookmark (useRelativePosition) in a header or footer
  • a page reference or number of pages in a format other than those above, such as \* CardText or \* Caps, or with a picture Word's text isn't known for, such as one with text in it, or more #s than the number has digits, which Word writes as spaces
  • a table of contents that lists no heading, or of captions or TC fields, which is left empty, and the entries of one given cachedEntries or contentChildren, which are left as they were given
  • the page numbers of a table of contents that writes a SEQ field's number before each of them (seqFieldIdentifierForPrefix), such as 2-5 for page 5 of chapter 2
  • a SEQ field in a format other than those above, such as \* CardText or \# 00, or past what the format writes, such as 781 in letters, for which Word writes an error
  • a SEQ field with a bookmark after its identifier, which shows the number of the SEQ field at the bookmark
  • a SEQ field with a switch not followed, such as \c with \r, or in deleted text, and the SEQ fields of its identifier after it, until one starts the count again with \r. So is a field with \s after a paragraph with an outline level but no heading style (outlineLevel), or another than its heading style's
  • the SEQ fields in headers, footers, footnotes and endnotes, which Word writes as an error, "Error! Main Document Only.", and every SEQ field of an identifier that has one in a comment

Word still asks when:

  • the document has updateFields on, which asks Word to update all of its fields
  • a table of contents is given beginDirty: true

Templates

patchDocument writes the page numbers of a template it fills in too, when it is given estimatePageNumbers as its pageNumbers. The pages are laid out once the patches are in, so the numbers are those of the filled-in document:

import * as fs from "fs";
import { Paragraph, patchDocument, PatchType } from "docx";
import { estimatePageNumbers } from "docx/layout";

const doc = await patchDocument({
    outputType: "nodebuffer",
    data: fs.readFileSync("Report template.docx"),
    patches: {
        summary: { type: PatchType.DOCUMENT, children: [new Paragraph("The harbour was rebuilt after the storm.")] },
    },
    pageNumbers: estimatePageNumbers,
});

The template is read as Word saved it, with its styles, theme, lists, settings, headers, footers and notes, and the numbers are written into its tables of contents, page references and numbers of pages, in its text, headers and footers. The numbers a template was saved with are those of the template before it was filled in, so one that docx/layout can't work out, after something it can't lay out, is left blank rather than kept. Its page references and tables of contents are written clean, as a document's are, so Word shows them as they are (see Opening the document in Word). The template's settings are kept as they are, updateFields (w:updateFields) among them, so a template that has it on still asks Word to update all of its fields when the filled-in document is opened. Leave it off in the template, and Word opens the filled-in document without asking, as it opens a document whose fields are written clean (see Opening the document in Word for what still makes it ask). What estimatePageNumbersWith returns works the same way.

A template can import other documents (w:altChunk), which Word turns into paragraphs and tables of the template's own when it opens it. A .docx it imports is laid out as Word lays it out: where it is imported, in the text, a table cell, a header, a footnote or another imported document, in the template's styles of the same names, its defaults, its theme and its settings, with the styles only the imported document has as they look there, and paragraphs of no style in its default style, its lists numbered on their own and its footnotes numbered with the template's, and without its own page size, margins, headers and footers. A bookmark of a name the template has is the template's. What the layout doesn't follow stops it (see What it leaves blank).

patchDocument doesn't add entries to a table of contents for the headings patches add. Word adds them when it updates the table.

What is on each page

layoutDocument lays out a document's pages as estimatePageNumbers does, and gives what is on each of them:

import { Document, Paragraph } from "docx";
import { layoutDocument } from "docx/layout";

const doc = new Document({ sections: [{ children: [new Paragraph("The harbour was rebuilt after the storm.")] }] });

const { pages, stoppedAt } = layoutDocument(doc);
for (const page of pages) {
    for (const block of page.body) {
        if (block.type === "paragraph") {
            for (const line of block.lines) {
                console.log(`Page ${page.pageNumber}: "${line.text}", ${line.y} pixels down`);
            }
        }
    }
}
if (stoppedAt) {
    console.log(`Laid out up to ${stoppedAt}`);
}

Lengths are in pixels, 96 to the inch, from the top left corner of the page. The page numbers of tables of contents and page references are laid out as estimatePageNumbers writes them, whether or not the document is given it. layoutDocument(doc, { guess: true }) lays out past what it would stop at, as estimatePageNumbersWith({ guess: true }) does (see Guessing past what it can't lay out).

The layout of the document, DocumentLayout:

Property Type What it is
pages readonly PageLayout[] The pages, in order
stoppedAt string or undefined What the layout stopped at, such as "a table that text flows around". The pages are those up to there, the last of them with what was laid out on it. With { guess: true }, what it has no guess for

Each page, PageLayout:

Property Type What it is
pageNumber string or none The page's number, as the page shows it, such as "3" or "iv". None when Word's isn't known: when the section's page numbers start with a chapter number
section number The section the page starts in, counted from 0
width number The width of the page
height number The height of the page
textRunsDown "fromRight", "fromLeft" or none When the page's text runs down it, as in Chinese and Japanese, whether its lines go across it from the right or from the left. Its lines are then down the page, as below
header "default", "first", "even" or none Which of the section's headers the page shows, by the name the section's headers give it. A section without one of them shows the one of the section before. None when it has none
footer "default", "first", "even" or none Which of the section's footers the page shows, in the same way
body readonly (ParagraphLayout | TableLayout)[] The paragraphs and tables of the body on the page, or the parts of them on it, in order
footnotes readonly NoteLayout[] The footnotes at the bottom of the page, in order. The rest of one that goes on from the page before comes first
endnotes readonly NoteLayout[] The endnotes on the page, which follow the body
guesses readonly string[] or none With { guess: true }, what the layout guessed at while it laid out the page, such as "a font not in the width tables". None when it guessed at nothing there

A paragraph, ParagraphLayout, is { type: "paragraph", index, lines }, and a table, TableLayout, is { type: "table", index, rows }. index is where it is among the paragraphs and tables of the body, or of its footnote or endnote, counted from 0, so a paragraph on two pages has the same index on both. It counts each paragraph docx writes, such as the entries of a table of contents, and the empty paragraph it writes at the end of each section but the last, which takes no room, so it isn't on any page.

Each line, LineLayout:

Property Type What it is
text string The text on the line, with the spaces where it wraps and a tab as \t, but not the hyphen where it breaks at a soft hyphen. The texts of a paragraph's lines, one after the other, are its text
x number Where the room for the line starts across the page: the left of its column, or of the page's text, and the paragraph's indent, or beside a drawing that text wraps around
y number Where the top of the line is down the page
width number How wide the room for the line is, between the paragraph's indents, or beside a drawing
height number How tall the line is, with the paragraph's line spacing
textWidth number How far its text goes from x, without the spaces at its end, and with the hyphen where it breaks at a soft hyphen

The text is lined up in the line's room as the paragraph's alignment says, so it starts at x when it is aligned to the left, (width - textWidth) / 2 further on when it is centred, and width - textWidth further on when it is aligned to the right. Justified lines but the last fill it. A line with text on both sides of a drawing is two lines with the same y, the left first, and a side the next word doesn't fit on is a line with no text.

On a page whose text runs down it (textRunsDown), each line is a line down the page: x and y are the top left of its room, width how far across the page the line is, with the paragraph's line spacing, and height how far down the page its room is, between the paragraph's indents. Its text goes textWidth down from y, and the lines go across the page from the right, or the left, from the margin.

Each row of a table, or the part of a row on the page when it breaks across pages, RowLayout, is { index, y, height }: which of the table's rows it is, counted from 0, the top of the row, and its height, with its borders. A table's header rows are repeated at the top of each page it goes on to, and go on to the next page with the row after them when none of it fits below them.

A footnote or endnote, NoteLayout, is { noteNumber, content }: its number, as its reference shows it, such as "1" or "iv", and its paragraphs and tables on the page.

A blank page that Word adds so a section starts on an odd or even page has nothing on it, and no header or footer, as Word prints it.

layoutDocument doesn't give the lines in table cells, in headers and footers, or where tables are across the page, yet. Each line is where Word puts it, to within a few twentieths of a point.

What it follows

The pages are laid out with the widths and heights of the characters of the fonts Word documents use most: Calibri, Cambria, Arial, Times New Roman and Courier New, and of Office's other fonts that Word installs: Calibri Light, Aptos, Aptos Narrow, Trebuchet MS, Georgia, Verdana, Tahoma, Century Gothic, Consolas, Candara, Corbel, Constantia, Book Antiqua, Franklin Gothic Book, Gill Sans MT and Impact; and the heights of the lines of the Chinese, Japanese and Korean fonts Office has, and how far each goes below its baseline, such as MS Mincho, Yu Gothic, SimSun, Microsoft YaHei, PMingLiU and Malgun Gothic. The widths are those of the letters of Western and Central European languages, Turkish, Vietnamese, Greek and Cyrillic, of punctuation and the spaces other than U+0020, and of currency signs, arrows and mathematical symbols, as Word draws them in each font, plain, bold, italic and bold italic. Italic text in a font without an italic face, such as Tahoma or Impact, is as wide as the upright text, as Word slants it, and Word draws Trebuchet MS bold italic as its bold, slanted. It follows:

  • the document's styles, and each paragraph's and run's own formatting: fonts, sizes, bold, italics, kerning and ligatures (see Kerning and ligatures), capitals, and hidden text. A paragraph whose mark is hidden (run: { vanish: true }) is joined to the next, on its lines, as Word joins it, in its own alignment, left indent and space before, and the next one's space after. Where both are in a list, the next one's number is counted but not shown, so the paragraph after them has the number after it. One with no paragraph after it, before a table or at the end of a table cell or of the document, stays as it is. A paragraph with nothing shown whose mark is hidden, such as one of a hidden style, takes no room, whatever its formatting, as in Word: before another paragraph or a table, and at the end of the document, but for one at the end of a table cell, which is a line of its own. The paragraph after it keeps its own formatting, one in a list takes a number, its fields are counted where it is, and its bookmarks start with what is after it. The paragraphs around it go by its style for their contextual spacing. A page break or picture in hidden text takes no room either. Chinese, Japanese and Korean are in the run's East Asian font (font: { eastAsia }), or in MS Mincho when that font has none of their characters, as Word draws them. A right-to-left run (rightToLeft) is in the run's font, size, bold and italics for complex scripts (font: { cs }, sizeComplexScript, boldComplexScript, italicsComplexScript), as Word draws it
  • lengths given with units, such as margin: { top: "1in" }, size: "12pt" or a table's width: { size: "6in", type: WidthType.DXA }, as well as those given in numbers. Word reads each as a whole number of twips: rounded down from inches, points and picas, and to the nearest from centimeters and millimeters, and a size in points rounded down to a half-point, so size: "10.75pt" is 10.5 points. It reads the minus sign of a negative length as the whole number's only, and adds the fraction: "-10.7pt" is -9.3 points
  • where lines break, as Word breaks them: at spaces, and at en, em, four-per-em and ideographic spaces, which go past the end of a line as spaces do, after hyphens, en and em dashes and zero-width spaces, and between Chinese and Japanese characters. A word breaks at a soft hyphen (SoftHyphen), at the last one whose part of the word and a hyphen fit on the line with a little room left, about a point, with the hyphen at the end of the line, and again on the next line when the rest is longer than a line. A soft hyphen takes no room where the line doesn't break, and a justified line squeezes a word with soft hyphens onto it whole where it would squeeze one without. Word doesn't break lines at the other spaces, such as the thin space, so neither does the layout. In text in Japanese or Chinese (language: { eastAsia: "ja-JP" }), Word's lists keep characters such as closing brackets and 、 from starting a line, and opening brackets from ending one, so the character before moves to the next line with it. Text with no East Asian language, or in Korean or English, has no such rules in Word. Korean, Thai and the other scripts without spaces between words break at their spaces, as Word breaks them, and a word wider than the line breaks after the last character that fits. A paragraph's wordWrap, which writes Word's "Allow Latin text to wrap in the middle of a word", lets the words of runs in an East Asian font or language break anywhere, as Word breaks them. Right-to-left paragraphs (bidirectional) break where left-to-right ones do
  • spacing before and after paragraphs, line spacing, indents and tab stops. A decimal tab stop (TabStopType.DECIMAL) lines up the first full stop of the text after it, such as that of $1,234.50 or e.g. 7, or the end of a number that comes first and has none, such as the 1 of 1 234.5, or else the end of the text, as Word lays it out. Past the end of the line, the text after a right, centred or decimal tab stop of the paragraph's own lines up with the end of the line, or of the next line when it doesn't fit, and a left one takes a line of its own, below the text before it, and the text after it goes to the start of the next line, as Word lays it out. A tab stop between the paragraph's right indent and the margin lines its text up on the line, past the indent. The other cases stop the layout (see below). A line in one font is as tall as Word makes it, to a fraction of a twip (a twentieth of a point): 268.55 twips for Calibri 11. A line in several fonts is as tall as Word makes it from the tallest of them above the baseline and the deepest below it, so a word of Courier New in a line of Calibri 11 makes it 275.53 twips, taller than either font's own line. Multiple line spacing (line with LineRuleType.AUTO) adds its share of the tallest font's own line below the text, and the last line on a page, or in a column, can have that space below the bottom of the page, as Word lays it out, but for the cases it stops at (see below). Contextual spacing (contextualSpacing) leaves out only its paragraph's own share of the space between it and a paragraph of the same style, as Word does: all of its space after, or as much of its space before as is more than the space after the paragraph above it. At the edges of a table cell, Word compares a paragraph with the one next to it in the document: the first cell's first paragraph with the paragraph before the table, and the last paragraph of each row with the end of the row, which is in the default paragraph style, so contextual spacing leaves out the space before a table's first paragraph of the same style as the paragraph before the table, and the space after a row's last paragraph in the default style, such as Normal
  • justified paragraphs (AlignmentType.JUSTIFIED), whose spaces Word squeezes to fit one more word on a line, so they can have more words to a line than left-aligned ones. It squeezes them, in proportion to their widths, when that takes less of their width than a quarter, and than half of what they would stretch by with the word on the next line. Spaces at the start of a line, those before a tab, and no-break spaces aren't squeezed. Distributed paragraphs (AlignmentType.DISTRIBUTE) are squeezed less often, as their letters can stretch too, and Latin text justified for Thai (THAI_DISTRIBUTE) or with a low kashida (LOW_KASHIDA) as justified text is
  • automatic hyphenation (hyphenation: { autoHyphenation: true }), where Word certainly leaves the word after a line whole: in a paragraph that suppresses hyphenation (w:suppressAutoHyphens, in templates), and where its dictionary breaks no word like it. In compatibility mode 15, Word hyphenates a word that doesn't fit at the end of a line whenever a part of it fits with a hyphen, however little room that leaves: it has no hyphenation zone, so hyphenationZone changes nothing. Its English dictionary, which it hyphenates text in English or in no language by, leaves at least two letters before the hyphen, and breaks no word of fewer than five letters, nor numbers. It doesn't hyphenate text not checked for spelling (noProof), or in no language (language: { value: "zxx" }), nor words in capitals, typed so or shown so with allCaps, when the document says so (doNotHyphenateCaps). On a justified line it squeezes a word in rather than hyphenate it, and doesn't squeeze the spaces to fit a part. consecutiveHyphenLimit only leaves more words whole. Which parts Word breaks other words into is in its dictionaries, which the layout doesn't have, so it stops there (see below)
  • paragraph borders (border, and thematicBreak), with the room Word gives them: a border above or below a paragraph takes its width and the space between it and the text, also at the top of a page, and at its foot, where the last line goes to the next page when its border doesn't fit below it. The space before and after goes outside the borders. Paragraphs next to each other with the same borders and the same left and right indents are one box, as Word draws them: the top border above the first, the bottom border below the last, a border between them (between) between each two, and no border where a page breaks the box. Borders at the sides take no room, and leave the lines as wide as they are. Each style takes the room Word gives it: a double line three times its width, a triple line five times, and a wave 3 points whatever its width
  • Word's automatic spacing (beforeAutoSpacing, afterAutoSpacing), as documents made from HTML have it: 14 points, the larger of two between paragraphs, in place of the space given. Word puts none above the first paragraph of the document, a table cell or a header, below the last of a cell, or between the paragraphs of a list, and contextual spacing leaves it out as it does the space given
  • indents in characters (firstLineChars, and the left, right and hanging indents in characters of documents Word made), and space before and after in lines, which Word takes in place of those in twips. A character of a first line or hanging indent is as wide as the paragraph's first character is tall, and one of a left or right indent as its mark, and a hanging indent in characters puts the first line at the left indent and the other lines further in. A line is 12 points, whatever the font
  • keeping a paragraph with the next, keeping its lines together, widow and orphan control, and page breaks
  • numbered and bulleted lists, including those a paragraph's style numbers it in, counted as Word counts them: lists made from the same definition count on from one another, and a list's own first number for a level, which docx writes for each instance of a list, starts that level there at the list's first paragraph of that level. A level starts again after any level above it, or only after the level it gives, or never (w:lvlRestart), and a legal level (isLegalNumberingStyle) writes every level's number in decimal. A number is in its paragraph mark's formatting (run on a Paragraph), but for what its level gives it (style.run), and makes its line taller only above the baseline. A number aligned to the right (AlignmentType.END or RIGHT) ends at the start of its paragraph's first line, and a centred one is centred there, so a wide number can go into the margin, as Word puts it, and the text after it goes on from its end, at the hanging indent or the next tab stop after it. Word measures the space after a number (LevelSuffix.SPACE) in Arial, and so does the layout
  • footnotes, which take room at the bottom of the page their reference is on, and endnotes, which follow the text. A footnote that doesn't fit below its reference continues at the bottom of the next page, as Word continues it: it breaks between its paragraphs and table rows, and inside a paragraph keeping to its widow and orphan control, and its reference's line moves to the next page with it when too little of it would stay. A first paragraph kept together, or kept with the next, stays with its reference whole, with the first lines of what it is kept with. A footnote breaks before a later paragraph kept together, and before paragraphs kept with the next with what they are kept with, as the text does, unless they start its part on the page, which would leave none of it, where it breaks as without them, as the text does at the top of a page. It breaks before a table row whose lines widow control keeps together, and in a row whose lines could go on both pages, between its cells' lines, as a row of the text breaks, with the rest of the row at the top of the next page's footnotes, as Word breaks it. A footnote or endnote that ends with a table has a line below it for the empty paragraph Word puts after the table. A table's header rows aren't repeated above the rest of a footnote on the next page, nor left alone at the bottom of a page, as the table goes on the next page then. The footnote of a line kept with a longer paragraph goes below the first lines of it that the line is kept with, and of one kept with a table, below its first row, and the rest goes on the next page. One longer than a page fills the pages after it, and the text goes on above its end. Before the next section, whether it starts on a new page or not, the rest of a footnote goes on pages of its own, which belong to the section its reference is in, and the new section starts after them. A line whose footnote can't go on a page with it, such as one that starts with a paragraph kept together that is taller than a page, goes at the top of a page, with the text after it, and the footnote starts on the next page, with those referred to after it after it. A table row refers to footnotes as a line does: it moves to the next page with a footnote that doesn't fit below it, and one that breaks across pages has each line's footnote on the page the line is on, and breaks after a line whose footnote continues. Where its footnotes fit whole below fewer of its lines, with the lines that refer to them, it breaks there instead, as Word breaks a row with a table in a cell beside a line whose footnote would otherwise continue. In columns, the footnotes of a page are laid out in the columns too, as Word lays them out: one after the other from the first column, evened out, each part broken at the width of the column it is in, and every column ends above them. Footnotes from another section on the page go on in the columns of its first footnote's. A line or table row in columns whose footnotes don't fit below it moves to the next column, or the next page, with all of them, as Word moves it, and the page is left as it was when a reference moves on as its columns are laid out again for its footnote. At the top of the page's columns, or of the column a section starts in after the section before's, a line stays, and its footnote goes on the page as far as it fits below the lines of every column, with the text going on above it, and continues at the foot of the next page's columns. At the top of a later column, the columns before it are laid out again above as much of the footnote as leaves the line on the page, as Word lays them out: a footnote of 120 lines referred to from line 11 of the first of 2 columns takes 44 lines of each, the columns above it 6, and its reference goes on in the second. The separator above the endnotes goes on the page of their first line, and on each page after the first they are on, the continuation separator is above them, as Word puts them. Each is a line of its paragraph style's text tall, at single spacing, whatever its own spacing, line spacing and size, as Word lays them out. Below the continuation separator, as many lines of endnotes go on the page as fit on it without it, so the last can go past the bottom margin by as much as the separator takes, as Word puts them. Footnotes and endnotes are numbered as Word numbers them, 1, 2, 3 and i, ii, iii, or in the format and from the number a document or its sections give, afresh in each section when they say so
  • run formatting that changes how much room text takes, as Word lays it out. Superscript and subscript (superScript, subScript) are drawn at 65% of the text's size, to the nearest half-point and down from a quarter, so 7 points at 11 and 9.5 at 15, and small capitals (smallCaps) at 80%, so 9 points at 11; both take up the line of their run's own size, so they never make a line taller. Raised and lowered text (position) raises the line's top or lowers its bottom by as much as it goes past the rest of the line: a word raised 6 points makes a line of Calibri 11 120 twips taller, and a smaller word raised a little none. Emphasis marks (emphasisMark) take a quarter of their line, over it, or under it for dots below; line spacing that gives a line a little more room adds it below the marks' room, and spacing that gives it enough, such as 1.5 lines, holds the marks. A border around text (border on a TextRun) takes its space and its width on each side of the text, and above and below it, as wide as a paragraph's border of its style: two runs next to each other with the same border are in one box, a box that goes on to the next line starts again there, and a line keeps room for its box to end after its last word
  • pictures in the line, which stand on the baseline, so a line with text in it is as tall as the picture and the text below the baseline, as Word makes it. A line with a picture is at least as tall as a line of the picture's run's font, and its multiple line spacing adds a share of that, as Word's does
  • pictures, shapes and charts that text wraps around (floating with a wrap), as Word lays the text out around them. A line beside a drawing has the room beside it, with the drawing's distances from the text (margins) and the room its effects take, such as a shape's line or shadow, and a line with no room beside it goes below it. Square, tight and through wrapping put the text beside the drawing's box, on the side or sides its wrapping's side says, the left first, and Word puts as many words in the room on a side as fit there, however narrow it is, and none when the next word doesn't fit. Top and bottom wrapping puts the lines below the drawing. Drawings that overlap keep the text out of all their room. A drawing in a margin, where there is no text, leaves the lines as they are. A line beside a drawing starts at the drawing's edge or the paragraph's left indent, whichever is further in, and its first line is indented from there. A drawing is placed against the page, its margins, the column, or the paragraph or line it is anchored in, as its horizontalPosition and verticalPosition say: at an offset, which places the drawing without its effects, lined up with them, with its effects, or at a percentage of them, as docx/shapes places shapes, and its percentage sizes are a share of the page or its margins. Placed against its paragraph, it is at the top of the paragraph, below the space after the paragraph before, which is that paragraph's, and above its own space before, and no higher than the top of the page's text. Where it would go past the bottom of the page's text, the paragraph moves to the next column or page with it, and a paragraph whose first line goes below a drawing with top and bottom wrapping keeps its own space before above that line. Placed against its line, it is at the line its anchor is on before the text goes round it, though the text going round it can move the anchor on to the next line. One anchored in a line that goes on to the next page goes there with it, against the top of the paragraph's part on that page. The text before a drawing's paragraph on its page goes round it too, as Word lays the page out again with it, and the drawing stays where it was first placed, though its paragraph moves down: with top and bottom wrapping, the lines before it that its distance above it reaches go below it. A table that fits beside a drawing at its indent goes beside it, as does one without an indent that fits past a drawing on its left, and one that doesn't fit goes below it. Paragraphs kept with the next are kept with as many of the next paragraph's lines beside a drawing as they would be without it, and move to the next page with a paragraph that moves there with its drawing. Columns are evened out with the drawings in them. A turned picture wraps the text around its box as it is before it is turned. A drawing that text wraps around in a header or footer, placed against the page or its margins, is on each page that shows the header or footer, and the body's text goes round it as round its own, as Word lays it out. Drawings behind or in front of the text don't move the body's lines
  • tables that text wraps around (a table's float), as Word lays the text out around them: the text after the table goes beside it, as beside a picture with square wrapping, kept from it by its distances from the text (leftFromText, rightFromText, topFromText and bottomFromText). A table is placed across against the page, its margins or the column (horizontalAnchor), and down against the page, its margins or the top of the paragraph after it (verticalAnchor), at a distance (absoluteHorizontalPosition, absoluteVerticalPosition) or lined up with them (relativeHorizontalPosition, relativeVerticalPosition). Its room is as wide as its rows with the halves of its borders left and right, or 0.75 points wider than its rows without borders there, and as tall as its rows, and its indent doesn't move it. It is below the space after the paragraph before, and the paragraph after it has all of its space before below that, as after a table. Tables one after the other before a paragraph each go round it, and the paragraphs after it go round it too while they are beside it
  • text frames (a paragraph's frame) and drop caps, as Word lays them out: the paragraph is taken out of the text and put in a box of its own, which the paragraph after it is anchored in, and the text goes round the box as it goes round a picture with square wrapping. The box is placed against the page, its margins, the column, or the paragraph after it, at the place or lined up as position or alignment says, and its space keeps the text from it, horizontal left and right and vertical above and below. It is as wide as width, or its text when it has none, and as tall as height exactly with the rule HeightRule.EXACT, its text with HeightRule.AUTO, and at least height otherwise, as Word takes a height with no rule. Paragraphs next to each other with the same frame are in one box, with the space before the first and after the last in it. With wrap none, the box is in front of the text and takes no room, and with not beside, the text goes above and below it; around, tight, through and auto are all around it. A drop cap is a frame like any other, as wide as its letter, and the lines of the next paragraph beside it are those its box is beside, as Word lays it out. The bookmarks and fields in a frame are on its anchor's page. The text in frames isn't among the lines of layoutDocument's pages
  • VML drawings (w:pict), as Word lays them out. A text box (Textbox) in the line is sized to its text, as Word sizes it whatever height it has: its paragraphs, broken in its width less 0.2 inches for the room between its edges and its text, with 0.1 inches above and below them and 0.72 points more, and its outline, which takes 0.72 points across and down, or none when it is hidden. It stands on the baseline, as a picture does. A text box placed on the page (position: "absolute") takes no room, as Word puts it in front of the text, as do docx's watermarks. In templates, a shape in the line without an outline is a box of its size, and one placed on the page with square or top and bottom wrapping (w10:wrap) is laid out as a picture with that wrapping, with VML's distances from the text, 9 points left and right, where it gives none
  • equations of text (Math with MathRuns, and a MathFunction alone), as Word lays them out in Cambria Math: letters in italic, unless a run is plain (style: "plain"), digits, operators and brackets upright, each as wide as Word draws it, with the spaces TeX puts between them, as Word puts them: 4 eighteenths of an em either side of a binary operator such as + or ×, 5 either side of a relation such as = or ≤, 3 after punctuation such as a comma and after a function's name, and none beside brackets, bars and slashes. A plus or minus sign at the start, or after an operator, a relation, an opening bracket or punctuation, is unary, with no space. Word's italic correction is added after an italic letter, unless a letter, a digit or another ordinary character follows it. An equation is in its paragraph's style's size, or its run's own, and takes room in its line as text in Cambria Math does, so a line of it beside text is as tall as the tallest ascent and the deepest descent of both. One alone in its paragraph is on a line of its own, centred, as tall as a line of Cambria Math
  • tracked changes, as Word lays them out with its markup in balloons beside the page, or in Simple Markup. Deleted text (DeletedTextRun), and deleted pictures, tabs and breaks, take no room, nor does text moved elsewhere, and inserted text (InsertedTextRun) does. A paragraph whose mark is deleted (run: { deletion }) is joined to the next, all in the next one's formatting, style and list, and a section whose break is deleted goes on into the next, on its pages. A paragraph with no paragraph after it to join, before a table or at the end of a table cell or of the document, stays as it is. A footnote whose reference is deleted isn't laid out, but Word still counts it, so the footnotes after it keep their numbers. A deleted table row (TableRow's deletion) takes no room, nor does the space between cells around it, and the rows around it have one border between them, which is the deleted row's own when it has borders of its own. Nor does a table all of whose rows are deleted take room. A table style's formatting for the first and last rows and for bands of rows goes by each row's place among all the rows, the deleted ones too, so with the first row deleted the second isn't formatted as the first. Word still sizes the columns of a table to their text, or widens them for long words, by its deleted rows and deleted text. Deleted and inserted cells, comments and changes of formatting don't move the lines. A document that asks Word to hide its insertions and deletions, or its markup (w:revisionView), is laid out the same, as Word for Mac opens it in its own view
  • tables, with their columns' widths (columnWidths, or their cells' widths), their rows' heights, cell margins and borders. The columns of a table given no widths are sized to their text, as Word sizes them: each as wide as its longest line, or narrower when they don't all fit, but never narrower than its longest word, and a column whose cells give it a width keeps it. A cell merged across columns (columnSpan) widens them where its longest line needs more room, each in proportion to how wide it is, and a table in a cell counts as wide as its columns. In a table whose cells all have widths, a column with a word longer than its cells give it is widened to fit the word, and the other columns are narrowed to make room, as Word does, unless the table's layout is fixed. A table with a width of its own in twips is fitted to it, as Word fits it: when its columns are narrower, they are widened in proportion, and when they are wider, they are narrowed toward their longest words, or, when its layout is fixed, whatever is in them, each by the same share of the room for its text. When a word is longer than the table, its column is as wide as the word, and the table goes past the margin. Where the rows of a table give a column different widths, each column is as wide as the widest a row gives it, and a cell merged across columns that is wider than they are widens the last of them, before they are fitted to the table's width, or, without one, narrowed to the room, unless its layout is fixed. A word in a cell merged across columns that is longer than they are wide is shared among them in proportion to each column's longest word and its longest line, or its width, added together, as Word shares it, and those columns keep its width when the others are narrowed. Rows break across pages between the lines of their cells, as Word breaks them, keeping to widow and orphan control and lines kept together, and with room on the page for the space after a cell's paragraph that ends there. They move to the next page whole when a cell would have none of its lines on the page, when they are kept whole (cantSplit), and when the page hasn't room for the height they are set to. A row kept whole, or whose paragraph is kept together, that is taller than a page moves to a new page and breaks there as other rows do, and a row set to a height taller than a page takes a page of its own, cut off at its bottom, as Word lays them out. A cell merged down from such a row has its text in it, and the row's footnote starts at the bottom of the next page. A row set to at least a height taller than a page, whose text is taller than a page too, breaks where its text does, and each part of it fills its page. In columns, a row kept whole that is taller than a column goes down only the first column of each page, from the top of a new page unless it is at the top of this one, as a paragraph kept together does. Where a table breaks across pages, Word draws its bottom border below the last of it on the page, which takes room there too, or its cells' own bottom borders. Header rows are repeated at the top of each page and column a table is on, and they aren't left alone at the foot of a page: when none of the row after them goes there, as it is kept whole, kept with the next or set to a height, they go on to the next page with it, as Word moves them. The text of a cell merged down rows (verticalMerge) goes down from below the border above its first row across the others, to above the border below the last, and makes the last of them taller when it needs the room. Where one of its rows breaks across pages, its text breaks with the row, as far down the page as its lines go, keeping to widow control, as Word breaks it, and the rest of it goes on from the top of its rows on the next page, and on across the pages after when it breaks in the last of them. A table in a cell breaks with its row, between its own rows and in them between the lines of their cells, as Word breaks it: as a table in the text breaks, keeping to widow control, with its bottom border below the last of it on the page and its cells' margins around their lines on each page, and with its rows kept whole, or of a set height, moving to the next page whole. On the next page, Word draws its top border above the rest of it, and doesn't repeat its header rows. A table in a cell merged down rows breaks as one in a cell of a row, and so does one with cells merged down its rows whose text is in their first rows. An empty paragraph that ends a cell after a table in it takes no room, as Word lays it out
  • table formatting, as Word lays it out. Borders come from the table's style and the table (borders), side by side, from its cells (TableCell's borders), and from the parts of its style for some of its cells. Where two cells meet, Word draws the heavier of their borders, by its width and a weight for its style, but makes room for the wider, so each row is as much taller as the widest border above its cells and below those above it. Double, triple and the other styles of border take the room Word gives them, such as three times their width for a double border, and a border's space adds to it. A cell's text is as far in from a border beside it as its margin, or half the border when that is more. A row is as tall as its tallest cell's text, with the largest margins above and below of its cells, which needn't be the same cell's. Space between cells (cellSpacing) goes around each cell and inside the table's edges, and the table keeps its width, its columns narrowed for the space as Word narrows them. Each cell's own borders take room inside it, left and right of its text as well as above and below it, and the table's own go around the space. Where such a table breaks across pages, Word draws its bottom border below the last of it on the page, and its top border above the rest of it on the next. A row's own space between its cells is the table's, and space given as a share of the table's width is none, as Word lays them out. A row whose first cell's first paragraph is kept with the next (keepNext) is kept on the page with the next row, or, for the last row, with the paragraph after the table, and rows kept together that don't fit on a page of their own start a new page and break where it ends. Text that runs up or down a cell (textDirection) makes its row only as tall as a line of its paragraph mark, as Word breaks it into lines as long as the row is tall. A table sized to its text that is indented (indent) is sized in the room the indent leaves. The parts of a table style for some cells, such as its first row, its last column or its bands of rows, apply where the table turns them on (tableLook), and where it doesn't say, as Word turns them on: its first row and column and its bands of rows. A header of several rows (tableHeader) is the table's first row, all of it, with the parts for its corner cells in each of its rows, and the bands of rows start below it, as Word applies them, but for a header of three rows with the first row turned off, whose bands start at its first row. A table style's own cell margins apply to its cells, and its own row height doesn't apply, as in Word, and a part of it for some rows gives them its height and not its space between cells. In templates, a row's own table borders and cell margins (w:tblPrEx) apply to its cells, cells merged across columns as old versions of Word wrote them (w:hMerge) are one cell across them, and in a table whose cells all have widths, a cell whose text Word is told not to wrap (w:noWrap) has it wrapped all the same, and text fitted to its cell (w:tcFitText) is on one line a paragraph, as Word lays them out. In templates, an empty last paragraph of a cell whose mark is hidden (w:hideMark) takes no room
  • sections, with their page sizes, margins, columns, headers and footers, how they start, and their page numbering. Page numbers are written in Word's number formats as Word writes them, such as roman numerals, letters, words ("twenty-one") and the numbers of other languages, but for those it leaves blank (see below), and with chapter numbers in front of them (chapterHeadingLevel), such as 2-5 for page 5 of chapter 2. Each column's lines are broken at its own width, so a paragraph that goes on into a column of another width is broken again there, as Word breaks it. Widow control counts the lines left for the next column as they are broken in the column before, as Word counts them, and a table sized to its text keeps the widths it was sized to in each column it goes on into, as Word keeps them, going past the edge of a narrower one. Columns before a continuous section break are evened out, as Word evens them out, unless a column break is in them or a section in them started in the next column, and the next section starts below the longest. A section that starts in the next column (SectionType.NEXT_COLUMN) starts in the next column of the page when the section before has as many columns and one is left, as Word starts it, and on a new page otherwise. When its own columns are of other widths, it is laid out in the page's, where they are and as wide as they are, as Word lays it out, and in its own on the pages after. Its footnotes are laid out in its own columns. A continuous section numbered afresh (pageNumbers: { start }) leaves the page it starts on its number, and numbers the next on from its own first number, as Word does: 8 after a section numbered from 7 starts on page 12. When none of it fits on the page before, the page it starts at the top of is its first, numbered 7. One that starts in the next column of a page numbers on through the document, as Word numbers it. A gutter is beside the page's text, or above it in a document that puts it at the top (w:gutterAtTop), as Word takes it from the page's height, on every page with mirrored margins too, and below a negative top margin, which the header doesn't push the text below. A paragraph kept together that is taller than a column goes down only the first column of each page, as Word lays it out, from the top of a new page unless it is at the top of this one, and what follows it goes on below it. In columns of different widths it does when it is taller than each of them. One taller than some of them but not others goes in the first column, from where it is, that it fits in, as Word moves it: from the top of a narrow first column to a wide second, and past a narrow second column to a new page, in 3 columns or more as in 2, and the paragraphs kept with the next before it go with it. Paragraphs kept with the next before one taller than each column go to the new page with it, unless they are at the top of the page already, and it moves on to the next page, as Word moves them, so they are alone on theirs. A section that ends with a table has a line below it for the empty paragraph that ends the section, as Word has it
  • a section's document grid (grid), as Chinese and Japanese documents and Word's templates for them have it. On a grid of lines (DocumentGridType.LINES), each line takes as many of the grid's lines (linePitch) as its own height needs, with its text in the middle, as Word lays it out: at 360 twips, a line of Times New Roman of up to 15.5 points takes one, and from 16 points two. Multiple line spacing takes the grid's lines times the spacing when that is more, so 1.08 lines are 388.8 twips, at least a height takes that height when it is more, and exact spacing is as it is without the grid. The space before and after a paragraph isn't put on the grid's lines, a line of space before or after (in lines) is one of them, and the room below the last line's text can go below the bottom of the page. The lines of table cells, headers and footers aren't on the grid, nor the lines above footnotes and endnotes, but footnotes and endnotes are. A paragraph whose snapToGrid is off, in documents Word made, isn't on the grid's lines. A grid of lines and characters (DocumentGridType.LINES_AND_CHARS) also adds its charSpace, in 4096ths of a point, after each character, and a quarter of a character more between Chinese, Japanese or Korean characters and Latin letters, as Word does. One that snaps to characters (DocumentGridType.SNAP_TO_CHARS) puts each Chinese, Japanese or Korean character in as many cells as it needs, as many cells as fit across a column at the size of the Normal style's text and the charSpace more, spread evenly across it, and the other text between them on a line in as many cells as it needs together. Characters of indents are the grid's characters. A run with snapToGrid: false isn't on a grid of characters, and headers and footers aren't. Sections whose text direction (page: { textDirection }) runs across the page are laid out as those without one
  • text that runs down the page (page: { textDirection: PageTextDirectionType.TOP_TO_BOTTOM_RIGHT_TO_LEFT }, and the other directions down it of documents Word made), as Chinese and Japanese documents have it, laid out as Word lays it out: each line runs from the top margin to the bottom one, and the lines go across the page from the right margin, or from the left for the directions that put them that way, each as far from the one before as it is tall, on the section's grid if it has one. Chinese, Japanese and Korean characters in fonts whose characters are all an em, such as MS Mincho and SimSun, are an em down the line, and Latin text is on its side, as wide as it is across a page. Indents are from the top and bottom margins, and the space before and after a paragraph is across the page. The header and footer stay across the top and bottom of the page, and a header doesn't push the lines down. A section whose text runs down the page starts a new page after one whose text runs across it, as a continuous section does too

What it leaves blank

It stops at the first thing it can't lay out yet, and the page numbers of the headings and bookmarks after it are left blank, until the fields are updated in Word (see Opening the document in Word):

  • a table that text wraps around (a table's float) where Word's way with it hasn't been seen: one in a table cell, a header, a footer or a note, one without a paragraph after it in its section, one placed without what it is placed against (horizontalAnchor, verticalAnchor) or lined up with the line it would be in, one with a footnote in it or a border on one side only, one kept with the next paragraph or before a paragraph kept with the next, two that may not overlap (overlap: OverlapType.NEVER) and do, and one that would go past the bottom of the page, which Word breaks across pages, with the paragraph after it on the last
  • a text frame where Word's way with it hasn't been seen: one with borders, which take room beside it that their width doesn't explain, one in a header, footer, table cell, footnote, endnote or text box, one with no paragraph after it in its section, such as one before a table, one with a footnote or endnote in it, one whose paragraph and style give it different frames, and one placed against something other than the page, the margins, the column and the paragraph, or lined up in line with the text
  • a VML drawing where Word's way with it hasn't been seen: a text box whose line would break differently in 0.72 points more or less room, one not sized to its text, with insets or an outline of its own, with a footnote, a list or a drawing in it, in a header or footer, or placed on the page with wrapping; a picture (v:imagedata), which Word draws at a size other than its own, a shape in the line with an outline, one placed on the page with tight or through wrapping or an outline, or in a header or footer against its paragraph or line, a shape sized in ems or a share, one turned, and an embedded object (w:object)
  • a picture, shape or chart that text wraps around where Word's way with it hasn't been seen: drawings that may not overlap (allowOverlap: false) and do, which Word moves out of the way, one in a table cell, a footnote or an endnote, one in a header or footer placed against its paragraph, its line or where its anchor is along its line, against a column of a section of several, beside the header's or footer's own text, or on a page of text that runs down it, one beside a table sized to its text, or beside an indented table it would move to the right, one beside paragraphs kept with the next that have drawings of their own or are kept with a table, one in columns evened out after being laid out again for a drawing beside text before it, and one beside the footnotes at the bottom of a page. So does one placed against where its anchor is along its line (HorizontalPositionRelativeFrom.CHARACTER), or by its simple position, one that would go above the page's text with a distance from the text above it, and one that would go past the bottom of the page's text at the top of a page or a column, above footnotes, or only by its distance from the text below it. So does one whose anchor's page changes as the text goes round it, and a page whose text going round a drawing moves the drawing's paragraph to the next page, or that has to be laid out again for its drawings more than 5 times
  • an equation Word builds up, such as one with a fraction, a superscript or subscript, a root, a sum or brackets that grow, or with normal text, another alphabet or bold; one with operators next to each other, or a bracket, bar or slash after an operator, which Word spaces in a way not yet followed; one that doesn't fit on its line, which Word breaks after an operator; a full stop other than a decimal point, a character whose width in Cambria Math isn't known, such as a hyphen, runs of different sizes, formatting other than a size of its own, an empty equation, two equations in one paragraph of equations, a paragraph of equations (m:oMathPara) beside text, more than one equation alone in a paragraph, one alone after its list's number, an equation outside a paragraph, and equations in a maths font other than Cambria Math, or with margins or space around them, in the document's maths settings
  • a footnote that continues on the next page where it would break in a table row across more than two pages, or in one with cells merged down rows, a table in a cell, text running up or down or a height of its own; one that starts with a table row that could break, none of which fits below its reference; a footnote or endnote that ends with a table, in a document whose Normal style and footnote or endnote text style differ; one that continues from a paragraph kept with a paragraph that starts a new page; one that starts on the page after its reference's, before a continuous section that starts on that page; a footnote line, or a line and the start of its footnote, taller than a page; and footnotes after one that starts on the page after its reference's that don't fit below its end
  • endnotes in a section of columns that go on into the next column or page, where Word may put the continuation separator in a way not yet followed, and in templates, an endnote separator with text in it, or of more than a paragraph
  • a footnote in columns too long for the columns of a page, from the top of a later column, where no room for it below the columns leaves its reference on the page; one continued from columns of different widths, below footnotes across the page, or before a section on the same page; a footnote referred to below one that continues from columns; a reference that moves on as its columns are laid out again, on a page with table rows, or to the top of a later column, where a line stays, so the page would be laid out again for the footnote; and a footnote in a section that starts in the next column when none of it fits below the columns of the section before
  • a paragraph kept with the next before a table whose header rows go on to the next page with the row after them, which Word may move with them, and a table's header rows alone at the foot of a column
  • contextual spacing at the edges of table cells Word hasn't been seen with: at the top of a cell after a table's first, the bottom of a cell before a row's last, and in the paragraphs around a table, where the paragraph next to it in the document is of its style
  • a line in a table cell taller than a page, a table row whose paragraph is kept together that is taller than a column, or one set to a height taller than a page in columns, a row set to at least a height taller than a page whose text is taller than a page too, with a footnote, and one set to a height taller than a page with two footnotes or one with others on its page, the text of a cell merged down into it from a row above or out of it that doesn't fit in it, or as a header row
  • a table in a table cell where it breaks across pages with the text of a cell merged down its rows that goes on past the first of them, or with space between its cells
  • the text of a cell merged down table rows that goes on across a page break between its rows, or across more than two pages but in the last of them, and one that goes on across pages from a table's header rows, or with a footnote in it
  • a line whose multiple line spacing would go below the bottom of the page in a table row that breaks across pages, into the footnotes at the bottom of the page, above its paragraph's border below, or below columns evened out before a continuous section break, and a line of only pictures in a paragraph whose mark is in a larger font than the pictures' runs
  • a footnote in a table row that holds back lines of a cell beside it, which would fit on the page above the footnote, and a table row that fits on an empty page, but not with its footnote
  • a table border in a style Word's PDFs haven't shown, such as a picture border, or a wave or 3D border of a width Word doesn't offer, and two cells' borders of different styles that meet beside text whose margin is less than half the wider, where Word draws the narrower
  • space between a table's cells with a long word in a cell, or in a table wider than its cells, the last row of a table with space between its cells that breaks across pages, and such a table with borders and header rows that breaks across pages
  • text that runs up or down a table cell in a row that breaks across pages, in a table sized to its text, with a word longer than its cell, or with paragraph marks of different sizes, a picture or a table in it
  • a table row kept with the next before a row that then moves to the next page whole, such as one of a height that doesn't fit
  • a table whose rows give a column different widths, when its width is a share of the page, it has space between its cells, or a row starts past its first column; a table given no widths of more than 63 columns, more than Word allows; and a word longer than a table with no width of its own in twips can make room for, which Word breaks in a way not yet followed
  • a long word in a cell merged across columns, which Word makes room for in a way not yet followed: a word longer than those columns' longest words together, but not their longest lines, when a table given no widths is narrowed to fit, a word longer than their longest lines with more text beside it in a table given no widths, and one whose share would leave a column narrower than its longest line or its width
  • text in a font that isn't in the width tables, isn't given as a file (see Measuring fonts from their files) and isn't embedded in the document, such as Garamond, Segoe UI or Roboto, so its lines may not be where Word puts them: Word draws it with the font's own widths, or in another font when it doesn't have it, such as Cambria on the Mac. Bold text in a font given or embedded without a bold face stops too, as Word makes the bold face itself, and so does bold text in the fonts of the tables that have none, Calibri Light, Franklin Gothic Book and Impact: Word draws each character 18 thousandths of an em wider than the regular at 10 points, and other sizes haven't been seen
  • kerning and ligatures Word's PDFs haven't shown (see Kerning and ligatures): kerned text in a font whose kerning isn't known, such as Carlito or an East Asian font that isn't monospaced, or with a character outside Windows-1252, such as Greek or Cyrillic, or one that takes no room, such as a zero-width space or a combining mark; kerned Cambria before a hyphen, en dash, no-break space, ™, backslash or à; kerned text with ligatures other than standard and contextual ones in a font Word kerns only without ligatures, such as Trebuchet MS; Times New Roman's discretional ligatures, kerned, beside some characters; ligatures in a font whose ligatures aren't known, of a setting Word's Font dialog doesn't write, in regular Cambria, or beside a character outside Windows-1252; kerning and ligatures across a soft hyphen, and kerned text before one in its font, with which the hyphen Word draws at the end of a line may be kerned; a word longer than its line, kerned or with ligatures, as where Word breaks it hasn't been seen; text kerned or with ligatures on a document grid of characters; and in a font's file, substitutions other than ligatures in the setting's features, such as contextual ones. Text with OpenType number forms or spacing, stylistic sets or contextual alternates (w14:numForm, w14:numSpacing, w14:stylisticSets, w14:cntxtAlts) stops too, as their widths aren't known
  • a character whose width in its font isn't known, so its line may not be where Word puts it: a letter or symbol its font doesn't have, or its font's file has no glyph for, which Word draws in another font, such as most mathematical symbols in Calibri, Arial and Courier New, which Word draws in Cambria Math, and the Greek and Cyrillic letters Gill Sans MT doesn't have, which Word draws in Calibri; a few that Word drew in a way their widths can't be read from, such as Ž and Ё in Courier New; and a symbol font's own symbol, such as Wingdings' tick (SymbolRun), or a symbol whose character isn't four hexadecimal digits
  • in a document that hyphenates its words, a line Word may end with a part of the next word and a hyphen: one with room for the word's first two letters and a hyphen, or its first letter in a language other than English, when the word has five letters or more, or two in such a language. A word longer than its line, a word squeezed onto a distributed line, and a table sized to its text whose columns are narrowed past a word Word may hyphenate, or given less than one, stop it too, as Word sizes columns to the parts of the words it hyphenates
  • a document that compresses its punctuation, or uses Word's strict rules for the characters that can't start a line
  • a soft hyphen where Word hasn't been seen breaking at it: in a justified line the word doesn't fit squeezed onto, in a word whose part before it is longer than its line or that has a border, where its hyphen ends a few twips before the end of the line, and in a table whose columns Word sizes to their text or widens for long words
  • a hidden paragraph mark Word hasn't been seen with, or lays out in a way not yet followed: between paragraphs of different styles or line spacing, or that differ in more than their alignment, left indent and space, at the edge of a content control, ending a section, and between paragraphs of text in a table whose columns Word sizes to their text. So do a paragraph with nothing shown and its mark hidden at the end of a header, footer or note, after a paragraph kept with the next (keepNext), between two with the same borders when it hasn't them, or with a field, note reference or list number after a paragraph joined to the next, and a footnote or endnote reference in hidden text, whose note Word doesn't lay out, but may count in the numbers of the notes after it
  • text at a decimal tab stop whose number ends at something other than a full stop, a space or the end, such as 12%, or after a comma, a decimal tab stop in a document whose decimal symbol isn't a full stop, and one of a paragraph's own tab stops past the end of the line in a paragraph with a first line or hanging indent or indented past the margin, a left one at the start of a line in an indented paragraph, and a right, centred or decimal one at the start of a line or in an indented paragraph, but for a right one indented on the right; and a centred or decimal tab stop past the right indent, one in a justified line, or one whose text goes past the margin
  • borders Word hasn't been seen to draw, or to lay out in a box: a style such as an art border, thin and thick lines narrower than half a point, or wider than 2¼ with a small gap or 3 with a medium or large one, a shadow on a style other than single, or a frame; two paragraphs with the same borders but for a border between them; a box of borders that goes on across a section break, or past a page break before a paragraph in it; and a border in a footnote, or on the empty paragraph that ends a section
  • automatic spacing in a footnote, on the empty paragraph that ends a section, and between the paragraphs of other levels of a list, or of lists made from the same definition
  • indents in characters where the size Word measures them in isn't known: a left or right indent of a paragraph whose mark is another size than its style, a right indent of text of another size than its mark, a first line indent of a list's paragraph whose number is another size than its text, and a hanging indent in characters with a left indent of 0 characters and one in twips, or a left indent in characters with a first line indent in twips
  • a size given in a unit other than points, such as size: "1cm", which Word ignores where no style gives a size, a negative length of a fraction of a centimeter or millimeter, and text lowered by a fraction of its unit, such as position: "-2.5pt"
  • emphasis marks on a line with a picture, with marks both over and under text, at line spacing of less than a line, or between the spacing Word adds below the marks' room and the spacing that holds them, such as 1.25 lines, and with line spacing on a line taller than its fonts' own lines, such as one with raised text
  • on text that runs down the page: a table, a footnote or endnote, a tab, soft hyphen or picture, a drawing that text wraps around, Chinese, Japanese or Korean text in a font whose characters aren't all an em, such as Yu Mincho, half-width characters, a border around text, emphasis marks, raised text, superscript, subscript and small capitals, a paragraph border, a justified line with spaces, a gutter, mirrored margins, columns or a negative margin, a footer that goes above the bottom margin, and a continuous section break after it; and text in a direction Word's documents don't write
  • on a document grid: a grid of characters without the pitch of its lines, a grid that snaps to characters in columns of different widths, and on one, a footnote, text spaced out by its run (characterSpacing), a tab or picture, a soft hyphen, a line beside a drawing that text wraps around, an indent of part of a character, a word longer than its line and a justified line that only fits squeezed; on a grid of lines and characters, a number, punctuation or text of another size next to a Chinese, Japanese or Korean character, which Word may space in a way not yet followed; emphasis marks with line spacing; and endnotes from a section on another grid than the last
  • a border around text of a style or width Word hasn't been seen to draw, as for paragraphs above, or with a shadow or a frame, a tab or picture in text with a border, text with a border lined up with a right or centered tab stop, and a word with a border that is longer than its line
  • a paragraph justified for Arabic with a medium or high kashida (MEDIUM_KASHIDA and HIGH_KASHIDA), and Thai or Arabic text in one justified for Thai or with a low kashida, whose lines Word hasn't been seen breaking, and a justified or distributed line that only fits with its spaces squeezed when it has an en, em or ideographic space, which Word hasn't been seen squeezing
  • page numbers in Thai and Hindi words (thaiCounting and hindiCounting), and page numbers Word writes as an error: any in none, 0 in Hebrew, Arabic, Thai and Hindi digits and Chicago's symbols, and those past where a format's letters run out, such as 781 in letters. Page numbers in Hebrew past 100, and in Hindi letters past 75 (hindiVowels) and 37 (hindiConsonants), haven't been checked in Word yet
  • a chapter number from a heading in a table or a text frame
  • a list number whose text or place Word hasn't shown: one in a format not yet written, such as Thai and Hindi words (thaiCounting, hindiCounting), or past where Word's lists start over, such as 32768 in roman numerals; one that shows a level its list doesn't have, or a level not counted yet that its list starts at a number of its own; a centred number followed by a space; a number with a border or emphasis marks, or raised or lowered; the tab after a number aligned to the right that ends at a tab stop of the paragraph's own, or, without a hanging indent, at the left indent off the default tab stops, or at a default stop past it; a line with nothing but a number of another size or font than its paragraph's mark; and a number taller than its line's text, with multiple line spacing. So do bullets that are pictures, numbers laid out as Word 6 laid them out, lists defined by a list style, and numbers aligned other than to the left, the centre or the right, which docx doesn't write
  • tracked changes Word hasn't been seen laying out: a field only part of which is deleted, a paragraph mark moved elsewhere, a deleted paragraph mark at the edge of a content control, a deleted section break before a table, or between sections that start, number their pages or have headers and footers differently, a deleted endnote reference and a moved note reference, a list or a note in a deleted table row, a cell merged down from a deleted row with something in it, a deleted row whose borders above and below it take different room, or, at the top or bottom of the table, other room than the table's own top or bottom border would, a deleted row in a table with borders and space between its cells, and a deleted row in a header of several rows (tableHeader) whose table style formats some of its rows by where they are, such as its first row or its bands. So are a deleted picture, tab, break or note reference, and a deleted paragraph mark between paragraphs of text, in a table whose columns Word sizes to their text or widens for long words, as it does docx's tables unless their layout is TableLayoutType.FIXED
  • a date or time (a DATE or TIME field, or a DayLong, MonthLong, YearLong and the like) in the text, a footnote or an endnote, as Word writes the date and time it opens the document, whose width changes with them. One in a header or footer is laid out as it is written
  • a page reference, number of pages or page number in a format other than those above, or with a picture Word's text isn't known for, as above, or past what its format writes, such as 781 in letters
  • in a document in compatibility mode, which Word lays out as Word 2010, 2007 or 2003 did (one saved by those versions of Word, or by an application that writes their mode, or given compatibility: { version: 14 }, 12 or 11), what those versions lay out unlike Word 2013 or haven't been seen laying out: a tab to a stop past the end of the line, whose text they put past the margin, a line beside a picture or frame in a gap narrower than 135 points, which they may leave empty, a page break at the end of a paragraph, a table that text wraps around, a table sized to its text in a table cell, indented or as a share of the width, or widened for a long word with no width of its own, a distributed paragraph, or one justified for Thai or with a low kashida, ligatures unless Word's enableOpenTypeFeatures is on, as Word 2010 writes it, and any of the compatibility options, which Word 2013 leaves out in its own mode, but the older ones may follow; and in Word 2007's and 2003's modes, Chinese, Japanese and Korean text and VML drawings that take room. The rest is laid out as in Word 2013's mode, but that justified lines aren't squeezed, so they break as lines aligned left do, and a table sized to its text has its first and last cells' margins beside the page's text, as Word 2010 and before line a table's text up with the margins rather than its borders. A mode Word doesn't have, such as 13, stops the layout
  • a compatibility setting that changes how Word lays out lines in compatibility mode 15 in a way not yet followed: with suppressTopSpacing, the first line of a page or column at at-least line spacing less than its text's height or at multiple spacing, a paragraph's line after its first at the top of a page, and such a line in a table cell, on a document grid, or below the space before a section's first paragraph or a border; with useFELayout, Chinese, Japanese and Korean text, and any text where another of the East Asian compatibility options is on too. suppressTopSpacing is followed otherwise: Word leaves out the space above the text of the first line of a page or column at exact spacing, all but 9.6 points of the 80% of the line above its baseline, and at at-least spacing, all but 9.6 points of the line, and leaves a line of single spacing as it is. useFELayout leaves the lines of other paragraphs as they are. The other compatibility options, which ask for an older Word's or another application's layout, Word lays out lines with as without them in its own mode, so they don't stop it, and doNotUseHTMLParagraphAutoSpacing is followed. In templates, Word's own settings (overrideTableStyleFontSizeAndJustification, enableOpenTypeFeatures, doNotFlipMirrorIndents, differentiateMultirowTableHeaders, useWord2013TrackBottomHyphenation, allowHyphenationAtTrackBottom and allowTextAfterFloatingTableBreak) leave Word's lines as they are too, and those it doesn't know, such as ones a later Word may write, stop it whether they are on or off. Settings for other applications, whose w:uri isn't Word's, are left to them, as Word leaves them
  • in templates, what docx doesn't write and Word lays out in ways not yet followed: space between a row's cells as a share of the table's width, rows with different space between their cells, space between cells of another type than twips, a table indented by a share of the width, a row with table properties of its own other than borders and cell margins, or with borders of its own in a table with space between its cells, a table style with formatting of its rows or cells other than its rows' height and its cells' margins, or a part of one for some cells with properties other than borders, margins, a height for its rows and space between cells, its parts for its bands of rows in a header of four rows or more with its first row turned off, text in a table cell in a direction with East Asian characters upright, text with a phonetic guide, text fitted to a width, or to its cell in a table sized to its text, two lines in one and horizontal in vertical text, ink and other content parts, a subdocument, a paragraph in an HTML division, a table cell whose text doesn't wrap in a table sized to its text, cells merged across columns as old versions of Word wrote them with text after the first, footnotes in columns of their own, footnotes or endnotes numbered afresh on each page, from a number of their own in a section after the first though they number on through the document, or in a format not yet written, footnotes anywhere but at the bottom of the page, endnotes at the end of each section, a footnote or endnote with a mark of its own in place of its number, a content control bound to custom XML or the document's properties that Word fills in with other text than is written in it when it opens the document (one whose text is already the XML's is laid out as it is), pages printed as a folded booklet, styles Word updates from the document's template when it opens it, and an imported document (w:altChunk) in another format than .docx, such as HTML, RTF or plain text, which Word converts its own way, of more than one section, whose formatting is kept as it is (w:matchSrc), with a style of its own where its defaults leave out some of the template's, or with a page reference or number of pages, whose number docx can't write in it

When laying out the pages again with the page numbers it worked out still changes them after three passes, as when a table of contents wraps one way with a number and the other way without it, all of them are left blank, and layoutDocument lays out the pages without them.

A wrong page number is worse than a blank one, so it doesn't guess, unless it is asked to (see Guessing past what it can't lay out).

Guessing past what it can't lay out

Some documents would rather have page numbers that are nearly right than blank ones, such as one in a font docx/layout doesn't have the widths of. Give the document estimatePageNumbersWith({ guess: true }), and the layout goes on past each thing it would stop at, with the best guess it has, rather than leave the page numbers after it blank:

import { Document } from "docx";
import { estimatePageNumbersWith } from "docx/layout";

const doc = new Document({
    pageNumbers: estimatePageNumbersWith({ guess: true }),
    sections: [...],
});

Its guesses, by what it would stop at:

  • text in a font that isn't in the width tables, isn't given as a file and isn't embedded is measured as the most similar font that is: Segoe UI as Calibri, a serif font such as Garamond as Times New Roman, a monospaced one as Courier New, and the others, such as Roboto, as Arial. Word draws them with their own widths, when it has them: in Word's PDF, Segoe UI was 1% wider than its guess and Garamond 3% narrower (word-watertight-text.docx TX18). Bold that Word makes itself is measured as the face it makes it from. A character whose width in its font isn't known is measured as an average letter of the font
  • kerning and ligatures Word's PDFs haven't shown are measured as the layout measures the rest: a pair whose kerning isn't known, or a word longer than its line, as if not kerned, and text either side of a soft hyphen as one word
  • a date or time is measured as it is written, where Word writes the date and time it opens the document
  • a setting or formatting the layout doesn't follow, such as hyphenation, a compatibility setting or mode, a document grid, a text frame or an indent in characters it hasn't seen, is laid out as if it weren't there, a page number in a format it can't write is written in figures, and a table whose widths it can't work out as Word does is sized as it sizes others. A table that text wraps around where Word's way with it hasn't been seen is laid out in the text, as one it doesn't wrap around
  • what it can't read at all, such as a text box, an equation, ink, or a picture or shape that text wraps around in a table cell or a note, is left out, and the rest of its paragraph is laid out without it. Text with a phonetic guide is laid out as its base, what is written in a content control bound to custom XML as it is, and a footnote with a mark of its own as the others are
  • where Word's rule for laying out a page isn't known, such as a footnote that would break in a paragraph kept together, the page is laid out by the rule docx/layout follows that is nearest to it
  • page numbers that still change how the pages are laid out after three passes are written as the last pass worked them out

It still stops where it has no guess: at an imported document (altChunk) it doesn't lay out as Word does (see Templates), such as one in HTML, a content control bound to custom XML whose first block is a table, a table all of whose rows are deleted where what Word does with one of them isn't known, a picture, shape or chart that text wraps around where Word's way with it hasn't been seen, tables that text wraps around that may not overlap and do, and a footnote or table row it can't fit on a page with what it is kept with, or that would go on across pages in columns, which it can't lay out past at all.

The page numbers may then not be Word's. They are written clean all the same, so Word shows them as they are, without asking to update the fields, unless the document has updateFields on. What the estimator gives says where it guessed, in guesses: why it would have stopped, such as "a font not in the width tables", and the page it was laying out then, counted from 1 for the document's first page, whatever number the page shows. The page numbers of what comes after it, from that page on, may not be Word's. With nothing to guess at, it gives what estimatePageNumbers gives.

layoutDocument takes the same option, and each page says what it guessed at on it:

const { pages } = layoutDocument(doc, { guess: true });
pages.forEach((page, index) => page.guesses?.forEach((reason) => console.log(`Guessed at ${reason} on page ${index + 1}`)));

Guessing is off by default, so the page numbers written are Word's, as near as docx/layout knows them, or blank.

Kerning and ligatures

Word kerns text that asks for it (kern on a run or a style, w:kern) from that size up, and joins letters into ligatures in text that asks for them (w14:ligatures, which docx doesn't write, but Word's own Normal template has, as documents and templates Word made do). Word's Normal template kerns from 1 point, which kern: 2 asks for, and has standard and contextual ligatures. The layout does both as Word does, from Word's PDF of every pair of the characters of Windows-1252 kerned in Calibri, Cambria, Arial, Times New Roman and Courier New, plain, bold, italic and bold italic, and the letters Word joined in them with each setting of its Font dialog, and from Word's PDFs of the same in Office's other fonts of the tables, with Normal's ligatures and with all:

  • Kerning brings pairs such as "To" and "AV" nearer, and, in Arial and Times New Roman, an A, L, P, T, V, W or Y nearer the space beside it. Courier New kerns nothing. Pairs across runs of the same font, formatting and language are kerned too, but not across runs of other languages, which Word kerns apart, though it does across runs of other colours. Text kerned from a size larger than it isn't kerned
  • Ligatures: Calibri joins ff, fi, fl, ffi, ffl, ft, tt, tti, ti and others, about 2% narrower than its letters, with standard ligatures and with all; and ch, ck, ct, st and ij with discretional ones. Times New Roman joins fi, fl, ff, ffi, ffl, fj, ffj and Th, much narrower, only with discretional ligatures, and Arial and Courier New join nothing. Cambria draws an f before some letters another way, as wide. Word joins no letters in text with space between its characters (characterSpacing), and joins them across runs as it kerns them. Text either side of hidden or deleted text, or of a paragraph mark that is hidden or deleted, which Word joins to the next, is kerned and joined as if the two were next to each other, which Word's PDFs haven't shown
  • The glyphs ligatures make are kerned with what is beside them as Word kerns them
  • Office's other fonts are kerned as their own files kern them, as Word kerns them, but for a no-break space, which Word kerns as the space in Trebuchet MS and Gill Sans MT, and not at all in Corbel and Constantia. Text with ligatures is kerned only where a font's kerning is in its GPOS table: Word leaves it without kerning in Trebuchet MS, Verdana, Tahoma, Impact, Gill Sans MT and Franklin Gothic Book, whose kerning is in their kern tables alone, and kerns the same text without ligatures. Calibri Light joins letters as Calibri does; Candara, Corbel and Constantia join ff, fi, fl, fb, fh, fj and fk, and ffi, ffl and the like, with Normal's ligatures and with all; Aptos and Aptos Narrow join ff, fi and fl, as wide as their letters, and fj too with all; Tahoma joins ff, fi, fl, ft and st and Consolas fi and fl only with all of them; and Georgia, Trebuchet MS, Verdana, Century Gothic, Book Antiqua, Gill Sans MT, Franklin Gothic Book and Impact join nothing. Word's PDFs showed their ligatures with Normal's setting and with all, so the layout stops at the others in a font that joins letters, and takes a font that joins none with all of them to join none with any. Italic text in a font without an italic face is kerned and joined as upright, and bold text in one without a bold face stops the layout

Where Word's PDFs don't show how it kerns or joins text, the layout stops, as What it leaves blank lists. Fonts given as files are kerned and joined from their own tables (see Measuring fonts from their files).

How close it is

Text in fonts made with the same widths as those five is measured exactly as them: Carlito as Calibri, Caladea as Cambria, Liberation Sans, Arimo and Helvetica as Arial, Liberation Serif and Tinos as Times New Roman, and Liberation Mono and Cousine as Courier New. Text in the fonts the document embeds (fonts) is measured from their files, as Word draws it in them. Text in Aptos, Office's default font since 2023, and Office's other fonts of the tables is measured with Word's own files of them: each word of a line of prose in each of them but Verdana, whose line Word's PDF broke in two, kerned and with ligatures as Word's Normal template has them, is within half a point of where Word puts it, across lines of 1,100 to 1,400 points. Text in other fonts, such as Garamond, stops the layout (see What it leaves blank), unless their files are given (see Measuring fonts from their files). Characters the width tables don't have, such as Hebrew, Arabic and Thai letters, box drawing, shapes such as the bullets ● and ■, and emoji, are measured as an average letter of the font, or an em for emoji. The Latin letters of the East Asian fonts that aren't monospaced, such as Yu Gothic, and East Asian fonts Office doesn't have stop the layout too.

Each change to docx/layout is checked against LibreOffice's layout of a set of documents, and against the pages Word marked in documents it saved. Word lays out some things differently from LibreOffice, so turn updateFields on if the page numbers must be Word's own once the document is opened in Word: Word then asks to update the fields, and works them out again. LibreOffice rounds the height of each line to whole twips, 269 for Calibri 11, so where a line only just fits on a page, it can be on the next page in LibreOffice and on this one in Word, and in docx/layout, which follows Word.

Laying out a document takes about 0.3 seconds per 100 pages in Node.

Measuring with a page's fonts

By default, text is measured with tables of the widths of the characters of those five fonts, which docx/layout has with it, so it lays out the same pages in Node and in every browser. In a browser, it can measure text in the fonts the page has instead, with Pretext, which measures text with a canvas.

docx doesn't come with Pretext. Install it (npm install @chenglou/pretext), give its module to measureWithPretext, and give what that returns to estimatePageNumbersWith, as measureWidth:

import * as pretext from "@chenglou/pretext";
import { Document, HeadingLevel, Paragraph, TableOfContents, TextRun } from "docx";
import { estimatePageNumbersWith, measureWithPretext } from "docx/layout";

// Until a font has loaded, the browser measures text in another one
await document.fonts.ready;

const text = "The harbour was rebuilt after the storm, and this report sets out what it cost and what is left to do. ".repeat(14);

const doc = new Document({
    features: { updateFields: true },
    pageNumbers: estimatePageNumbersWith({
        // Carlito is as wide as Calibri, for a page that has it and not Calibri
        measureWidth: measureWithPretext(pretext, { fontFamilies: { Calibri: "Calibri, Carlito, sans-serif" } }),
    }),
    styles: { default: { document: { run: { font: "Calibri", size: 22 } } } },
    sections: [
        {
            children: [
                new TableOfContents("Contents", { hyperlink: true, headingStyleRange: "1-3" }),
                ...[1, 2, 3, 4].flatMap((chapter) => [
                    new Paragraph({ heading: HeadingLevel.HEADING_1, children: [new TextRun(`Chapter ${chapter}`)] }),
                    new Paragraph(text),
                ]),
            ],
        },
    ],
});

Pretext only measures how wide words and spaces are. The rest is laid out as Word lays it out: lines break where Word breaks them, rather than where a browser would, tabs move to the paragraph's tab stops, and lines are as tall as Word makes them. Their heights still come from the tables, so the layout stops at text in a font that isn't in them, such as Garamond, as how tall Word makes its lines isn't known, unless its file is given too (see Measuring fonts from their files) or the document embeds it.

  • Pretext needs a canvas to measure with: an OffscreenCanvas, or a page's. Node has neither, so use estimatePageNumbers there.
  • Load the fonts before the document is written, such as with document.fonts.load('11pt "Calibri"'). A font that hasn't loaded is measured as the browser's default font, and Pretext keeps the widths it measured.
  • A font the page has under another name, such as a web font, is measured in the CSS font family fontFamilies gives it. Fonts not in it are measured in the font of their own name, or the browser's default font when the page doesn't have one.
  • The page numbers are only as close to Word's as the page's fonts are to the fonts Word has. Laid out in Chrome with Word's own fonts, the headings of the documents docx/layout is checked against were all on Word's page.

measureWidth can be any function that measures how wide text is, in points, in a font with a name, size in points, and whether it is bold or italic:

import { estimatePageNumbersWith } from "docx/layout";

const canvas = new OffscreenCanvas(1, 1).getContext("2d")!;

const estimatePageNumbers = estimatePageNumbersWith({
    measureWidth: (text, { name, size, bold, italic }) => {
        canvas.font = `${italic ? "italic " : ""}${bold ? "bold " : ""}${size}pt "${name}"`;
        return canvas.measureText(text).width * 0.75;
    },
});

Space between characters, and text scaled wider or narrower, are added to what it measures, as the document's formatting gives them.

Measuring fonts from their files

To measure text in other fonts as Word does, in Node or in a browser, give estimatePageNumbersWith their font files, as fonts:

import { readFile } from "node:fs/promises";
import { Document } from "docx";
import { estimatePageNumbersWith } from "docx/layout";

const doc = new Document({
    pageNumbers: estimatePageNumbersWith({
        fonts: [
            { data: await readFile("Aptos.ttf") },
            { data: await readFile("Aptos-Bold.ttf") },
            { data: await readFile("Aptos-Italic.ttf") },
        ],
    }),
    styles: { default: { document: { run: { font: "Aptos", size: 24 } } } },
    sections: [...],
});

In a browser, give it the bytes of a file the page fetched, such as await (await fetch("Aptos.ttf")).arrayBuffer(). docx doesn't come with any font files.

  • The files are TrueType or OpenType fonts (.ttf or .otf), or collections of them (.ttc), as bytes: a Uint8Array, such as a Node Buffer, or an ArrayBuffer. Web fonts (.woff and .woff2) are compressed, and can't be read.
  • Each file is one face of a font, such as Aptos Bold, or a collection of faces, such as Cambria and Cambria Math in cambria.ttc, each of which is measured. The name of each face and whether it is bold or italic are read from it. Give a file for each face the document uses. Bold text in a font without a bold file is measured as it would be without the files, so it stops the layout when the font isn't in the width tables, as Word makes the bold face itself, and italic text without an italic file is measured with the upright one. To measure a font with a file of another name, give the name the document uses, such as { data: carlito, name: "Calibri" }, which every face in the file is given.
  • Widths are the font's own. The layout stops at a character the file has no glyph for, as Word draws it in another font (see What it leaves blank).
  • Kerning is applied as Word applies it: only to text that asks for it, with kern on a run or a style (w:kern), and only to text of that size or larger. kern: 2 kerns text from 1 point, as Word's own Normal template does. The pairs are the font's, from its GPOS table, or its kern table when it has no GPOS table, and pairs across runs in the same font are kerned too.
  • Ligatures join letters as Word joins them, in text that asks for them (w14:ligatures): with the ligatures of the font's GSUB table of the kinds the setting names, such as the standard ligatures of Aptos's ff, fi and fl for Word's Normal template's standard and contextual ligatures. The layout stops at text a substitution of another kind in those features could change, such as Cambria's contextual ones.
  • The height of a line is the font's, as Word works it out: its ascent and descent for Windows and the gap between lines it adds to them, or its typographic ascent, descent and line gap when the font says to use them, as Aptos does. The line goes that descent below its baseline, with the gap above the text, which is what a line of it and another font, or a picture, is made from.

Text in fonts without files is measured as it is without them: with the width tables, or as measureWidth measures it when it is given too.

Fonts the document embeds

Text in the fonts a document embeds is measured from the files it embeds, with nothing more given to the estimator: the fonts docx embeds with the fonts option, each as the regular face of the font of the name it is given, and those a template Word saved embeds ("Embed fonts in the file"), each as the face Word embedded it as. Bold text in a font embedded without a bold face stops the layout, as it does with a file given without one. A file the document embeds that isn't a font, or is damaged, is left out, so text in its font stops the layout. When a font the document embeds is given as a file too, the document's own file is measured.

import { readFile } from "node:fs/promises";
import { Document } from "docx";
import { estimatePageNumbers } from "docx/layout";

const doc = new Document({
    pageNumbers: estimatePageNumbers,
    fonts: [{ name: "Pacifico", data: await readFile("Pacifico.ttf") }],
    styles: { default: { document: { run: { font: "Pacifico", size: 22 } } } },
    sections: [...],
});