feat(layout): read a .docx into the layout, to write a template's page numbers and check Word's own pages (#3619)

* feat(layout): read a .docx into the layout, to write a template's page numbers and check Word's own pages

docx/layout read only the document being written, from its formatted
XML. A second adapter, read-docx.ts, reads a parsed .docx into the same
blocks: it follows the package's relationships to the main document and
its styles, theme, numbering, settings, headers, footers and notes, and
reads them with the same reader, which now takes a document's parts
rather than context.file.

patchDocument takes the same estimatePageNumbers as Document, as its
pageNumbers. Once the patches are in, it gives the estimator the
template's parsed parts and writes the page numbers into the PAGEREF,
NUMPAGES and SECTIONPAGES fields of its body, headers and footers. The
numbers a template was saved with are those from before it was filled
in, so one the layout can't work out is left blank. The writing of the
fields is shared between formatted and parsed trees.

A document in compatibility mode stops the layout: Word lays it out as
an older version of Word did, which isn't followed. LibreOffice writes
mode 12, and docx writes 15.

compare-layout.ts lays out documents Word saved through the adapter, and
compares them with the pages Word marked with w:lastRenderedPageBreak,
read with the rules Word's PDFs of the layout demos showed, and with
Word's PDFs. The 7 demos whose marks have all their pages are committed
in scripts/layout-probes, so CI checks docx/layout against Word's own
pages. A new demo fills a template in with patchDocument and writes its
page numbers.

* fix(layout): fail the layout comparison when there are no documents saved from Word to compare

compare-layout.sh copied the documents saved from Word in
scripts/layout-probes into its output directory only if they were there,
so when the glob found none, as when the script runs from another
directory, Word's own pages weren't compared and the comparison passed
anyway. It now stops with an error. compare-layout.ts still compares a
directory without them, as it does when run on its own.

* fix(layout): compare documents saved from Word only with the pages Word marked in them

compare-layout.ts compared each document saved from Word with Word's PDF
of the demo of the same name too. When a demo changes, as columns did in
#3611, Word's PDF is made again of the new demo, and no longer is of the
document Word saved, so the two disagreed although docx/layout matched
both. A document saved from Word has Word's own pages in its marks, so it
is compared only with them, and one whose marks don't have all its pages
isn't compared.

* fix(layout): fail the layout comparison when a committed document saved from Word can't be compared

The documents saved from Word in scripts/layout-probes are committed
because Word's marks have all their pages. One whose marks no longer read
as having them all was skipped without failing, so a mistake in reading
Word's pages would have turned off the check in CI. It now fails. A
document only in the output directory whose marks don't have all its
pages, as Word's columns and long-table-of-contents, is still left out.
This commit is contained in:
Dolan
2026-10-02 01:48:30 +01:00
committed by GitHub
parent eee355bff2
commit e008c45c0c
28 changed files with 1455 additions and 290 deletions
+66
View File
@@ -0,0 +1,66 @@
// The page numbers of a template's table of contents, written by docx/layout once patchDocument has filled the template
// in, so they are those of the filled-in document. See docs/usage/layout.md.
import * as fs from "fs";
import { Document, Footer, HeadingLevel, Packer, PageNumber, Paragraph, PatchType, TableOfContents, TextRun, patchDocument } from "docx";
import { estimatePageNumbers } from "docx/layout";
// Words of different lengths, so the lines wrap in different places
const WORDS =
"the survey of the coast found that the old harbour wall had moved in the winter storms and that the new one would need deeper footings".split(
" ",
);
const text = (words: number, seed: number): string =>
Array.from({ length: words }, (_, index) => WORDS[(index * 7 + seed * 5) % WORDS.length]).join(" ");
const CHAPTERS = ["The coast", "The harbour wall", "The footings", "The costs", "What is left to do"];
// A report template, as it might be made in Word: a table of contents, and a placeholder for each chapter's text. Its
// table of contents has no page numbers yet
const template = new Document({
features: { updateFields: true },
sections: [
{
footers: {
default: new Footer({
children: [
new Paragraph({
children: [new TextRun({ children: ["Page ", PageNumber.CURRENT, " of ", PageNumber.TOTAL_PAGES] })],
}),
],
}),
},
children: [
new TableOfContents("Contents", { hyperlink: true, headingStyleRange: "1-3" }),
...CHAPTERS.flatMap((title, index) => [
new Paragraph({ heading: HeadingLevel.HEADING_1, children: [new TextRun(title)] }),
new Paragraph(`{{chapter${index + 1}}}`),
]),
],
},
],
});
// Each chapter's text, of a different length, so the chapters move to later pages once the template is filled in
const chapterText = (chapter: number): readonly Paragraph[] =>
Array.from(
{ length: 2 + ((chapter * 3) % 5) },
(_, index) => new Paragraph(text(80 + ((chapter * 29 + index * 17) % 90), chapter + index)),
);
Packer.toBuffer(template)
.then((data) =>
patchDocument({
outputType: "nodebuffer",
data,
patches: Object.fromEntries(
CHAPTERS.map((_, index) => [`chapter${index + 1}`, { type: PatchType.DOCUMENT, children: chapterText(index + 1) }]),
),
// Lays out the filled-in document's pages as Word would, and writes the page numbers of its table of contents
// and its number of pages
pageNumbers: estimatePageNumbers,
}),
)
.then((buffer) => {
fs.writeFileSync("My Document.docx", buffer);
});
+25 -1
View File
@@ -77,6 +77,29 @@ Word still asks when:
- a table of contents is given `beginDirty: true`
- the document has a `SequentialIdentifier`, a SEQ field, which is written for Word to number
## Templates
[`patchDocument`](usage/templates.md) 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:
```ts
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](#opening-the-document-in-word)). What `estimatePageNumbersWith` returns works the same way.
`patchDocument` doesn't add entries to a table of contents for the headings patches add. Word adds them when it updates the table.
## 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 the heights of the lines of the Chinese, Japanese and Korean fonts Office has, such as MS Mincho, Yu Gothic, SimSun, Microsoft YaHei, PMingLiU and Malgun Gothic. It follows:
@@ -109,6 +132,7 @@ It stops at the first thing it can't lay out yet, and the page numbers of the he
- a document that hyphenates its words, compresses its punctuation, or uses Word's strict rules for the characters that can't start a line
- 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
- a document in compatibility mode, which Word lays out as an older version of Word did: one saved by Word 2010 or earlier, or by an application that writes an older mode, such as LibreOffice, or given an older `compatibility` `version`
A wrong page number is worse than a blank one, so it doesn't guess.
@@ -116,7 +140,7 @@ A wrong page number is worse than a blank one, so it doesn't guess.
Text in fonts other than those five is measured as the most similar of them, so its page numbers are rougher. Aptos, Office's default font since 2023, is measured as Arial. In a browser, text can be measured in the fonts the page has instead (see [Measuring with a page's fonts](#measuring-with-a-pages-fonts)). Letters the fonts have no widths for, such as Greek, Cyrillic, Hebrew, Arabic and Thai, are measured as an average letter of the font, and East Asian fonts Office doesn't have as MS Mincho or MS Gothic.
Each change to `docx/layout` is checked against LibreOffice's layout of a set of documents. 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.
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.
+2
View File
@@ -45,6 +45,8 @@ The patcher also takes in a `keepOriginalStyles` boolean, which will preserve th
It also takes in `footnotes` and `endnotes`, for the notes that patches refer to with a `FootnoteReferenceRun` or an `EndnoteReferenceRun`. See [Footnotes and endnotes](usage/templates.md#footnotes-and-endnotes).
Given `estimatePageNumbers` from `docx/layout` as its `pageNumbers`, it writes the page numbers of the template's tables of contents and page references, and its numbers of pages, once the patches are in. See [Page numbers](usage/templates.md#page-numbers).
A patch can also be for a drawing whose alt text holds the placeholder, rather than for text: `ChartDataPatch` from `docx/charts` gives a chart made in Word new data, keeping its look. See [Charts in Templates](usage/chart-templates.md).
### How to patch existing document
+21
View File
@@ -337,6 +337,27 @@ The ids only link each reference to its note. In the patched document, each note
A template that has no footnotes or endnotes yet is given what they need, including the styles that show their numbers as superscript.
### Page numbers
A template's table of contents, page references and numbers of pages show the page numbers the template was saved with, which the patches can change. Give `patchDocument` `estimatePageNumbers` from `docx/layout` as its `pageNumbers`, and it lays out the filled-in document's pages as Word would, and writes their numbers:
```ts
import * as fs from "fs";
import { patchDocument, PatchType, TextRun } from "docx";
import { estimatePageNumbers } from "docx/layout";
const doc = await patchDocument({
outputType: "nodebuffer",
data: fs.readFileSync("Report template.docx"),
patches: {
name: { type: PatchType.PARAGRAPH, children: [new TextRun("John Doe")] },
},
pageNumbers: estimatePageNumbers,
});
```
Its page references and tables of contents are written clean, so Word shows the numbers as they are, rather than asking to update the fields when it opens the document. See [Layout](usage/layout.md#templates) for what it follows, and what it leaves blank.
## Preserving Styles
Set `keepOriginalStyles: true` to preserve the formatting of the placeholder text:
+16 -1
View File
@@ -14,6 +14,10 @@
# named after the demo with .word.pdf, such as text-and-spacing.word.pdf, in the output directory. Its text is written to
# a .word.txt the next time this runs. Word's PDFs are kept, so delete them when the demos change.
#
# Documents saved from Word, as .docx files named with .word.docx, such as text-and-spacing.word.docx, are compared with
# the pages Word wrote into them (see scripts/compare-layout.ts). Those committed in scripts/layout-probes are copied in,
# unless the output directory has one of the same name, and any in the output directory are kept.
#
# The pages are laid out with LibreOffice (set SOFFICE if soffice isn't on the PATH) and pdftotext from Poppler. When
# SHAPE_RENDER_IMAGE names a Docker image built from scripts/shape-demos/Dockerfile, they are laid out in it, with its
# pinned LibreOffice and fonts, as CI does.
@@ -31,7 +35,18 @@ fi
SOFFICE="${SOFFICE:-soffice}"
mkdir -p "$OUT"
find "$OUT" -maxdepth 1 \( -name "*.docx" -o -name "*.txt" -o \( -name "*.pdf" -not -name "*.word.pdf" \) \) -delete
find "$OUT" -maxdepth 1 \( \( -name "*.docx" -not -name "*.word.docx" \) -o -name "*.txt" -o \( -name "*.pdf" -not -name "*.word.pdf" \) \) -delete
# Without them, Word's own pages wouldn't be compared at all, and the comparison would pass without them
SAVED=(scripts/layout-probes/*.word.docx)
if [ ! -f "${SAVED[0]}" ]; then
echo "No documents saved from Word in scripts/layout-probes: run this from the root of the repository" >&2
exit 1
fi
for saved in "${SAVED[@]}"; do
if [ ! -f "$OUT/$(basename "$saved")" ]; then
cp "$saved" "$OUT/"
fi
done
FILES=()
for demo in "${DEMOS[@]}"; do
+190 -3
View File
@@ -1,6 +1,7 @@
/**
* Compares the page numbers docx/layout wrote into the tables of contents of the documents scripts/compare-layout.sh
* made with the pages LibreOffice put their headings on, and Word, when PDFs of them saved from Word are there.
* made with the pages LibreOffice put their headings on, and Word, when PDFs of them saved from Word are there. Then it
* compares docx/layout with Word's own pages in documents saved from Word, through the .docx adapter.
*
* Usage: npm run run-ts -- scripts/compare-layout.ts [directory]
*
@@ -12,6 +13,14 @@
* heading's page number isn't LibreOffice's or Word's, or is left blank, when the number of pages written into a NUMPAGES
* field isn't the number of pages of LibreOffice's or Word's PDF, and when there is no text of LibreOffice's pages of a
* document, as when it couldn't convert it.
*
* A document saved from Word, named after it with .word.docx, such as text-and-spacing.word.docx, has Word's own pages:
* Word writes a w:lastRenderedPageBreak where each page began when it last laid the document out. docx/layout lays out
* the document Word saved, read through the .docx adapter as patchDocument's templates are, and each bookmark a page
* reference refers to, such as each heading of a table of contents, is compared with the page Word put it on. It fails
* when one isn't on Word's page, and when the number of pages isn't Word's. A document whose marks don't have all of
* Word's pages (see wordPagesOf) isn't compared, and fails when it is one committed in scripts/layout-probes, which are
* there because their marks have them all.
*/
import { existsSync, readFileSync, readdirSync } from "node:fs";
import { join } from "node:path";
@@ -19,6 +28,8 @@ import { join } from "node:path";
import JSZip from "jszip";
import { type Element, xml2js } from "xml-js";
import { estimatePageNumbers } from "../src/layout/estimate-page-numbers";
const directory = process.argv[2] ?? "build/layout";
/** The text of an element, with its tabs, leaving out field instructions */
@@ -90,6 +101,122 @@ const pageCountsOf = async (path: string): Promise<readonly string[]> => {
return results;
};
/** The first element of the name in an element, in document order */
const findElement = (element: Element, name: string): Element | undefined =>
element.name === name
? element
: (element.elements ?? []).reduce<Element | undefined>((found, child) => found ?? findElement(child, name), undefined);
/** The XML parts of a .docx, parsed as patchDocument parses them, by their paths */
const partsOf = async (path: string): Promise<ReadonlyMap<string, Element>> => {
const zip = await JSZip.loadAsync(readFileSync(path));
const paths = Object.keys(zip.files).filter((file) => file.endsWith(".xml") || file.endsWith(".rels"));
return new Map(
await Promise.all(
paths.map(
async (file) =>
[
file,
xml2js(await zip.file(file)!.async("string"), { compact: false, captureSpacesBetweenElements: true }) as Element,
] as const,
),
),
);
};
/**
* Word's pages of a document it saved, read from the w:lastRenderedPageBreak elements Word writes where each page began
* when it last laid the document out: the page each bookmark starts on, as of the first text after it, and the number
* of pages. Also each bookmark's paragraph's text, and the bookmarks page references refer to.
*
* Word's PDFs of the layout demos showed where it writes them, and where it doesn't:
*
* - a row that breaks across pages has one in each of its cells that goes on to the next page, which are one page
* - the row or paragraph just after a row that broke across pages starts with one, though it is on the same page
* - there is none for the blank page before a section that starts on an odd or even page, so one is added when the
* section would start on a page of the other kind, with pages counted from 1
* - there is none where a column break starts a page, in a table of contents, nor on the pages Word hadn't laid out yet
* when it saved the document, so the pages read are only Word's when there are as many of them as Word says the
* document has (`Pages` in docProps/app.xml)
*/
const wordPagesOf = (
document: Element,
): {
readonly pages: ReadonlyMap<string, number>;
readonly titles: ReadonlyMap<string, string>;
readonly referred: readonly string[];
readonly pageCount: number;
} => {
const pages = new Map<string, number>();
const titles = new Map<string, string>();
const referred = new Set<string>();
// How each section starts, from its properties at its end
const starts: string[] = [];
const findSections = (element: Element): void => {
if (element.name === "w:sectPr") {
starts.push(String(element.elements?.find(({ name }) => name === "w:type")?.attributes?.["w:val"] ?? "nextPage"));
}
(element.elements ?? []).forEach(findSections);
};
findSections(document);
let page = 1;
let section = 0;
let sectionStarted = false;
let waiting: string[] = [];
// Whether a row just broke across pages, so a mark before any text after it is on the same page
let afterBrokenRow = false;
// The row being read: whether it has had a mark, which is its page's, and text, and whether it broke across pages
let row: { counted: boolean; text: boolean; broke: boolean } | undefined;
const read = (element: Element, paragraph: Element | undefined): void => {
if (element.name === "w:lastRenderedPageBreak") {
if (afterBrokenRow) {
afterBrokenRow = false;
} else if (!row?.counted) {
page++;
row = row && { ...row, counted: true };
}
row = row && { ...row, broke: row.broke || row.text };
} else if (element.name === "w:bookmarkStart") {
const name = String(element.attributes?.["w:name"]);
waiting.push(name);
titles.set(name, collapsed(paragraph ? textOf(paragraph) : ""));
} else if (element.name === "w:instrText") {
const reference = /^\s*PAGEREF\s+("?)([^\s"\\]+)\1/i.exec(textOf({ ...element, name: "w:t" }));
if (reference) {
referred.add(reference[2]);
}
} else if ((element.name === "w:t" && textOf(element).length > 0) || element.name === "w:tab" || element.name === "w:drawing") {
const start = starts[section];
if (sectionStarted && ((start === "oddPage" && page % 2 === 0) || (start === "evenPage" && page % 2 === 1))) {
// The blank page before it
page++;
}
sectionStarted = false;
afterBrokenRow = false;
row = row && { ...row, text: true };
waiting.forEach((name) => pages.set(name, page));
waiting = [];
} else if (element.name === "w:tr" && !row) {
row = { counted: false, text: false, broke: false };
(element.elements ?? []).forEach((child) => read(child, paragraph));
afterBrokenRow = row.broke;
row = undefined;
} else {
(element.elements ?? []).forEach((child) => read(child, element.name === "w:p" ? element : paragraph));
// A paragraph whose properties have its section's ends the section
if (
element.name === "w:p" &&
element.elements?.find(({ name }) => name === "w:pPr")?.elements?.some(({ name }) => name === "w:sectPr")
) {
section++;
sectionStarted = true;
}
}
};
read(document, undefined);
return { pages, titles, referred: [...referred], pageCount: page };
};
/** The pages of a PDF's text, each as its lines, or undefined when there is no such file */
const pagesOf = (path: string): readonly (readonly string[])[] | undefined =>
existsSync(path)
@@ -109,7 +236,7 @@ const pageCounts = new Map(REFERENCES.map(({ name }) => [name, { compared: 0, ma
// The documents LibreOffice didn't lay out, which aren't compared
const notLaidOut: string[] = [];
for (const name of readdirSync(directory)
.filter((file) => file.endsWith(".docx"))
.filter((file) => file.endsWith(".docx") && !file.endsWith(".word.docx"))
.sort()) {
const entries = await entriesOf(join(directory, name));
const references = REFERENCES.flatMap((reference) => {
@@ -151,6 +278,53 @@ for (const name of readdirSync(directory)
}
}
// Documents saved from Word, laid out through the .docx adapter, and compared with the pages Word marked in them. Each has
// Word's own pages in it, so it stays a check of docx/layout when the demo it was saved from changes, as Word's PDF of
// the demo doesn't
const saved = { compared: 0, matched: 0 };
const savedPageCounts = { compared: 0, matched: 0 };
// The documents whose marks don't have all of Word's pages, which aren't compared, and those of them that are committed
const notMarked: string[] = [];
const notMarkedCommitted: string[] = [];
for (const name of readdirSync(directory)
.filter((file) => file.endsWith(".word.docx"))
.sort()) {
const parts = await partsOf(join(directory, name));
const marked = wordPagesOf(parts.get("word/document.xml")!);
// The number of pages Word had laid out when it saved the document
const app = parts.get("docProps/app.xml");
const pagesElement = app && findElement(app, "Pages");
const laidOut = pagesElement ? Number(textOf(pagesElement)) : undefined;
if (laidOut !== marked.pageCount) {
// Those committed in scripts/layout-probes are there because their marks have all their pages, so one that doesn't
// is read wrong, and fails
const committed = existsSync(join("scripts", "layout-probes", name));
console.log(
`\n${name}, saved from Word: ${committed ? "FAIL, " : ""}its marks have ${marked.pageCount} of its ${laidOut ?? "unknown"} pages, so it isn't compared`,
);
notMarked.push(name);
notMarkedCommitted.push(...(committed ? [name] : []));
continue;
}
console.log(`\n${name}, saved from Word`);
const estimate = estimatePageNumbers({ parts });
for (const bookmark of marked.referred.filter((referredTo) => marked.pages.has(referredTo))) {
const page = estimate.bookmarks.get(bookmark) ?? "";
const found = String(marked.pages.get(bookmark));
saved.compared++;
saved.matched += page === found ? 1 : 0;
console.log(
`${page === found ? " ok " : " FAIL"} ${marked.titles.get(bookmark)!.slice(0, 50).padEnd(50)} docx/layout ${(page || "blank").padStart(5)} ${page === found ? " " : "*"}Word ${found.padStart(4)}`,
);
}
const counted = String(estimate.pageCount ?? "");
savedPageCounts.compared++;
savedPageCounts.matched += counted === String(laidOut) ? 1 : 0;
console.log(
`${counted === String(laidOut) ? " ok " : " FAIL"} ${"Number of pages".padEnd(50)} docx/layout ${(counted || "blank").padStart(5)} ${counted === String(laidOut) ? " " : "*"}Word ${String(laidOut).padStart(4)}`,
);
}
console.log("");
for (const [reference, { compared, matched }] of counts) {
if (compared > 0) {
@@ -162,9 +336,22 @@ for (const [reference, { compared, matched }] of pageCounts) {
console.log(`${matched} of ${compared} numbers of pages are ${reference}'s`);
}
}
if (saved.compared > 0) {
console.log(
`${saved.matched} of ${saved.compared} headings are on Word's page in the documents saved from Word, laid out through the .docx adapter`,
);
console.log(`${savedPageCounts.matched} of ${savedPageCounts.compared} numbers of pages are Word's in the documents saved from Word`);
}
if (notMarked.length > 0) {
console.log(`Word's marks don't have all the pages of ${notMarked.join(", ")}, which aren't compared`);
}
if (notLaidOut.length > 0) {
console.log(`LibreOffice didn't lay out ${notLaidOut.join(", ")}`);
}
process.exit(
notLaidOut.length === 0 && [...counts.values(), ...pageCounts.values()].every(({ compared, matched }) => compared === matched) ? 0 : 1,
notLaidOut.length === 0 &&
notMarkedCommitted.length === 0 &&
[...counts.values(), ...pageCounts.values(), saved, savedPageCounts].every(({ compared, matched }) => compared === matched)
? 0
: 1,
);
+15
View File
@@ -125,3 +125,18 @@ heights over many lines.
When Word's rule for something isn't known, write a probe in the shape of `word-rules2.ts`, with a reader for its PDF, and have
it saved from Word as a PDF with the same name as its `.docx`. Commit the `.docx`, the PDF and the reader beside the
script, and leave out LibreOffice's PDFs, `pdftotext`'s HTML, SVG pages and Word's `~$` lock files.
## Documents saved from Word
Each `<demo>.word.docx` is a layout demo, as `scripts/compare-layout.sh` writes it, opened in Word 16 for Mac in Print
Layout, with No to updating the fields, and saved as a Word Document once Word had laid out all its pages (2026-10-01).
Word writes a `w:lastRenderedPageBreak` where each page began, and the number of pages in `docProps/app.xml`.
`scripts/compare-layout.sh` copies them into its output directory, and `scripts/compare-layout.ts` lays each out through
the `.docx` adapter, as `patchDocument` lays out a template, and compares the page of each heading in its table of
contents with the page Word marked it on. Word's PDFs of the same documents showed where Word writes the marks, and where
it doesn't (see `wordPagesOf` in `scripts/compare-layout.ts`).
`columns` and `long-table-of-contents` aren't here: Word writes no mark where a column break starts a page, nor in a
table of contents, so their marks don't have all of Word's pages. Word's PDFs of them put all their headings on the
pages docx/layout puts them on.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,254 @@
/**
* Writes estimated page numbers into the fields of a tree of elements that show them: those docx formats to write a
* document, and those `patchDocument` parses from a template. Not part of the public API.
*
* A page reference is a PAGEREF field, and the numbers of pages of the document and of a section are NUMPAGES and
* SECTIONPAGES fields. Each field's result is written just after its `separate` field character, and any result it had
* is taken out.
*
* @module
*/
import type { EstimatedPageNumbers } from "./page-numbers";
/**
* How the elements of a tree are read and changed.
*/
export type ElementTree<E> = {
/** The element's name, such as "w:r", or undefined for text, and for a formatted element's attributes */
readonly nameOf: (element: E) => string | undefined;
/** The element's content, which can be changed in place, or undefined when it has none */
// eslint-disable-next-line functional/prefer-readonly-type
readonly contentOf: (element: E) => E[] | undefined;
readonly attributeOf: (element: E, attribute: string) => unknown;
/** The text directly in the element, such as an instruction's */
readonly textOf: (element: E) => string;
/** A `w:t` element of the text */
readonly textElement: (text: string) => E;
/**
* Writes clean the beginning (`w:fldChar` of type `begin`) of a field whose result is a page number, once its
* instruction is read, when the field would otherwise make Word ask to update the fields
*/
readonly writeClean: (begin: E, instruction: string) => void;
/** Makes a simple field's result (`w:fldSimple`) a run of the text, keeping the field's attributes */
readonly setSimpleFieldResult: (element: E, text: string) => void;
};
/** A complex field being read: its beginning, its instruction, and whether its result has been reached */
type OpenField<E> = {
readonly begin: E;
// eslint-disable-next-line functional/prefer-readonly-type
instruction: string;
// eslint-disable-next-line functional/prefer-readonly-type
inResult: boolean;
/** The result it is written with */
// eslint-disable-next-line functional/prefer-readonly-type
result?: string;
};
/** How the fields of a part of a document are filled in */
type FieldFilling<E> = {
/** The result of a field, from its instruction, or undefined to leave the field as it is */
readonly resultOf: (instruction: string) => string | undefined;
/** Called after each paragraph, whose properties can end a section */
readonly afterParagraph: (paragraph: E) => void;
};
// Formatting switches that don't change how a number is written
// cspell:ignore mergeformatinet
const PLAIN_FORMATS = new Set(["mergeformat", "charformat", "mergeformatinet"]);
/** Whether a field's switches give its number a format of its own, such as `\* roman`, or a picture, such as `\# "00"` */
const hasOwnFormat = (switches: string): boolean => {
const formats = [...switches.matchAll(/\\\*\s*"?([^\s"\\]+)/g)].map(([, format]) => format.toLowerCase());
return /\\#/.test(switches) || formats.some((format) => !PLAIN_FORMATS.has(format));
};
/**
* The bookmark a PAGEREF field refers to, unless the field shows something other than the page's number: its
* position relative to the bookmark (`\p`), or the number in a format of its own (`\* roman`).
*/
const bookmarkOf = (instruction: string): string | undefined => {
const match = /^\s*PAGEREF\s+("?)([^\s"\\]+)\1(.*)$/i.exec(instruction);
if (!match) {
return undefined;
}
const [, , bookmark, switches] = match;
return /\\p\b/i.test(switches) || hasOwnFormat(switches) ? undefined : bookmark;
};
/** The number of pages a NUMPAGES or SECTIONPAGES field shows, unless it writes it in a format of its own */
const pageCountOf = (instruction: string): "document" | "section" | undefined => {
const match = /^\s*(NUMPAGES|SECTIONPAGES)\b(.*)$/i.exec(instruction);
if (!match || hasOwnFormat(match[2])) {
return undefined;
}
return match[1].toUpperCase() === "NUMPAGES" ? "document" : "section";
};
/**
* The result of a field that shows a page's number or a number of pages, or undefined to leave it as it is. A field
* the estimate has no number for is left as it is, or made blank.
*/
const resultFrom = (
instruction: string,
{ bookmarks, pageCount }: EstimatedPageNumbers,
{ sectionPageCount, blank }: { readonly sectionPageCount?: number; readonly blank: boolean },
): string | undefined => {
const bookmark = bookmarkOf(instruction);
const count = bookmark === undefined ? pageCountOf(instruction) : undefined;
if (bookmark === undefined && count === undefined) {
return undefined;
}
const value = bookmark !== undefined ? bookmarks.get(bookmark) : count === "document" ? pageCount : sectionPageCount;
return value === undefined ? (blank ? "" : undefined) : String(value);
};
/**
* Writes the results the filling works out into the fields in the elements, in order.
*/
// eslint-disable-next-line functional/prefer-readonly-type
const fillFields = <E>(tree: ElementTree<E>, elements: E[], open: OpenField<E>[], filling: FieldFilling<E>): void => {
for (let index = 0; index < elements.length; index++) {
const element = elements[index];
const name = tree.nameOf(element);
if (name === undefined) {
continue;
}
const current = open[open.length - 1];
if (name === "w:fldChar") {
const type = tree.attributeOf(element, "w:fldCharType");
if (type === "begin") {
// eslint-disable-next-line functional/immutable-data
open.push({ begin: element, instruction: "", inResult: false });
} else if (type === "separate" && current) {
tree.writeClean(current.begin, current.instruction);
// eslint-disable-next-line functional/immutable-data
current.inResult = true;
// eslint-disable-next-line functional/immutable-data
current.result = filling.resultOf(current.instruction);
if (current.result !== undefined) {
// eslint-disable-next-line functional/immutable-data
elements.splice(index + 1, 0, tree.textElement(current.result));
index++;
}
} else if (type === "end") {
// eslint-disable-next-line functional/immutable-data
open.pop();
}
} else if (name === "w:instrText" && current && !current.inResult) {
// eslint-disable-next-line functional/immutable-data
current.instruction += tree.textOf(element);
} else if ((name === "w:t" || name === "w:tab" || name === "w:br" || name === "w:cr") && current?.result !== undefined) {
// The result it was written with
// eslint-disable-next-line functional/immutable-data
elements.splice(index, 1);
index--;
} else if (name === "w:fldSimple") {
// A simple field's runs are its result
const result = filling.resultOf(String(tree.attributeOf(element, "w:instr")));
if (result === undefined) {
fillFields(tree, tree.contentOf(element) ?? [], [], filling);
} else {
tree.setSimpleFieldResult(element, result);
}
} else {
fillFields(tree, tree.contentOf(element) ?? [], open, filling);
if (name === "w:p") {
filling.afterParagraph(element);
}
}
}
};
/** The section properties (`w:sectPr`) in the elements, in order: those of the paragraphs that end sections, and the last */
const sectionPropertiesIn = <E>(tree: ElementTree<E>, elements: readonly E[]): readonly E[] =>
elements.flatMap((element): readonly E[] => {
const name = tree.nameOf(element);
if (name === undefined) {
return [];
}
return name === "w:sectPr" ? [element] : sectionPropertiesIn(tree, tree.contentOf(element) ?? []);
});
/** Whether a paragraph ends a section: whether its properties have the section's */
const endsSection = <E>(tree: ElementTree<E>, paragraph: E): boolean =>
(tree.contentOf(paragraph) ?? []).some(
(child) => tree.nameOf(child) === "w:pPr" && (tree.contentOf(child) ?? []).some((part) => tree.nameOf(part) === "w:sectPr"),
);
/**
* The number of pages each header and footer shows in its SECTIONPAGES fields, by the id of the relationship to it:
* that of the sections whose pages it is on, when they all have the same. A section without a header or footer of a kind
* has the one of the section before, as Word lays them out.
*/
const partPageCountsOf = <E>(
tree: ElementTree<E>,
body: E,
sectionPageCounts: readonly (number | undefined)[],
): ReadonlyMap<string, number> => {
const partsOfSections = sectionPropertiesIn(tree, [body]).reduce<readonly ReadonlyMap<string, string>[]>((all, properties) => {
const references = (tree.contentOf(properties) ?? []).flatMap((child) => {
const name = tree.nameOf(child);
return name === "w:headerReference" || name === "w:footerReference"
? [[`${name} ${String(tree.attributeOf(child, "w:type"))}`, String(tree.attributeOf(child, "r:id"))] as const]
: [];
});
return [...all, new Map([...(all[all.length - 1] ?? []), ...references])];
}, []);
const countsOfParts = partsOfSections.reduce((counts, parts, section) => {
for (const id of parts.values()) {
// eslint-disable-next-line functional/immutable-data
counts.set(id, [...(counts.get(id) ?? []), sectionPageCounts[section]]);
}
return counts;
}, new Map<string, readonly (number | undefined)[]>());
return new Map(
[...countsOfParts].flatMap(([id, [first, ...rest]]) =>
first !== undefined && rest.every((count) => count === first) ? [[id, first] as const] : [],
),
);
};
/**
* How fields whose number wasn't worked out are written: left as they are, as in a document docx writes, which writes
* them empty, or made blank, as in a template, whose results are those of the template before it was patched.
*/
export type UnknownNumbers = { readonly blank: boolean };
/**
* Writes the estimated page numbers into the fields of a document's body that show them: its PAGEREF fields, in its
* tables of contents and elsewhere, and its NUMPAGES and SECTIONPAGES fields.
*
* @returns The number of pages each header and footer shows in its SECTIONPAGES fields, by the id of the relationship to it
*/
export const fillBodyFields = <E>(
tree: ElementTree<E>,
body: E,
estimate: EstimatedPageNumbers,
{ blank }: UnknownNumbers,
): ReadonlyMap<string, number> => {
const { sectionPageCounts = [] } = estimate;
let section = 0;
fillFields(tree, [body], [], {
resultOf: (instruction) => resultFrom(instruction, estimate, { sectionPageCount: sectionPageCounts[section], blank }),
afterParagraph: (paragraph) => {
section += endsSection(tree, paragraph) ? 1 : 0;
},
});
return partPageCountsOf(tree, body, sectionPageCounts);
};
/**
* Writes the estimated page numbers into the fields of a header or footer that show them, with the number of pages its
* SECTIONPAGES fields show, if it is known.
*/
export const fillPartFields = <E>(
tree: ElementTree<E>,
part: E,
estimate: EstimatedPageNumbers,
{ blank, sectionPageCount }: UnknownNumbers & { readonly sectionPageCount?: number },
): void =>
fillFields(tree, [part], [], {
resultOf: (instruction) => resultFrom(instruction, estimate, { sectionPageCount, blank }),
afterParagraph: () => undefined,
});
+44 -222
View File
@@ -18,6 +18,8 @@
import { isDirtyWithoutPageNumbers } from "@file/paragraph/run/field";
import type { IContext, IXmlableObject } from "@file/xml-components";
import { type ElementTree, fillBodyFields, fillPartFields } from "./page-number-fields";
/**
* The page each bookmark of a document starts on, and the number of pages of the document and of each of its sections,
* as a {@link PageNumberEstimator} works them out.
@@ -53,221 +55,52 @@ export type EstimatedPageNumbers = {
*/
export type PageNumberEstimator = (body: IXmlableObject, context: IContext) => EstimatedPageNumbers;
/** A formatted element, such as `{ "w:r": [...] }` */
type Element = Record<string, unknown>;
/** A formatted element, such as `{ "w:r": [...] }`, or its attributes, or text */
type Element = unknown;
/** A complex field being read: its instruction, and whether its result has been reached */
type OpenField = {
// eslint-disable-next-line functional/prefer-readonly-type
instruction: string;
// eslint-disable-next-line functional/prefer-readonly-type
inResult: boolean;
/** The result it is written with */
// eslint-disable-next-line functional/prefer-readonly-type
result?: string;
};
/** How the fields of a part of a document are filled in */
type FieldFilling = {
/** The result of a field, from its instruction, or undefined to leave the field as it is */
readonly resultOf: (instruction: string) => string | undefined;
/** Called after each paragraph, whose properties can end a section */
readonly afterParagraph: (paragraph: Element) => void;
};
// Formatting switches that don't change how a number is written
// cspell:ignore mergeformatinet
const PLAIN_FORMATS = new Set(["mergeformat", "charformat", "mergeformatinet"]);
/** Whether a field's switches give its number a format of its own, such as `\* roman`, or a picture, such as `\# "00"` */
const hasOwnFormat = (switches: string): boolean => {
const formats = [...switches.matchAll(/\\\*\s*"?([^\s"\\]+)/g)].map(([, format]) => format.toLowerCase());
return /\\#/.test(switches) || formats.some((format) => !PLAIN_FORMATS.has(format));
};
/**
* The bookmark a PAGEREF field refers to, unless the field shows something other than the page's number: its
* position relative to the bookmark (`\p`), or the number in a format of its own (`\* roman`).
*/
const bookmarkOf = (instruction: string): string | undefined => {
const match = /^\s*PAGEREF\s+("?)([^\s"\\]+)\1(.*)$/i.exec(instruction);
if (!match) {
return undefined;
}
const [, , bookmark, switches] = match;
return /\\p\b/i.test(switches) || hasOwnFormat(switches) ? undefined : bookmark;
};
/** The number of pages a NUMPAGES or SECTIONPAGES field shows, unless it writes it in a format of its own */
const pageCountOf = (instruction: string): "document" | "section" | undefined => {
const match = /^\s*(NUMPAGES|SECTIONPAGES)\b(.*)$/i.exec(instruction);
if (!match || hasOwnFormat(match[2])) {
return undefined;
}
return match[1].toUpperCase() === "NUMPAGES" ? "document" : "section";
};
/** The result of a field that shows a page's number or a number of pages, or undefined to leave it as it is */
const resultFrom = (instruction: string, { bookmarks, pageCount }: EstimatedPageNumbers, sectionPageCount?: number): string | undefined => {
const bookmark = bookmarkOf(instruction);
if (bookmark !== undefined) {
return bookmarks.get(bookmark);
}
const count = pageCountOf(instruction);
const value = count === "document" ? pageCount : count === "section" ? sectionPageCount : undefined;
return value === undefined ? undefined : String(value);
};
const nameOf = (element: unknown): string | undefined =>
typeof element === "object" && element !== null && !Array.isArray(element) ? Object.keys(element)[0] : undefined;
const contentOf = (element: Element): readonly unknown[] => {
const content = element[nameOf(element)!];
return Array.isArray(content) ? content : [];
};
const attributeOf = (element: Element, name: string, attribute: string): unknown => {
const content = element[name];
const holder = Array.isArray(content) ? content.find((child) => nameOf(child) === "_attr") : content;
return (holder as { readonly _attr?: Record<string, unknown> } | undefined)?._attr?.[attribute];
const nameOf = (element: Element): string | undefined => {
const name = typeof element === "object" && element !== null && !Array.isArray(element) ? Object.keys(element)[0] : undefined;
return name === "_attr" ? undefined : name;
};
const textElement = (text: string): Element => ({ "w:t": [{ _attr: { "xml:space": "preserve" } }, text] });
/**
* Writes clean the beginning of a field that is dirty only without page numbers, such as a page reference, so Word
* shows its result as it is written and doesn't ask to update the fields
*/
const writeClean = (begin: Element): void => {
const attributes = (begin["w:fldChar"] as { readonly _attr: Record<string, unknown> })._attr;
// eslint-disable-next-line functional/immutable-data
begin["w:fldChar"] = { _attr: Object.fromEntries(Object.entries(attributes).filter(([key]) => key !== "w:dirty")) };
};
/**
* Writes the results the filling works out into the fields in the elements, in order. A field's result is written just
* after its `separate` field character, and any result it had is taken out.
*/
// eslint-disable-next-line functional/prefer-readonly-type
const fillFields = (elements: unknown[], open: OpenField[], filling: FieldFilling): void => {
for (let index = 0; index < elements.length; index++) {
const element = elements[index];
const name = nameOf(element);
if (name === undefined || name === "_attr") {
continue;
}
const current = open[open.length - 1];
if (name === "w:fldChar") {
const type = attributeOf(element as Element, name, "w:fldCharType");
if (type === "begin") {
// eslint-disable-next-line functional/immutable-data
open.push({ instruction: "", inResult: false });
if (isDirtyWithoutPageNumbers(element)) {
writeClean(element as Element);
}
} else if (type === "separate" && current) {
// eslint-disable-next-line functional/immutable-data
current.inResult = true;
// eslint-disable-next-line functional/immutable-data
current.result = filling.resultOf(current.instruction);
if (current.result !== undefined) {
// eslint-disable-next-line functional/immutable-data
elements.splice(index + 1, 0, textElement(current.result));
index++;
}
} else if (type === "end") {
// eslint-disable-next-line functional/immutable-data
open.pop();
}
} else if (name === "w:instrText" && current && !current.inResult) {
// An instruction is written as its attributes and its text
/** The elements docx formats to write a document */
const FORMATTED: ElementTree<Element> = {
nameOf,
contentOf: (element) => {
const content = (element as Record<string, unknown>)[nameOf(element)!];
return Array.isArray(content) ? content : undefined;
},
attributeOf: (element, attribute) => {
const content = (element as Record<string, unknown>)[nameOf(element)!];
const holder = Array.isArray(content)
? content.find((child) => typeof child === "object" && child !== null && "_attr" in child)
: content;
return (holder as { readonly _attr?: Record<string, unknown> } | undefined)?._attr?.[attribute];
},
// An instruction is written as its attributes and its text
textOf: (element) =>
FORMATTED.contentOf(element)!
.filter((part) => typeof part === "string")
.join(""),
textElement,
// A field docx writes dirty only without page numbers, such as a page reference, is written clean, so Word shows
// its result as it is written and doesn't ask to update the fields
writeClean: (begin) => {
if (isDirtyWithoutPageNumbers(begin)) {
const attributes = ((begin as Record<string, unknown>)["w:fldChar"] as { readonly _attr: Record<string, unknown> })._attr;
// eslint-disable-next-line functional/immutable-data
current.instruction += contentOf(element as Element)
.filter((part) => typeof part === "string")
.join("");
} else if ((name === "w:t" || name === "w:tab" || name === "w:br" || name === "w:cr") && current?.result !== undefined) {
// The result it was written with
// eslint-disable-next-line functional/immutable-data
elements.splice(index, 1);
index--;
} else if (name === "w:fldSimple") {
fillSimpleField(element as Element, filling);
} else {
const content = (element as Element)[name];
if (Array.isArray(content)) {
fillFields(content, open, filling);
}
if (name === "w:p") {
filling.afterParagraph(element as Element);
}
(begin as Record<string, unknown>)["w:fldChar"] = {
_attr: Object.fromEntries(Object.entries(attributes).filter(([key]) => key !== "w:dirty")),
};
}
}
};
/**
* Writes the result into a simple field (`w:fldSimple`) whose result the filling works out: its runs are its result.
*/
const fillSimpleField = (element: Element, filling: FieldFilling): void => {
const result = filling.resultOf(String(attributeOf(element, "w:fldSimple", "w:instr")));
const content = element["w:fldSimple"] as readonly unknown[];
if (result === undefined) {
// eslint-disable-next-line functional/prefer-readonly-type
fillFields(content as unknown[], [], filling);
return;
}
const attributes = content.filter((child) => nameOf(child) === "_attr");
// eslint-disable-next-line functional/immutable-data
element["w:fldSimple"] = [...attributes, { "w:r": [textElement(result)] }];
};
/** The section properties (`w:sectPr`) in the elements, in order: those of the paragraphs that end sections, and the last */
const sectionPropertiesIn = (elements: readonly unknown[]): readonly Element[] =>
elements.flatMap((element): readonly Element[] => {
const name = nameOf(element);
if (name === undefined || name === "_attr") {
return [];
}
return name === "w:sectPr" ? [element as Element] : sectionPropertiesIn(contentOf(element as Element));
});
/** Whether a paragraph ends a section: whether its properties have the section's */
const endsSection = (paragraph: Element): boolean =>
contentOf(paragraph).some(
(child) => nameOf(child) === "w:pPr" && contentOf(child as Element).some((part) => nameOf(part) === "w:sectPr"),
);
/**
* The number of pages each header and footer shows in its SECTIONPAGES fields, by the id of the relationship to it:
* that of the sections whose pages it is on, when they all have the same. A section without a header or footer of a kind
* has the one of the section before, as Word lays them out.
*/
const partPageCountsOf = (body: IXmlableObject, sectionPageCounts: readonly (number | undefined)[]): ReadonlyMap<string, number> => {
const partsOfSections = sectionPropertiesIn([body]).reduce<readonly ReadonlyMap<string, string>[]>((all, properties) => {
const references = contentOf(properties).flatMap((child) => {
const name = nameOf(child);
return name === "w:headerReference" || name === "w:footerReference"
? [
[
`${name} ${String(attributeOf(child as Element, name, "w:type"))}`,
String(attributeOf(child as Element, name, "r:id")),
] as const,
]
: [];
});
return [...all, new Map([...(all[all.length - 1] ?? []), ...references])];
}, []);
const countsOfParts = partsOfSections.reduce((counts, parts, section) => {
for (const id of parts.values()) {
// eslint-disable-next-line functional/immutable-data
counts.set(id, [...(counts.get(id) ?? []), sectionPageCounts[section]]);
}
return counts;
}, new Map<string, readonly (number | undefined)[]>());
return new Map(
[...countsOfParts].flatMap(([id, [first, ...rest]]) =>
first !== undefined && rest.every((count) => count === first) ? [[id, first] as const] : [],
),
);
},
setSimpleFieldResult: (element, text) => {
const attributes = FORMATTED.contentOf(element)!.filter((child) => typeof child === "object" && child !== null && "_attr" in child);
// eslint-disable-next-line functional/immutable-data
(element as Record<string, unknown>)["w:fldSimple"] = [...attributes, { "w:r": [textElement(text)] }];
},
};
/** The estimate of each document's pages, and the numbers of pages its headers and footers show, once its body is written */
@@ -281,16 +114,9 @@ const estimates = new WeakMap<object, { readonly estimate: EstimatedPageNumbers;
*/
export const fillPageNumbers = (body: IXmlableObject, context: IContext, estimator: PageNumberEstimator): void => {
const estimate = estimator(body, context);
const { sectionPageCounts = [] } = estimate;
let section = 0;
fillFields([body], [], {
resultOf: (instruction) => resultFrom(instruction, estimate, sectionPageCounts[section]),
afterParagraph: (paragraph) => {
section += endsSection(paragraph) ? 1 : 0;
},
});
const partPageCounts = fillBodyFields(FORMATTED, body, estimate, { blank: false });
if (context.file) {
estimates.set(context.file, { estimate, partPageCounts: partPageCountsOf(body, sectionPageCounts) });
estimates.set(context.file, { estimate, partPageCounts });
}
};
@@ -307,9 +133,5 @@ export const fillPartPageNumbers = (part: IXmlableObject | undefined, context: I
if (!part || !written) {
return;
}
const sectionPageCount = written.partPageCounts.get(`rId${referenceId}`);
fillFields([part], [], {
resultOf: (instruction) => resultFrom(instruction, written.estimate, sectionPageCount),
afterParagraph: () => undefined,
});
fillPartFields(FORMATTED, part, written.estimate, { blank: false, sectionPageCount: written.partPageCounts.get(`rId${referenceId}`) });
};
+58
View File
@@ -1,9 +1,11 @@
import JSZip from "jszip";
import { describe, expect, it, vi } from "vitest";
import { Formatter } from "@export/formatter";
import { File } from "@file/file";
import {
Bookmark,
Document,
type EstimatedPageNumbers,
FrameAnchorType,
HeadingLevel,
@@ -11,14 +13,18 @@ import {
type IFrameOptions,
type IPropertiesOptions,
type IXmlableObject,
Packer,
PageBreak,
PageNumber,
type PageNumberEstimator,
PageReference,
Paragraph,
PatchType,
TabStopType,
TableOfContents,
type TemplatePageNumberEstimator,
TextRun,
patchDocument,
} from "docx";
import { estimatePageNumbers, estimatePageNumbersWith } from "./estimate-page-numbers";
@@ -55,6 +61,43 @@ const FRAME: IFrameOptions = {
const heading = (text: string, bookmark: string): Paragraph =>
new Paragraph({ heading: HeadingLevel.HEADING_1, children: [new Bookmark({ id: bookmark, children: [new TextRun(text)] })] });
/**
* The document of a template with a page reference and a number of pages, once patchDocument has filled it in with two
* pages of chapters, with the page numbers the estimator works out
*/
const patchedTemplateOf = async (pageNumbers: TemplatePageNumberEstimator): Promise<string> => {
const template = await Packer.toBuffer(
new Document({
sections: [
{
children: [
new Paragraph({ children: [new TextRun("The end is on page "), new PageReference("end")] }),
new Paragraph("{{chapters}}"),
heading("The end", "end"),
new Paragraph({ children: [new TextRun({ children: ["Pages: ", PageNumber.TOTAL_PAGES] })] }),
],
},
],
}),
);
const patched = await patchDocument({
outputType: "nodebuffer",
data: template,
patches: {
chapters: {
type: PatchType.DOCUMENT,
children: [1, 2].map((chapter) => new Paragraph({ children: [new TextRun(`Chapter ${chapter}`), new PageBreak()] })),
},
},
pageNumbers,
});
return (await JSZip.loadAsync(patched)).file("word/document.xml")!.async("text");
};
/** The results written into the fields of a document */
const resultsOf = (document: string): readonly string[] =>
[...document.matchAll(/<w:fldChar w:fldCharType="separate"\/><w:t xml:space="preserve">([^<]*)<\/w:t>/g)].map(([, result]) => result);
describe("estimatePageNumbers", () => {
it("should work out the page each bookmark starts on", () => {
const pages = pageNumbersOf({
@@ -121,10 +164,21 @@ describe("estimatePageNumbers", () => {
expect(stopped.sectionPageCounts).to.deep.equal([undefined]);
});
it("should work out the page numbers of a template once patchDocument has patched it, and write them clean", async () => {
const document = await patchedTemplateOf(estimatePageNumbers);
// The page reference and the number of pages
expect(resultsOf(document)).to.deep.equal(["3", "3"]);
// The template's page reference was written dirty, without page numbers
expect(document).not.to.contain("w:dirty");
});
it("should place nothing without a document to lay out", () => {
expect(estimatePageNumbers({ "w:body": [] } as IXmlableObject, { stack: [] } as unknown as IContext)).to.deep.equal({
bookmarks: new Map(),
});
expect((estimatePageNumbers as (body: IXmlableObject) => EstimatedPageNumbers)({ "w:body": [] })).to.deep.equal({
bookmarks: new Map(),
});
});
});
@@ -161,4 +215,8 @@ describe("estimatePageNumbersWith", () => {
it("should measure text with the width tables, as estimatePageNumbers does, without a way to measure it", () => {
expect(estimateOf(DOCUMENT, estimatePageNumbersWith({}))).to.deep.equal(estimateOf(DOCUMENT));
});
it("should work out the page numbers of a template once patchDocument has patched it, as estimatePageNumbers does", async () => {
expect(resultsOf(await patchedTemplateOf(estimatePageNumbersWith({})))).to.deep.equal(["3", "3"]);
});
});
+32 -13
View File
@@ -1,14 +1,23 @@
/**
* Estimates the page numbers of a document's bookmarks when it is written, by laying out its pages as Word does.
* Estimates the page numbers of a document's bookmarks when it is written, or of a template's once `patchDocument` has
* patched it, by laying out its pages as Word does.
*
* @module
*/
import type { EstimatedPageNumbers, IContext, IXmlableObject, PageNumberEstimator } from "docx";
import type {
EstimatedPageNumbers,
IContext,
IXmlableObject,
PageNumberEstimator,
PatchedTemplate,
TemplatePageNumberEstimator,
} from "docx";
import { DEFAULT_MEASURER, type TextMeasurer } from "../text-layout";
import { type MeasureWidth, measurerOf } from "./measure-width";
import { paginate } from "./paginate";
import { readDocument } from "./read-document";
import { type DocumentContent, readDocument } from "./read-document";
import { readDocx } from "./read-docx";
// How many times the pages are laid out again with the page numbers of the pass before, which can change how the
// lines of a table of contents wrap
@@ -24,12 +33,15 @@ const sameNumbers = (one: Pass, other: Pass): boolean =>
one.sectionPageCounts.length === other.sectionPageCounts.length &&
one.sectionPageCounts.every((count, index) => other.sectionPageCounts[index] === count);
/** What a document is read into: a template patchDocument patched, or the body of a document being written */
const contentOf = (document: IXmlableObject | PatchedTemplate, context?: IContext): DocumentContent | undefined =>
"parts" in document ? readDocx(document.parts) : context?.file && readDocument(document, context);
/** Lays out the pages until their page numbers stop changing, with a measurer */
const estimateWith = (body: IXmlableObject, context: IContext, measurer: TextMeasurer): EstimatedPageNumbers => {
if (!context.file) {
const estimateWith = (content: DocumentContent | undefined, measurer: TextMeasurer): EstimatedPageNumbers => {
if (!content) {
return { bookmarks: new Map() };
}
const content = readDocument(body, context);
const layOut = (before: Pass, pass: number): Pass => {
const { bookmarks, pageCount, sectionPageCounts, stoppedAt } = paginate(content, {
measurer,
@@ -47,10 +59,12 @@ const estimateWith = (body: IXmlableObject, context: IContext, measurer: TextMea
/**
* Works out the page each bookmark of a document starts on, and how many pages the document and each of its sections
* have, by laying out its pages as Word does, so the page numbers of its tables of contents and page references, and its
* numbers of pages, are written with it. Give it to a document as its `pageNumbers`:
* numbers of pages, are written with it. Give it to a document as its `pageNumbers`, or to `patchDocument` as its
* `pageNumbers` to write a template's once it is patched:
*
* ```ts
* new Document({ pageNumbers: estimatePageNumbers, sections: [...] });
* await patchDocument({ outputType: "nodebuffer", data, patches, pageNumbers: estimatePageNumbers });
* ```
*
* The pages are laid out with the widths and heights of the fonts Word documents use most, such as Calibri, Cambria,
@@ -61,7 +75,8 @@ const estimateWith = (body: IXmlableObject, context: IContext, measurer: TextMea
* It stops at the first thing it can't lay out yet: a drawing that text flows around, a text box or frame, an equation,
* a footnote that continues on the next page, columns evened out before a continuous section break, or a table row kept
* whole that is taller than a page. The page references to bookmarks after it are left blank, for
* Word to fill in when it updates the fields.
* Word to fill in when it updates the fields. A document in compatibility mode, which Word lays out as an older version
* of Word did, isn't laid out at all.
*
* Page references and tables of contents are written clean, so Word shows the numbers as they are written, and the
* page numbers it left blank stay blank, without asking to update the fields, unless the document has `updateFields`
@@ -69,8 +84,10 @@ const estimateWith = (body: IXmlableObject, context: IContext, measurer: TextMea
*
* @publicApi
*/
export const estimatePageNumbers = (body: IXmlableObject, context: IContext): EstimatedPageNumbers =>
estimateWith(body, context, DEFAULT_MEASURER);
export const estimatePageNumbers: PageNumberEstimator & TemplatePageNumberEstimator = (
document: IXmlableObject | PatchedTemplate,
context?: IContext,
): EstimatedPageNumbers => estimateWith(contentOf(document, context), DEFAULT_MEASURER);
/**
* How {@link estimatePageNumbersWith} lays out the pages.
@@ -88,7 +105,7 @@ export type EstimatePageNumbersOptions = {
/**
* Works out the page each bookmark of a document starts on, as {@link estimatePageNumbers} does, measuring text as the
* options say. Give what it returns to a document as its `pageNumbers`:
* options say. Give what it returns to a document as its `pageNumbers`, or to `patchDocument` as its `pageNumbers`:
*
* ```ts
* new Document({ pageNumbers: estimatePageNumbersWith({ measureWidth: measureWithPretext(pretext) }), sections: [...] });
@@ -96,8 +113,10 @@ export type EstimatePageNumbersOptions = {
*
* @publicApi
*/
export const estimatePageNumbersWith = ({ measureWidth }: EstimatePageNumbersOptions): PageNumberEstimator => {
export const estimatePageNumbersWith = ({
measureWidth,
}: EstimatePageNumbersOptions): PageNumberEstimator & TemplatePageNumberEstimator => {
// One measurer for every document, so the lines laid out for one are kept for the passes after
const measurer = measureWidth ? measurerOf(measureWidth) : DEFAULT_MEASURER;
return (body, context) => estimateWith(body, context, measurer);
return (document: IXmlableObject | PatchedTemplate, context?: IContext) => estimateWith(contentOf(document, context), measurer);
};
+1 -1
View File
@@ -39,7 +39,7 @@ describe("measureWithPretext", () => {
it("should take Pretext's module, and give a way to measure text to the estimator", () => {
expectTypeOf<PretextModule>().toExtend<layout.Pretext<PreparedTextWithSegments>>();
expectTypeOf(layout.measureWithPretext<PreparedTextWithSegments>).returns.toEqualTypeOf<layout.MeasureWidth>();
expectTypeOf(layout.estimatePageNumbersWith).returns.toEqualTypeOf<docx.PageNumberEstimator>();
expectTypeOf(layout.estimatePageNumbersWith).returns.toEqualTypeOf<docx.PageNumberEstimator & docx.TemplatePageNumberEstimator>();
expectTypeOf(layout.estimatePageNumbersWith).parameter(0).toEqualTypeOf<layout.EstimatePageNumbersOptions>();
});
});
+20 -3
View File
@@ -16,7 +16,8 @@ import {
TextRun,
} from "docx";
import { type DocumentContent, type LayoutItem, type ParagraphBlock, type TableBlock, readDocument } from "./read-document";
import { WORD_DEFAULT_STYLES } from "../text-layout";
import { type DocumentContent, type LayoutItem, type ParagraphBlock, type TableBlock, readContent, readDocument } from "./read-document";
const contextOf = (file: File): IContext => ({ file, viewWrapper: file.Document, stack: [] }) as unknown as IContext;
@@ -426,6 +427,14 @@ describe("readDocument", () => {
expect(itemsOf(content).map((part) => part.type)).to.deep.equal(["text", "tab", "text"]);
expect(textOf(content).endsWith("a")).to.equal(true);
});
it("should write no number for a placeholder of a list that doesn't exist", () => {
const content = readContent(
{ "w:body": [p(pPr({ "w:numPr": [value("w:ilvl", 0), value("w:numId", "{list-0}")] }), r(t("Item")))] },
{ styles: WORD_DEFAULT_STYLES, otherListIds: new Map([["{list-0}", "1"]]), headersAndFooters: new Map() },
);
expect(textOf(content)).to.equal("Item");
});
});
describe("lists given by styles", () => {
@@ -1103,10 +1112,13 @@ describe("readDocument", () => {
expect(readBody([], { hyphenation: { autoHyphenation: true } }).unsupported).to.equal("hyphenation");
});
/** Reads a document whose settings are these elements, which docx doesn't write */
/** Reads a document whose settings are these elements, which docx doesn't write, in Word 2013's compatibility mode */
const readSettings = (...settings: readonly object[]): DocumentContent => {
const file = new File({ sections: [] });
const withSettings = Object.create(file, { Settings: { value: { prepForXml: () => ({ "w:settings": settings }) } } }) as File;
const compatibility = { "w:compat": [{ "w:compatSetting": { _attr: { "w:name": "compatibilityMode", "w:val": 15 } } }] };
const withSettings = Object.create(file, {
Settings: { value: { prepForXml: () => ({ "w:settings": [...settings, compatibility] }) } },
}) as File;
return readDocument({ "w:body": [] } as IXmlableObject, contextOf(withSettings));
};
@@ -1136,6 +1148,11 @@ describe("readDocument", () => {
expect(readSettings(value("w:characterSpacingControl", "compressPunctuation")).unsupported).to.equal("punctuation compressed");
expect(readSettings(value("w:characterSpacingControl", "doNotCompress")).unsupported).to.equal(undefined);
});
it("should mark a document in the compatibility mode of a version of Word before 2013 as unsupported", () => {
expect(readBody([], { compatibility: { version: 14 } }).unsupported).to.equal("a document in compatibility mode");
expect(readBody([], { compatibility: { version: 15 } }).unsupported).to.equal(undefined);
});
});
it("should read headings as they are written, with their bookmarks from the table of contents", () => {
+119 -45
View File
@@ -920,20 +920,14 @@ const readSection = (element: unknown, readPart: (id: string) => readonly Block[
/**
* Reads the levels of each list in the document's numbering (`w:numbering`), by the ids its paragraphs refer to it by:
* its number, and the placeholder docx writes before it is given one.
* its number, and any other name it has, such as the placeholder docx writes before it is given one.
*/
const readNumbering = (context: IContext, styles: TextStyles): ReadonlyMap<string, readonly NumberingLevel[]> => {
const numbering = context.file.Numbering;
// The lists that styles number their paragraphs in are added to the document as its styles are written, after its
// body, so they are added now to be read
for (const style of styles.styles.values()) {
const placeholder = /^\{(.+)-(\d+)\}$/.exec(style.numbering?.id ?? "");
if (placeholder) {
numbering.createConcreteNumberingInstance(placeholder[1], Number(placeholder[2]));
}
}
const xml = numbering.prepForXml(READING_CONTEXT) as XmlObject;
const root = childrenOf(xml["w:numbering"]);
const readNumbering = (
xml: XmlObject | undefined,
styles: TextStyles,
otherIds: ReadonlyMap<string, string>,
): ReadonlyMap<string, readonly NumberingLevel[]> => {
const root = childrenOf(xml?.["w:numbering"]);
const abstract = new Map(
root
.filter((child) => "w:abstractNum" in child)
@@ -943,13 +937,14 @@ const readNumbering = (context: IContext, styles: TextStyles): ReadonlyMap<strin
.map((level) => {
const levelChildren = childrenOf(level["w:lvl"]);
return {
index: numberOf(attributesOf(level["w:lvl"])["w:ilvl"])!,
index: numberOf(attributesOf(level["w:lvl"])["w:ilvl"]) ?? 0,
level: {
...withoutUndefined({ style: valueOf(levelChildren, "w:pStyle") }),
format: valueOf(levelChildren, "w:numFmt") ?? "decimal",
text: stringOf(attributesOf(find(levelChildren, "w:lvlText"))["w:val"]) ?? "",
suffix: valueOf(levelChildren, "w:suff") ?? "tab",
start: numberOf(attributesOf(find(levelChildren, "w:start"))["w:val"])!,
// A level that doesn't give its first number starts at 0
start: numberOf(attributesOf(find(levelChildren, "w:start"))["w:val"]) ?? 0,
paragraph: readParagraphFormat(find(levelChildren, "w:pPr")),
run: readRunFormat(find(levelChildren, "w:rPr"), styles.themeFonts),
},
@@ -964,20 +959,29 @@ const readNumbering = (context: IContext, styles: TextStyles): ReadonlyMap<strin
return [String(attributesOf(child["w:abstractNum"])["w:abstractNumId"]), byIndex] as const;
}),
);
// Each list refers to one of the definitions docx writes with it
const byNumber = root
.filter((child) => "w:num" in child)
.map((child) => {
const abstractId = String(numberOf(attributesOf(find(childrenOf(child["w:num"]), "w:abstractNumId"))["w:val"]));
return [String(attributesOf(child["w:num"])["w:numId"]), abstract.get(abstractId)!] as const;
});
const numbers = new Map(byNumber);
const placeholders = numbering.ConcreteNumbering.map(
(concrete) => [`{${concrete.reference}-${concrete.instance}}`, numbers.get(String(concrete.numId))!] as const,
// Each list refers to one of the definitions
const numbers = new Map(
root
.filter((child) => "w:num" in child)
.flatMap((child) => {
const abstractId = String(numberOf(attributesOf(find(childrenOf(child["w:num"]), "w:abstractNumId"))["w:val"]));
const levels = abstract.get(abstractId);
return levels ? [[String(attributesOf(child["w:num"])["w:numId"]), levels] as const] : [];
}),
);
return new Map([...byNumber, ...placeholders]);
return new Map([
...numbers,
...[...otherIds].flatMap(([other, id]) => {
const levels = numbers.get(id);
return levels ? [[other, levels] as const] : [];
}),
]);
};
// The compatibility mode of Word 2013 and later, which lay out pages as Word does today. A document in an older one, or
// without one, is laid out as that version of Word laid it out
const CURRENT_COMPATIBILITY_MODE = 15;
/**
* The document's own lists of the characters that can't start a line (`w:noLineBreaksBefore`) and can't end one
* (`w:noLineBreaksAfter`), which take the place of Word's for their language.
@@ -998,11 +1002,19 @@ const readKinsokuLists = (settings: readonly XmlObject[]): NonNullable<LineBreak
* Reads the parts of the document's settings (`w:settings`) that change how it is laid out.
*/
const readSettings = (
context: IContext,
xml: XmlObject | undefined,
): Pick<DocumentContent, "defaultTabStop" | "evenAndOddHeaders" | "addsParagraphSpacing" | "breakRules" | "unsupported"> => {
const settings = childrenOf((context.file.Settings.prepForXml(READING_CONTEXT) as XmlObject)["w:settings"]);
const settings = childrenOf(xml?.["w:settings"]);
const compatibility = childrenOf(find(settings, "w:compat"));
const lists = readKinsokuLists(settings);
const spacingControl = valueOf(settings, "w:characterSpacingControl");
const mode = numberOf(
attributesOf(
compatibility.find(
(child) => "w:compatSetting" in child && attributesOf(child["w:compatSetting"])["w:name"] === "compatibilityMode",
)?.["w:compatSetting"],
)["w:val"],
);
// Word's strict rules, and its compression of punctuation, aren't known yet
const unsupported =
onOff(settings, "w:autoHyphenation") === true
@@ -1011,45 +1023,107 @@ const readSettings = (
? "the strict rules for the characters that can't start a line"
: spacingControl !== undefined && spacingControl !== "doNotCompress"
? "punctuation compressed"
: undefined;
: mode === undefined || mode < CURRENT_COMPATIBILITY_MODE
? "a document in compatibility mode"
: undefined;
return {
defaultTabStop: twips(attributesOf(find(settings, "w:defaultTabStop"))["w:val"]) ?? 36,
evenAndOddHeaders: onOff(settings, "w:evenAndOddHeaders") === true,
addsParagraphSpacing: onOff(childrenOf(find(settings, "w:compat")), "w:doNotUseHTMLParagraphAutoSpacing") === true,
addsParagraphSpacing: onOff(compatibility, "w:doNotUseHTMLParagraphAutoSpacing") === true,
...(Object.keys(lists).length > 0 ? { breakRules: { lists } } : {}),
...(unsupported ? { unsupported } : {}),
};
};
/**
* The parts of a document other than its body that it is read with, as elements formatted as docx writes them: those of
* a document being written, or those of a .docx (see `read-docx.ts`).
*/
export type DocumentParts = {
/** Its defaults and styles, with the fonts of its theme */
readonly styles: TextStyles;
/** Its numbering (`w:numbering`), if it has any */
readonly numbering?: XmlObject;
/** Other ids its lists are referred to by, with the number of the list each is: the placeholders docx writes */
readonly otherListIds?: ReadonlyMap<string, string>;
/** Its settings (`w:settings`), if it has any */
readonly settings?: XmlObject;
/** The content of each header and footer, by the id of the relationship to it: its attributes, paragraphs and tables */
readonly headersAndFooters: ReadonlyMap<string, readonly unknown[]>;
/** Its footnotes (`w:footnotes`), if it has any */
readonly footnotes?: XmlObject;
/** Its endnotes (`w:endnotes`), if it has any */
readonly endnotes?: XmlObject;
};
/**
* The parts of the document being written, formatted to be read.
*/
const partsOfFile = (context: IContext): DocumentParts => {
const { file } = context;
const styles = getTextStyles(context);
// The lists that styles number their paragraphs in are added to the document as its styles are written, after its
// body, so they are added now to be read
for (const style of styles.styles.values()) {
const placeholder = /^\{(.+)-(\d+)\}$/.exec(style.numbering?.id ?? "");
if (placeholder) {
file.Numbering.createConcreteNumberingInstance(placeholder[1], Number(placeholder[2]));
}
}
// Formatting a part needs a context with the part in it
const format = (wrapper: { readonly View: { readonly prepForXml: (context: IContext) => unknown } }): XmlObject =>
wrapper.View.prepForXml({ ...context, viewWrapper: wrapper as unknown as IContext["viewWrapper"], stack: [] }) as XmlObject;
return {
styles,
numbering: file.Numbering.prepForXml(READING_CONTEXT) as XmlObject,
// docx writes a placeholder for each list in the paragraphs, before it is given its number
otherListIds: new Map(
file.Numbering.ConcreteNumbering.map((concrete) => [`{${concrete.reference}-${concrete.instance}}`, String(concrete.numId)]),
),
settings: file.Settings.prepForXml(READING_CONTEXT) as XmlObject,
// A header or footer is written with its attributes and its paragraphs and tables
headersAndFooters: new Map(
[...file.Headers, ...file.Footers].map(
(wrapper) => [`rId${wrapper.View.ReferenceId}`, Object.values(format(wrapper))[0] as readonly unknown[]] as const,
),
),
footnotes: format(file.FootNotes),
endnotes: format(file.Endnotes),
};
};
/**
* Reads a document's body, as it is written, with its styles, lists, settings, headers and footers.
*
* @param body - The formatted body (`w:body`)
* @param context - The context it was formatted in, with the document it is in
*/
export const readDocument = (body: IXmlableObject, context: IContext): DocumentContent => {
const styles = getTextStyles(context);
const numbering = readNumbering(context, styles);
export const readDocument = (body: IXmlableObject, context: IContext): DocumentContent =>
readContent(body as XmlObject, partsOfFile(context));
/**
* Reads a document's body (`w:body`), with the other parts of the document.
*/
export const readContent = (body: XmlObject, parts: DocumentParts): DocumentContent => {
const { styles } = parts;
const numbering = readNumbering(parts.numbering, styles, parts.otherListIds ?? new Map());
const readerOf = (inHeader: boolean): Reader => ({ styles, numbering, inHeader, fields: [], counters: new Map() });
// Each header and footer, the first time a section refers to it
const parts = new Map<string, readonly Block[] | undefined>();
const headersAndFooters = new Map<string, readonly Block[] | undefined>();
const readPart = (id: string): readonly Block[] | undefined => {
if (!parts.has(id)) {
const wrapper = [...context.file.Headers, ...context.file.Footers].find(({ View }) => `rId${View.ReferenceId}` === id);
const xml = wrapper?.View.prepForXml({ ...context, viewWrapper: wrapper, stack: [] }) as XmlObject | undefined;
// A header or footer is written with its attributes and its paragraphs and tables
if (!headersAndFooters.has(id)) {
const content = parts.headersAndFooters.get(id);
// eslint-disable-next-line functional/immutable-data
parts.set(id, xml && readBlocks(Object.values(xml)[0] as readonly unknown[], readerOf(true)));
headersAndFooters.set(id, content && readBlocks(content, readerOf(true)));
}
return parts.get(id);
return headersAndFooters.get(id);
};
// The footnotes and endnotes, by their ids, and the separators above them
const noteElements = (kind: NoteKind): ReadonlyMap<string, XmlObject> => {
const wrapper = kind === "footnote" ? context.file.FootNotes : context.file.Endnotes;
const xml = wrapper.View.prepForXml({ ...context, viewWrapper: wrapper, stack: [] }) as XmlObject;
const notes = childrenOf(Object.values(xml)[0]).filter((child) => `w:${kind}` in child);
const xml = kind === "footnote" ? parts.footnotes : parts.endnotes;
const notes = childrenOf(xml && Object.values(xml)[0]).filter((child) => `w:${kind}` in child);
return new Map(
notes.map((note) => {
const attributes = attributesOf(note[`w:${kind}`]);
@@ -1135,7 +1209,7 @@ export const readDocument = (body: IXmlableObject, context: IContext): DocumentC
}
};
// The body is written with its section's properties at its end, if nothing else
read(Object.values(body as XmlObject)[0] as readonly unknown[]);
read(contentOf(body));
if (sections.length === 0 || blocks.some(({ section }) => section >= sections.length)) {
addSection(undefined);
}
@@ -1147,6 +1221,6 @@ export const readDocument = (body: IXmlableObject, context: IContext): DocumentC
footnoteSeparator: footnotes.size > 0 ? readNoteContent("footnote", "separator") : [],
footnoteContinuationSeparator: footnotes.size > 0 ? readNoteContent("footnote", "continuationSeparator") : [],
endnotes: endnotes.length > 0 ? [...readNoteContent("endnote", "separator"), ...endnotes] : [],
...readSettings(context),
...readSettings(parts.settings),
};
};
+216
View File
@@ -0,0 +1,216 @@
import JSZip from "jszip";
import { describe, expect, it } from "vitest";
import { type Element, xml2js } from "xml-js";
import {
AlignmentType,
Document,
EndnoteReferenceRun,
Footer,
FootnoteReferenceRun,
Header,
HeadingLevel,
LevelFormat,
Packer,
PageNumber,
PageReference,
Paragraph,
SectionType,
Table,
TableCell,
TableOfContents,
TableRow,
TextRun,
WidthType,
} from "docx";
import { type DocumentContent, type ParagraphBlock, readDocument } from "./read-document";
import { readDocx } from "./read-docx";
/** Parses XML as patchDocument parses a template's parts */
const parse = (xml: string): Element => xml2js(xml, { compact: false, captureSpacesBetweenElements: true }) as Element;
/** The XML parts of a .docx, parsed, by their paths */
const partsOf = async (buffer: Buffer): Promise<ReadonlyMap<string, Element>> => {
const zip = await JSZip.loadAsync(buffer);
const paths = Object.keys(zip.files).filter((path) => path.endsWith(".xml") || path.endsWith(".rels"));
return new Map(await Promise.all(paths.map(async (path) => [path, parse(await zip.file(path)!.async("string"))] as const)));
};
const W = 'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"';
const R = 'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"';
const TRANSITIONAL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
const STRICT = "http://purl.oclc.org/ooxml/officeDocument/relationships";
const COMPATIBLE = `<w:settings ${W}><w:compat><w:compatSetting w:name="compatibilityMode" w:uri="http://schemas.microsoft.com/office/word" w:val="15"/></w:compat></w:settings>`;
const relationships = (...relationship: readonly string[]): Element =>
parse(`<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${relationship.join("")}</Relationships>`);
const documentOf = (body: string): Element => parse(`<w:document ${W} ${R}><w:body>${body}</w:body></w:document>`);
const paragraphText = ({ items }: ParagraphBlock): string =>
items.map((item) => (item.type === "text" ? item.text : item.type === "tab" ? "\t" : "")).join("");
const textOf = (content: DocumentContent, index = 0): string => paragraphText(content.blocks[index].block as ParagraphBlock);
describe("readDocx", () => {
it("should read a .docx into what the document it was written from is read into", async () => {
let written: DocumentContent | undefined;
const doc = new Document({
features: { updateFields: true },
pageNumbers: (body, context) => {
written = readDocument(body, context);
return { bookmarks: new Map() };
},
styles: { default: { document: { run: { font: "Arial", size: 22 } }, heading1: { run: { size: 32 } } } },
numbering: {
config: [
{
reference: "steps",
levels: [{ level: 0, format: LevelFormat.DECIMAL, text: "%1.", alignment: AlignmentType.START, start: 3 }],
},
],
},
footnotes: { 1: { children: [new Paragraph("A footnote")] } },
endnotes: { 1: { children: [new Paragraph("An endnote")] } },
sections: [
{
headers: { default: new Header({ children: [new Paragraph("The header")] }) },
footers: {
default: new Footer({
children: [new Paragraph({ children: [new TextRun({ children: [PageNumber.TOTAL_PAGES] })] })],
}),
},
children: [
new TableOfContents("Contents", { hyperlink: true, headingStyleRange: "1-3" }),
new Paragraph({ heading: HeadingLevel.HEADING_1, children: [new TextRun("A heading & more")] }),
new Paragraph({ children: [new TextRun("Text "), new FootnoteReferenceRun(1), new EndnoteReferenceRun(1)] }),
new Paragraph({ numbering: { reference: "steps", level: 0 }, children: [new TextRun("A step")] }),
new Paragraph({ numbering: { reference: "steps", level: 0 }, children: [new TextRun("Another step")] }),
new Table({
width: { size: 9000, type: WidthType.DXA },
columnWidths: [3000, 6000],
rows: [
new TableRow({
tableHeader: true,
children: [
new TableCell({ children: [new Paragraph("Name")] }),
new TableCell({ children: [new Paragraph("Value")] }),
],
}),
],
}),
new Paragraph({ children: [new TextRun("See page "), new PageReference("_Toc1")] }),
],
},
{
properties: { type: SectionType.CONTINUOUS, column: { count: 2, space: 720 } },
children: [new Paragraph({ heading: HeadingLevel.HEADING_1, children: [new TextRun("In columns")] })],
},
],
});
const parts = await partsOf(await Packer.toBuffer(doc));
const read = readDocx(parts);
expect(read).to.deep.equal(written);
// What it is read into has the document's text, lists, tables, notes and sections
expect(read.blocks.map(({ block }) => (block.type === "table" ? "table" : paragraphText(block)))).to.include.members([
"A heading & more",
"Text 1i",
"3.\tA step",
"4.\tAnother step",
"table",
"In columns",
]);
expect(read.sections).to.have.length(2);
expect(read.footnotes.size).to.equal(1);
expect(read.endnotes).to.not.be.empty;
expect(read.unsupported).to.equal(undefined);
});
it("should find the main document and its parts through the package's relationships, transitional or strict", () => {
const parts = new Map([
["_rels/.rels", relationships(`<Relationship Id="rId1" Type="${TRANSITIONAL}/officeDocument" Target="/content/main.xml"/>`)],
[
"content/_rels/main.xml.rels",
relationships(
`<Relationship Id="rId1" Type="${STRICT}/styles" Target="../shared/./styles.xml"/>`,
`<Relationship Id="rId2" Type="${TRANSITIONAL}/settings" Target="settings.xml"/>`,
`<Relationship Id="rId3" Type="${TRANSITIONAL}/header" Target="header.xml"/>`,
`<Relationship Id="rId4" Type="${TRANSITIONAL}/hyperlink" Target="https://example.com" TargetMode="External"/>`,
`<Relationship Id="rId5" Type="${TRANSITIONAL}/footer"/>`,
`<Relationship Type="${TRANSITIONAL}/footer" Target="nowhere.xml"/>`,
`<Relationship Id="rId6" Type="${TRANSITIONAL}/footer" Target="missing.xml"/>`,
),
],
[
"shared/styles.xml",
parse(
`<w:styles ${W}><w:docDefaults><w:rPrDefault><w:rPr><w:sz w:val="28"/></w:rPr></w:rPrDefault></w:docDefaults></w:styles>`,
),
],
["content/settings.xml", parse(COMPATIBLE)],
["content/header.xml", parse(`<w:hdr ${W}><w:p><w:r><w:t>The header</w:t></w:r></w:p></w:hdr>`)],
[
"content/main.xml",
documentOf(
`<w:p><w:r><w:t>Text</w:t></w:r></w:p><w:sectPr><w:headerReference w:type="default" r:id="rId3"/><w:footerReference w:type="default" r:id="rId5"/><w:footerReference w:type="first" r:id="rId6"/></w:sectPr>`,
),
],
]);
const content = readDocx(parts);
expect(textOf(content)).to.equal("Text");
expect((content.blocks[0].block as ParagraphBlock).markFont).to.deep.equal({ size: 14 });
expect(content.sections[0].headers.default).to.have.length(1);
// The footers it refers to aren't in the package
expect(content.sections[0].footers).to.deep.equal({});
expect(content.unsupported).to.equal(undefined);
});
it("should number lists with Word's defaults for what a level doesn't give, and not those whose definition is missing", () => {
const parts = new Map([
[
"word/_rels/document.xml.rels",
relationships(
`<Relationship Id="rId1" Type="${TRANSITIONAL}/numbering" Target="numbering.xml"/>`,
`<Relationship Id="rId2" Type="${TRANSITIONAL}/settings" Target="settings.xml"/>`,
),
],
["word/settings.xml", parse(COMPATIBLE)],
[
"word/numbering.xml",
parse(
`<w:numbering ${W}><w:abstractNum w:abstractNumId="0"><w:lvl><w:lvlText w:val="%1."/></w:lvl></w:abstractNum>` +
'<w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num><w:num w:numId="2"><w:abstractNumId w:val="5"/></w:num></w:numbering>',
),
],
[
"word/document.xml",
documentOf(
["1", "2"]
.map((id) => `<w:p><w:pPr><w:numPr><w:numId w:val="${id}"/></w:numPr></w:pPr><w:r><w:t>Item</w:t></w:r></w:p>`)
.join(""),
),
],
]);
const content = readDocx(parts);
// A level without a first number starts at 0
expect(textOf(content, 0)).to.equal("0.\tItem");
expect(textOf(content, 1)).to.equal("Item");
});
it("should read text in CDATA, and leave out comments and processing instructions", () => {
const content = readDocx(
new Map([
["word/document.xml", documentOf("<w:p><w:r><!-- a note --><?mso-application?><w:t><![CDATA[A & B]]></w:t></w:r></w:p>")],
]),
);
expect(textOf(content)).to.equal("A & B");
});
it("should read a .docx without settings as one in compatibility mode, as Word lays it out", () => {
const content = readDocx(new Map([["word/document.xml", documentOf("<w:p/>")]]));
expect(content.unsupported).to.equal("a document in compatibility mode");
});
it("should read an empty body from a package without its main document", () => {
expect(readDocx(new Map()).blocks).to.deep.equal([]);
expect(readDocx(new Map([["word/document.xml", parse(`<w:document ${W}/>`)]])).blocks).to.deep.equal([]);
});
});
+111
View File
@@ -0,0 +1,111 @@
/**
* Reads a .docx, parsed, into what its pages are laid out from, as `read-document.ts` reads a document being written: its
* body, with its styles, lists, settings, headers, footers and notes, found through the relationships of its package.
* It reads templates `patchDocument` has patched, and documents saved from Word.
*
* @module
*/
import type { Element } from "xml-js";
import { type XmlObject, attributesOf, childrenOf, find, readTextStyles, readThemeFonts } from "../text-layout";
import { type DocumentContent, type DocumentParts, readContent } from "./read-document";
/** A relationship of a part to another part of the package */
type Relationship = {
readonly id: string;
/** The last part of its type, such as "styles" for `.../relationships/styles`, whether its type is transitional or strict */
readonly type: string;
/** The path of the part it refers to */
readonly path: string;
};
// The part a package's main document is at when its relationships don't say
const DEFAULT_DOCUMENT = "word/document.xml";
/**
* An element as xml-js parses it, formatted as docx formats elements: `{ "w:p": [{ _attr: {...} }, ...content] }`, with
* text as strings.
*/
const formatted = (element: Element): unknown => {
if (element.type === "text" || element.type === "cdata") {
return String(element.type === "text" ? element.text : element.cdata);
}
return {
[String(element.name)]: [
...(element.attributes === undefined ? [] : [{ _attr: element.attributes }]),
...(element.elements ?? []).filter(({ type }) => type === "element" || type === "text" || type === "cdata").map(formatted),
],
};
};
/** The content of a formatted element: its attributes, the elements in it and its text */
const contentOf = (element: XmlObject): readonly unknown[] => Object.values(element)[0] as readonly unknown[];
/** The root element of a part, such as `w:document`, formatted */
const rootOf = (part: Element | undefined): XmlObject | undefined => {
const root = part?.elements?.find(({ type }) => type === "element");
return root && (formatted(root) as XmlObject);
};
// A part's folder, with its slash, such as "word/" for word/document.xml, or "" for a part at the package's root
const folderOf = (path: string): string => path.slice(0, path.lastIndexOf("/") + 1);
/**
* The path of the part a relationship's target refers to: relative to the folder of the part the relationship belongs to,
* or from the package's root if it starts with "/".
*/
const resolveTarget = (from: string, target: string): string =>
(target.startsWith("/") ? target : `${folderOf(from)}${target}`)
.split("/")
.reduce<readonly string[]>((segments, segment) => {
if (segment === "" || segment === ".") {
return segments;
}
return segment === ".." ? segments.slice(0, -1) : [...segments, segment];
}, [])
.join("/");
/** The relationships of the part at the path to the other parts of the package, from its relationships part */
const relationshipsOf = (parts: ReadonlyMap<string, Element>, from: string): readonly Relationship[] => {
const relationshipsPath = `${folderOf(from)}_rels/${from.slice(folderOf(from).length)}.rels`;
const root = rootOf(parts.get(relationshipsPath));
return childrenOf(root && contentOf(root))
.filter((child) => "Relationship" in child)
.flatMap((child) => {
const { Id: id, Type: type, Target: target, TargetMode: mode } = attributesOf(child.Relationship);
return typeof id !== "string" || typeof target !== "string" || mode === "External"
? []
: [{ id, type: String(type).slice(String(type).lastIndexOf("/") + 1), path: resolveTarget(from, target) }];
});
};
/**
* Reads a .docx's main document, with the parts it refers to.
*
* @param parts - The XML parts of its package, parsed by xml-js's `xml2js`, not compact and keeping the spaces between
* elements, by their paths, such as "word/document.xml"
*/
export const readDocx = (parts: ReadonlyMap<string, Element>): DocumentContent => {
const documentPath = relationshipsOf(parts, "").find(({ type }) => type === "officeDocument")?.path ?? DEFAULT_DOCUMENT;
const relationships = relationshipsOf(parts, documentPath);
const partOf = (type: string): XmlObject | undefined => {
const relationship = relationships.find((candidate) => candidate.type === type);
return relationship && rootOf(parts.get(relationship.path));
};
const theme = partOf("theme");
const documentParts: DocumentParts = {
styles: readTextStyles(partOf("styles") ?? { "w:styles": [] }, theme && readThemeFonts(theme)),
numbering: partOf("numbering"),
settings: partOf("settings"),
headersAndFooters: new Map(
relationships.flatMap(({ id, type, path }) => {
const part = type === "header" || type === "footer" ? rootOf(parts.get(path)) : undefined;
return part ? [[id, contentOf(part)] as const] : [];
}),
),
footnotes: partOf("footnotes"),
endnotes: partOf("endnotes"),
};
const document = rootOf(parts.get(documentPath));
return readContent({ "w:body": find(childrenOf(document && contentOf(document)), "w:body") ?? [] }, documentParts);
};
+38
View File
@@ -1563,5 +1563,43 @@ describe("from-docx", () => {
expect(await read("word/_rels/document.xml.rels")).not.to.contain("relationships/image");
});
});
describe("Page numbers", () => {
const W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
// A page reference, with the page Word wrote for it before the template was patched
const PAGE_REFERENCE =
'<w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText xml:space="preserve"> PAGEREF _Toc1 \\h </w:instrText></w:r>' +
'<w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:t>9</w:t></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r>';
const template = (): JSZip =>
new JSZip()
.file("[Content_Types].xml", `<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"/>`)
.file(
"word/document.xml",
`<w:document xmlns:w="${W}"><w:body><w:p>${PAGE_REFERENCE}</w:p><w:p><w:r><w:t>{{name}}</w:t></w:r></w:p></w:body></w:document>`,
);
const patches = { name: { type: PatchType.PARAGRAPH, children: [new TextRun("Ada")] } } as const;
const documentOf = async (output: Buffer): Promise<string> =>
(await JSZip.loadAsync(output)).file("word/document.xml")!.async("text");
it("should write the page numbers the estimator works out for the patched template", async () => {
const pageNumbers = vi.fn(({ parts }: { readonly parts: ReadonlyMap<string, unknown> }) => {
// The estimate is of the template once it is patched
expect(JSON.stringify(parts.get("word/document.xml"))).to.contain("Ada");
return { bookmarks: new Map([["_Toc1", "4"]]) };
});
const document = await documentOf(
await patchDocument({ outputType: "nodebuffer", data: template(), patches, pageNumbers }),
);
expect(pageNumbers).toHaveBeenCalledOnce();
expect(document).to.contain('<w:fldChar w:fldCharType="separate"/><w:t xml:space="preserve">4</w:t></w:r><w:r/>');
expect(document).not.to.contain("<w:t>9</w:t>");
});
it("should leave the template's page numbers as they are without an estimator", async () => {
expect(await documentOf(await patchDocument({ outputType: "nodebuffer", data: template(), patches }))).to.contain(
"<w:t>9</w:t>",
);
});
});
});
});
+15
View File
@@ -27,6 +27,7 @@ import { findBookmarkIds, renumberBookmarksAvoiding } from "./bookmark-ids";
import { appendContentType, appendContentTypeOverride } from "./content-types-manager";
import { type DrawingPatch, patchDrawings, relationshipsPathOf } from "./drawing-patch";
import { patchNotes } from "./notes";
import { type TemplatePageNumberEstimator, fillTemplatePageNumbers } from "./page-numbers";
import { PatchType } from "./patch-type";
import { appendRelationship, createRelationshipFile, getNextRelationshipIndex } from "./relationship-manager";
import { replacer } from "./replacer";
@@ -46,6 +47,7 @@ export type InputDataType = Buffer | string | number[] | Uint8Array | ArrayBuffe
export { PatchType } from "./patch-type";
export { DrawingPatch } from "./drawing-patch";
export type { TemplateDrawing, TemplatePackage, TemplatePart } from "./drawing-patch";
export type { PatchedTemplate, TemplatePageNumberEstimator } from "./page-numbers";
/**
* Patch definition for paragraph-level replacement.
@@ -162,6 +164,7 @@ export type PatchDocumentOutputType = OutputType;
* @property recursive - Whether to replace every occurrence of a placeholder in a paragraph, rather than only the first
* @property footnotes - The footnotes that patches refer to with a `FootnoteReferenceRun`
* @property endnotes - The endnotes that patches refer to with an `EndnoteReferenceRun`
* @property pageNumbers - Works out the page each bookmark is on, to write the page numbers of page references
*/
export type PatchDocumentOptions<T extends PatchDocumentOutputType = PatchDocumentOutputType> = {
/** Output format type */
@@ -189,6 +192,12 @@ export type PatchDocumentOptions<T extends PatchDocumentOutputType = PatchDocume
readonly footnotes?: Readonly<Record<string, { readonly children: readonly Paragraph[] }>>;
/** The endnotes that patches refer to, by the id given to their `EndnoteReferenceRun`s, as with footnotes */
readonly endnotes?: Readonly<Record<string, { readonly children: readonly Paragraph[] }>>;
/**
* Works out the page each bookmark of the patched document is on, and how many pages it has, so the page numbers of
* its tables of contents and page references, and its numbers of pages, are written with it, rather than left as they
* were in the template. Give it `estimatePageNumbers` from `docx/layout`. See {@link TemplatePageNumberEstimator}
*/
readonly pageNumbers?: TemplatePageNumberEstimator;
};
/**
@@ -290,6 +299,7 @@ export const patchDocument = async <T extends PatchDocumentOutputType = PatchDoc
recursive = true,
footnotes,
endnotes,
pageNumbers,
}: PatchDocumentOptions<T>): Promise<OutputByType[T]> => {
const zipContent = data instanceof JSZip ? data : await JSZip.loadAsync(data);
const contexts = new Map<string, IContext>();
@@ -537,6 +547,11 @@ export const patchDocument = async <T extends PatchDocumentOutputType = PatchDoc
appendRelationship(relationshipsJson, id, type, target, targetMode);
}
// The pages are worked out once everything is patched in
if (pageNumbers) {
fillTemplatePageNumbers(map, pageNumbers);
}
// The parts that patches added to the package, such as charts, which add their own parts as they are written, such
// as a chart's workbook
const packageParts = xmlifyPackageParts(file, undefined);
+114
View File
@@ -0,0 +1,114 @@
import { describe, expect, it, vi } from "vitest";
import { type Element, js2xml } from "xml-js";
import { fillTemplatePageNumbers } from "./page-numbers";
import { toJson } from "./util";
const W = 'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"';
const R = 'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"';
const RELATIONSHIPS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
/** A complex field, with the result Word wrote, and dirty if it is to be updated */
const field = (instruction: string, result: string, dirty = false): string =>
`<w:r><w:fldChar w:fldCharType="begin"${dirty ? ' w:dirty="true"' : ""}/></w:r>` +
`<w:r><w:instrText xml:space="preserve">${instruction}</w:instrText></w:r>` +
'<w:r><w:fldChar w:fldCharType="separate"/></w:r>' +
`<w:r><w:t>${result}</w:t></w:r>` +
'<w:r><w:fldChar w:fldCharType="end"/></w:r>';
const paragraph = (...runs: readonly string[]): string => `<w:p>${runs.join("")}</w:p>`;
const sectionEnd = (references: string): string => `<w:p><w:pPr><w:sectPr>${references}</w:sectPr></w:pPr></w:p>`;
/** The text of a part, with each field's result where it is */
const textOf = (part: Element): string =>
js2xml(part)
.replace(/<w:instrText[^>]*>[^<]*<\/w:instrText>/g, "")
.replace(/<w:t[^>]*>([^<]*)<\/w:t>|<w:t[^>]*\/>|<[^>]+>/g, "$1");
describe("fillTemplatePageNumbers", () => {
it("should write the estimate into the fields of the body, headers and footers, and leave those it has no number for blank", () => {
const parts = new Map([
[
"word/document.xml",
toJson(
`<w:document ${W} ${R}><w:body>${paragraph(
field(" PAGEREF _Toc1 \\h ", "2"),
"<w:r><w:t>|</w:t></w:r>",
field(" PAGEREF _Toc2 \\h ", "5"),
)}${
paragraph(field("NUMPAGES", "9"), "<w:r><w:t>|</w:t></w:r>", field("SECTIONPAGES", "8"))
// A field that doesn't show a page's number, and one whose instruction has no text, are left as they are
}${
paragraph(field("PAGE", "7"), field(" PAGEREF _Toc1 \\p ", "above"), field("", "empty"))
// A simple field's runs are its result
}${paragraph('<w:fldSimple w:instr="NUMPAGES"><w:r><w:t>9</w:t></w:r></w:fldSimple>')}${paragraph(
'<w:fldSimple w:instr="PAGE"><w:r><w:t>7</w:t></w:r></w:fldSimple>',
'<w:fldSimple w:instr="PAGE"/>',
)}<w:p/><w:p><w:pPr/></w:p>${sectionEnd('<w:headerReference w:type="default" r:id="rId1"/>')}${paragraph(
field("SECTIONPAGES", "1"),
)}<w:sectPr><w:footerReference w:type="default" r:id="rId2"/></w:sectPr>` + `</w:body></w:document>`,
),
],
[
"word/_rels/document.xml.rels",
toJson(
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
`<Relationship Id="rId1" Type="${RELATIONSHIPS}/header" Target="header1.xml"/>` +
`<Relationship Id="rId2" Type="${RELATIONSHIPS}/footer" Target="/word/footer1.xml"/>` +
`<Relationship Id="rId3" Type="${RELATIONSHIPS}/footer" Target="missing.xml"/>` +
`<Relationship Id="rId4" Type="${RELATIONSHIPS}/styles" Target="styles.xml"/>` +
"</Relationships>",
),
],
["word/header1.xml", toJson(`<w:hdr ${W}>${paragraph(field("SECTIONPAGES", "1"), field("NUMPAGES", "1"))}</w:hdr>`)],
["word/footer1.xml", toJson(`<w:ftr ${W}>${paragraph(field("SECTIONPAGES", "1"))}</w:ftr>`)],
]);
const estimator = vi.fn(() => ({ bookmarks: new Map([["_Toc1", "3"]]), pageCount: 4, sectionPageCounts: [3, 5] }));
fillTemplatePageNumbers(parts, estimator);
expect(estimator).toHaveBeenCalledWith({ parts });
expect(textOf(parts.get("word/document.xml")!)).to.equal("3|" + "4|3" + "7aboveempty" + "4" + "7" + "5");
// The header is on the pages of both sections, which have different numbers of pages, and the footer on the second's
expect(textOf(parts.get("word/header1.xml")!)).to.equal("4");
expect(textOf(parts.get("word/footer1.xml")!)).to.equal("5");
});
it("should write the numbers of a document without headers and footers", () => {
const parts = new Map([
["word/document.xml", toJson(`<w:document ${W}><w:body>${paragraph(field("NUMPAGES", "1"))}<w:sectPr/></w:body></w:document>`)],
]);
fillTemplatePageNumbers(parts, () => ({ bookmarks: new Map(), pageCount: 2 }));
expect(textOf(parts.get("word/document.xml")!)).to.equal("2");
});
it("should write page references and tables of contents clean, as a document's are with page numbers, and leave other fields dirty", () => {
const parts = new Map([
[
"word/document.xml",
toJson(
`<w:document ${W}><w:body>${paragraph(
field(' TOC \\o "1-3" \\h ', "", true),
field(" PAGEREF _Toc1 \\h ", "2", true),
field(" DATE ", "today", true),
)}</w:body></w:document>`,
),
],
]);
fillTemplatePageNumbers(parts, () => ({ bookmarks: new Map([["_Toc1", "3"]]) }));
const document = js2xml(parts.get("word/document.xml")!);
expect(document.match(/<w:fldChar [^>]*w:fldCharType="begin"[^>]*\/>/g)).to.deep.equal([
'<w:fldChar w:fldCharType="begin"/>',
'<w:fldChar w:fldCharType="begin"/>',
'<w:fldChar w:fldCharType="begin" w:dirty="true"/>',
]);
expect(textOf(parts.get("word/document.xml")!)).to.equal("3today");
});
it("should leave a package without its main document as it is", () => {
const estimator = vi.fn(() => ({ bookmarks: new Map() }));
fillTemplatePageNumbers(new Map(), estimator);
expect(estimator).not.toHaveBeenCalled();
});
});
+97
View File
@@ -0,0 +1,97 @@
/**
* Page numbers written into a template's fields once `patchDocument` has patched it, from an estimate of its pages, as
* a document's are when it is written with `pageNumbers`.
*
* @module
*/
import type { Element } from "xml-js";
import { type ElementTree, fillBodyFields, fillPartFields } from "@file/document/body/page-number-fields";
import type { EstimatedPageNumbers } from "@file/document/body/page-numbers";
import { relationshipsPathOf, resolveTarget } from "./drawing-patch";
/**
* A template once `patchDocument` has patched it, as a {@link TemplatePageNumberEstimator} reads it.
*
* @publicApi
*/
export type PatchedTemplate = {
/**
* Each XML part of the template's package, by its path in the package, such as "word/document.xml". Each is parsed as
* `patchDocument` parses it, with xml-js's `xml2js`, not compact, and keeping the spaces between elements
* (`captureSpacesBetweenElements`), as the spaces in a text element are its text
*/
readonly parts: ReadonlyMap<string, Element>;
};
/**
* Works out which page each bookmark of a template starts on, and how many pages it and each of its sections have, once
* `patchDocument` has patched it, so the page numbers of its tables of contents and page references, and its numbers of
* pages, are written with it.
*
* `estimatePageNumbers`, from `docx/layout`, is one. Give it to `patchDocument` as its `pageNumbers`.
*
* @publicApi
*/
export type TemplatePageNumberEstimator = (template: PatchedTemplate) => EstimatedPageNumbers;
/** The elements of a template, as xml-js parses them */
const PARSED: ElementTree<Element> = {
nameOf: (element) => (element.type === "element" ? element.name : undefined),
contentOf: (element) => element.elements,
attributeOf: (element, attribute) => element.attributes?.[attribute],
textOf: (element) =>
(element.elements ?? [])
.filter(({ type }) => type === "text")
.map(({ text }) => String(text))
.join(""),
textElement: (text) => ({ type: "element", name: "w:t", attributes: { "xml:space": "preserve" }, elements: [{ type: "text", text }] }),
// A page reference or table of contents is written clean, as docx writes them with page numbers, so Word shows its
// numbers as they are and doesn't ask to update the fields
writeClean: (begin, instruction) => {
if (/^\s*(PAGEREF|TOC)\b/i.test(instruction) && begin.attributes?.["w:dirty"] !== undefined) {
// eslint-disable-next-line functional/immutable-data
begin.attributes = Object.fromEntries(Object.entries(begin.attributes).filter(([key]) => key !== "w:dirty"));
}
},
setSimpleFieldResult: (element, text) => {
// eslint-disable-next-line functional/immutable-data
element.elements = [{ type: "element", name: "w:r", elements: [PARSED.textElement(text)] }];
},
};
// The part patchDocument patches as the document's body
const DOCUMENT = "word/document.xml";
/** The root element of a part, such as `w:document` */
const rootOf = (part: Element | undefined): Element | undefined => part?.elements?.find(({ type }) => type === "element");
/**
* Writes the page numbers the estimator works out for a patched template into the fields of its body, headers and
* footers that show them: its PAGEREF fields, in its tables of contents and elsewhere, and its NUMPAGES and SECTIONPAGES
* fields. The results a field was written with are those of the template before it was patched, so a field whose number
* the estimator doesn't work out is left blank, as it is in a document written with `pageNumbers`. Page references and
* tables of contents are written clean, as they are in a document written with `pageNumbers`, so Word shows their numbers
* as they are and doesn't ask to update the fields.
*
* @param parts - The template's XML parts, parsed, by their paths, which are changed in place
*/
export const fillTemplatePageNumbers = (parts: ReadonlyMap<string, Element>, estimator: TemplatePageNumberEstimator): void => {
const document = rootOf(parts.get(DOCUMENT));
if (!document) {
return;
}
const estimate = estimator({ parts });
const partPageCounts = fillBodyFields(PARSED, document, estimate, { blank: true });
// The headers and footers the document refers to
const relationships = rootOf(parts.get(relationshipsPathOf(DOCUMENT)))?.elements ?? [];
for (const { attributes = {} } of relationships) {
const part = /\/(header|footer)$/.test(String(attributes.Type))
? rootOf(parts.get(resolveTarget(DOCUMENT, String(attributes.Target))))
: undefined;
if (part) {
fillPartFields(PARSED, part, estimate, { blank: true, sectionPageCount: partPageCounts.get(String(attributes.Id)) });
}
}
};
+1 -1
View File
@@ -280,7 +280,7 @@ export const readParagraphFormat = (element: unknown): ParagraphFormat => {
/**
* Reads the fonts of a document's theme (`a:theme`), once it is formatted.
*/
const readThemeFonts = (xml: XmlObject): ThemeFonts => {
export const readThemeFonts = (xml: XmlObject): ThemeFonts => {
const elements = childrenOf(find(childrenOf(xml["a:theme"]), "a:themeElements"));
const scheme = childrenOf(find(elements, "a:fontScheme"));
// Every font of a theme has a font for Latin text