feat: write Word's Caption style, and document captions and cross-references (#557) (#3813)

Word gives the captions it inserts the paragraph style "caption", and docx
didn't write it, so a paragraph with `style: "Caption"` came out in Normal:
Word drops a style the document doesn't define. docx now writes the style
as Word writes it when it inserts a caption (small italic text in the
theme's second dark color, with space after), and `styles.default.caption`
changes it. A Caption style in paragraphStyles or externalStyles still takes
its place.

A new docs page shows captions with SequentialIdentifier, their numbers
written by docx/layout, cross-references to them with a bookmark and
NumberedItemReference, and a table of figures, none of which the docs
covered.


Claude-Session: https://claude.ai/code/session_01X5zGDL3sgGVBMXPfny376c

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Dolan
2026-10-21 16:22:38 +01:00
committed by GitHub
co-authored by Claude Opus 5.5
parent ba2b4e26a0
commit 9397bbd549
7 changed files with 405 additions and 0 deletions
@@ -0,0 +1,80 @@
// Captions for a table and a picture, numbered by Word, with cross-references to them and a table of figures
// See docs/usage/captions.md for full documentation.
import * as fs from "fs";
import {
Bookmark,
Document,
HeadingLevel,
ImageRun,
NumberedItemReference,
NumberedItemReferenceFormat,
Packer,
PageReference,
Paragraph,
SequentialIdentifier,
Table,
TableCell,
TableOfContents,
TableRow,
TextRun,
} from "docx";
// A caption, with its label and number in a bookmark that cross-references refer to
const caption = (label: string, bookmark: string, title: string): Paragraph =>
new Paragraph({
style: "Caption",
children: [
new Bookmark({ id: bookmark, children: [new TextRun(`${label} `), new SequentialIdentifier(label)] }),
new TextRun(`: ${title}`),
],
});
// A reference to a caption's label and number, such as "Table 1", which Word works out when it updates the fields
const reference = (bookmark: string, text: string): NumberedItemReference =>
new NumberedItemReference(bookmark, text, { referenceFormat: NumberedItemReferenceFormat.NONE });
const row = (cells: readonly string[]): TableRow =>
new TableRow({ children: cells.map((text) => new TableCell({ children: [new Paragraph(text)] })) });
const doc = new Document({
features: { updateFields: true },
sections: [
{
children: [
new Paragraph({ text: "Pizza report", heading: HeadingLevel.HEADING_1 }),
new Paragraph({ text: "Tables and figures", heading: HeadingLevel.HEADING_2 }),
new TableOfContents("Tables", { captionLabelIncludingNumbers: "Table", hyperlink: true }),
new TableOfContents("Figures", { captionLabelIncludingNumbers: "Figure", hyperlink: true }),
new Paragraph({ text: "Sales", heading: HeadingLevel.HEADING_2 }),
new Paragraph({
children: [
new TextRun("Margherita sold the most ("),
reference("salesTable", "Table 1"),
new TextRun("), and the special is in "),
reference("specialFigure", "Figure 1"),
new TextRun(", on page "),
new PageReference("specialFigure"),
new TextRun("."),
],
}),
caption("Table", "salesTable", "Pizzas sold in May"),
new Table({ rows: [row(["Pizza", "Sold"]), row(["Margherita", "412"]), row(["Pepperoni", "389"])] }),
new Paragraph({
children: [
new ImageRun({
type: "gif",
data: fs.readFileSync("./demo/assets/images/pizza.gif"),
transformation: { width: 200, height: 200 },
}),
],
}),
caption("Figure", "specialFigure", "Today's special"),
],
},
],
});
Packer.toBuffer(doc).then((buffer) => {
fs.writeFileSync("My Document.docx", buffer);
});
+1
View File
@@ -48,6 +48,7 @@
- [Numbering](usage/numbering.md)
- [Hyperlinks](usage/hyperlinks.md)
- [Bookmarks](usage/bookmarks.md)
- [Captions and Cross-references](usage/captions.md)
- [Checkboxes](usage/checkboxes.md)
- [Text Box](usage/text-box.md)
- [WPS Text Box](usage/wps-text-box.md)
+207
View File
@@ -0,0 +1,207 @@
# Captions and Cross-references
A caption labels and numbers a table, a picture or an equation, such as "Table 1: Results". A cross-reference refers to it from elsewhere in the text, as Word's **References > Insert Caption** and **Insert Cross-reference** do.
## Captions
A caption is a paragraph in the `Caption` style, with its label and a `SequentialIdentifier`, which numbers the captions with the same label, 1, 2, 3 and on. `docx` writes Word's own Caption style, small italic text in the theme's second dark color:
```ts live
import * as fs from "fs";
import { Document, ImageRun, Paragraph, SequentialIdentifier, Table, TableCell, TableRow, TextRun } from "docx";
const doc = new Document({
sections: [
{
children: [
new Paragraph({
style: "Caption",
children: [new TextRun("Table "), new SequentialIdentifier("Table"), new TextRun(": Opening hours")],
}),
new Table({
rows: [
new TableRow({
children: [
new TableCell({ children: [new Paragraph("Weekdays")] }),
new TableCell({ children: [new Paragraph("9 to 5")] }),
],
}),
new TableRow({
children: [
new TableCell({ children: [new Paragraph("Saturday")] }),
new TableCell({ children: [new Paragraph("10 to 2")] }),
],
}),
],
}),
new Paragraph({
children: [
new ImageRun({
type: "gif",
data: fs.readFileSync("./demo/assets/images/pizza.gif"),
transformation: { width: 200, height: 200 },
}),
],
}),
new Paragraph({
style: "Caption",
children: [new TextRun("Figure "), new SequentialIdentifier("Figure"), new TextRun(": Today's special")],
}),
],
},
],
});
```
A caption can go above or below what it labels.
### Caption numbers
Word works out the numbers when it updates the document's fields, so it asks to update them when it opens the document, and until then the captions have no numbers. To write the numbers with the document, give it `pageNumbers: estimatePageNumbers` from [`docx/layout`](usage/layout.md), which counts them as Word does. Word then opens it without asking:
```ts live
import { Document, Paragraph, SequentialIdentifier, TextRun } from "docx";
import { estimatePageNumbers } from "docx/layout";
const doc = new Document({
pageNumbers: estimatePageNumbers,
sections: [
{
children: [
new Paragraph({
style: "Caption",
children: [new TextRun("Figure "), new SequentialIdentifier("Figure"), new TextRun(": Written as Figure 1")],
}),
new Paragraph({
style: "Caption",
children: [new TextRun("Figure "), new SequentialIdentifier("Figure"), new TextRun(": Written as Figure 2")],
}),
],
},
],
});
```
A `SequentialIdentifier` takes Word's switches after the label, such as `new SequentialIdentifier("Figure \\r 5")` to number from 5 again, or `new SequentialIdentifier("Figure \\s 1")` to number from 1 again after each Heading 1.
### Changing the caption style
Give `caption` in the default styles to change how captions look. It takes the options of any [paragraph style](usage/styling-with-js.md), and its `run` and `paragraph` replace the Caption style's own:
```ts live
import { Document, Paragraph, SequentialIdentifier, TextRun } from "docx";
const doc = new Document({
styles: {
default: {
caption: {
run: { bold: true, color: "2E74B5", size: 20 },
paragraph: { spacing: { before: 120, after: 240 } },
},
},
},
sections: [
{
children: [
new Paragraph({
style: "Caption",
children: [new TextRun("Figure "), new SequentialIdentifier("Figure"), new TextRun(": A caption in bold blue")],
}),
],
},
],
});
```
A paragraph style with the id `Caption` in `paragraphStyles`, or in a template's styles (`externalStyles`), takes the place of `docx`'s.
## Cross-references
To refer to a caption, put its label and number in a [bookmark](usage/bookmarks.md), then refer to the bookmark with a `NumberedItemReference` in the `NONE` format, which writes the bookmark's text, such as "Table 2". Give the text the reference shows until Word updates the document's fields, as Word works it out then. A `PageReference` gives the page the caption is on:
```ts live
import {
Bookmark,
Document,
NumberedItemReference,
NumberedItemReferenceFormat,
PageReference,
Paragraph,
SequentialIdentifier,
Table,
TableCell,
TableRow,
TextRun,
} from "docx";
const caption = (bookmark: string, title: string): Paragraph =>
new Paragraph({
style: "Caption",
children: [
new Bookmark({ id: bookmark, children: [new TextRun("Table "), new SequentialIdentifier("Table")] }),
new TextRun(`: ${title}`),
],
});
const table = (text: string): Table =>
new Table({ rows: [new TableRow({ children: [new TableCell({ children: [new Paragraph(text)] })] })] });
const doc = new Document({
sections: [
{
children: [
new Paragraph({
children: [
new TextRun("Sales grew in every region ("),
new NumberedItemReference("salesTable", "Table 2", { referenceFormat: NumberedItemReferenceFormat.NONE }),
new TextRun(", on page "),
new PageReference("salesTable"),
new TextRun(")."),
],
}),
caption("costsTable", "Costs"),
table("Costs by region"),
caption("salesTable", "Sales"),
table("Sales by region"),
],
},
],
});
```
The reference is a link to the caption. Give `hyperlink: false` for plain text.
## Table of Figures
A table of contents with `captionLabelIncludingNumbers` lists the captions with a label, with their numbers and pages, as Word's **Insert Table of Figures** does. Word fills it in when it updates the document's fields:
```ts live
import { Document, Paragraph, SequentialIdentifier, TableOfContents, TextRun } from "docx";
const doc = new Document({
features: { updateFields: true },
sections: [
{
children: [
new TableOfContents("Figures", { captionLabelIncludingNumbers: "Figure", hyperlink: true }),
new Paragraph({
style: "Caption",
children: [new TextRun("Figure "), new SequentialIdentifier("Figure"), new TextRun(": The first figure")],
}),
new Paragraph({
style: "Caption",
children: [new TextRun("Figure "), new SequentialIdentifier("Figure"), new TextRun(": The second figure")],
}),
],
},
],
});
```
See [Table of Contents](usage/table-of-contents.md) for its other options.
## Demo
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/fields/captions-and-cross-references.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/fields/captions-and-cross-references.ts_
+45
View File
@@ -440,6 +440,51 @@ describe("File", () => {
]);
});
it("should write Word's caption style, so paragraphs with the style Caption are captions", () => {
const doc = new File({ sections: [] });
const tree = new Formatter().format(doc.Styles)["w:styles"];
const captionStyles = tree.filter((child: { readonly "w:style"?: readonly { readonly _attr?: Record<string, string> }[] }) =>
child["w:style"]?.some((part) => part._attr?.["w:styleId"] === "Caption"),
);
expect(captionStyles).to.deep.equal([new Formatter().format(createDefaultStyles().caption)]);
});
it("should format captions with the caption style given in styles.default", () => {
const doc = new File({
styles: {
default: {
caption: { run: { color: "FF0000", size: 20 } },
},
},
sections: [],
});
const tree = new Formatter().format(doc.Styles)["w:styles"];
const captionStyles = tree.filter((child: { readonly "w:style"?: readonly { readonly _attr?: Record<string, string> }[] }) =>
child["w:style"]?.some((part) => part._attr?.["w:styleId"] === "Caption"),
);
expect(captionStyles).to.deep.equal([
new Formatter().format(createDefaultStyles({ caption: { run: { color: "FF0000", size: 20 } } }).caption),
]);
});
it("should write a paragraph style with the id Caption in place of docx's caption style", () => {
const doc = new File({
styles: {
paragraphStyles: [{ id: "Caption", name: "caption", run: { bold: true } }],
},
sections: [],
});
const tree = new Formatter().format(doc.Styles)["w:styles"];
const captionStyles = tree.filter((child: { readonly "w:style"?: readonly { readonly _attr?: Record<string, string> }[] }) =>
child["w:style"]?.some((part) => part._attr?.["w:styleId"] === "Caption"),
);
expect(captionStyles).to.have.length(1);
expect(captionStyles[0]["w:style"]).to.deep.include({ "w:rPr": [{ "w:b": {} }, { "w:bCs": {} }] });
});
it("should create with even and odd headers and footers", () => {
const doc = new File({
evenAndOddHeaderAndFooters: true,
+8
View File
@@ -11,6 +11,7 @@ import type { XmlComponent } from "@file/xml-components";
import { DocumentDefaults, type IDocumentDefaultsOptions } from "./defaults";
import {
CaptionStyle,
EndnoteReferenceStyle,
EndnoteText,
EndnoteTextChar,
@@ -51,6 +52,7 @@ import { DocumentAttributes } from "../document/document-attributes";
* @property heading6 - Heading 6 paragraph style options
* @property strong - Strong paragraph style options
* @property listParagraph - List paragraph style options
* @property caption - Caption paragraph style options
* @property hyperlink - Hyperlink character style options
* @property footnoteReference - Footnote reference character style options
* @property footnoteText - Footnote text paragraph style options
@@ -78,6 +80,11 @@ export type IDefaultStylesOptions = {
readonly strong?: IBaseParagraphStyleOptions;
/** List paragraph style options */
readonly listParagraph?: IBaseParagraphStyleOptions;
/**
* The style of captions (`style: "Caption"`), such as "Table 1" above a table. Options given replace the style's
* own, so a `run` replaces its italic, size and color
*/
readonly caption?: IBaseParagraphStyleOptions;
/** Hyperlink character style options */
readonly hyperlink?: IBaseCharacterStyleOptions;
/** Footnote reference character style options */
@@ -164,6 +171,7 @@ export const createDefaultStyles = (
...options.strong,
}),
listParagraph: new ListParagraph(options.listParagraph || {}),
caption: new CaptionStyle(options.caption || {}),
hyperlink: new HyperlinkStyle(options.hyperlink || {}),
footnoteReference: new FootnoteReferenceStyle(options.footnoteReference || {}),
footnoteText: new FootnoteText(options.footnoteText || {}),
@@ -360,6 +360,38 @@ describe("Default Styles", () => {
});
});
it("CaptionStyle#constructor is Word's caption style: small italic text in the theme's second dark color", () => {
expect(new Formatter().format(new defaultStyles.CaptionStyle({}))).to.deep.equal({
"w:style": [
{ _attr: { "w:type": "paragraph", "w:styleId": "Caption" } },
{ "w:name": { _attr: { "w:val": "caption" } } },
{ "w:basedOn": { _attr: { "w:val": "Normal" } } },
{ "w:next": { _attr: { "w:val": "Normal" } } },
{ "w:uiPriority": { _attr: { "w:val": 35 } } },
{ "w:semiHidden": EMPTY_OBJECT },
{ "w:unhideWhenUsed": EMPTY_OBJECT },
{ "w:qFormat": EMPTY_OBJECT },
{ "w:pPr": [{ "w:spacing": { _attr: { "w:after": 200 } } }] },
{
"w:rPr": [
{ "w:i": EMPTY_OBJECT },
{ "w:iCs": EMPTY_OBJECT },
{ "w:color": { _attr: { "w:val": "44546A", "w:themeColor": "dark2" } } },
{ "w:sz": { _attr: { "w:val": 18 } } },
{ "w:szCs": { _attr: { "w:val": 18 } } },
],
},
],
});
});
it("CaptionStyle#constructor replaces its own formatting with the options given", () => {
const tree = new Formatter().format(new defaultStyles.CaptionStyle({ run: { bold: true } }));
expect(tree["w:style"]).to.deep.include({ "w:rPr": [{ "w:b": EMPTY_OBJECT }, { "w:bCs": EMPTY_OBJECT }] });
expect(tree["w:style"]).to.deep.include({ "w:pPr": [{ "w:spacing": { _attr: { "w:after": 200 } } }] });
});
it("LineNumberStyle#constructor is Word's line number style, with no formatting of its own", () => {
expect(new Formatter().format(new defaultStyles.LineNumberStyle({}))).to.deep.equal({
"w:style": [
+32
View File
@@ -195,6 +195,38 @@ export class ListParagraph extends StyleForParagraph {
}
}
/**
* Represents the Caption paragraph style.
*
* Word gives the captions it inserts (References > Insert Caption) the paragraph style named "caption", and this is that
* style as Word writes it: small italic text in the theme's second dark color, with space after it.
*/
export class CaptionStyle extends StyleForParagraph {
public constructor(options: IBaseParagraphStyleOptions) {
super({
id: "Caption",
name: "caption",
basedOn: "Normal",
next: "Normal",
uiPriority: 35,
semiHidden: true,
unhideWhenUsed: true,
quickFormat: true,
paragraph: {
spacing: {
after: 200,
},
},
run: {
italics: true,
color: { theme: "dark2" },
size: 18,
},
...options,
});
}
}
/**
* Represents the Footnote Text paragraph style.
*