DOCX
Styles and Themes
Declarative style system for character and paragraph formatting
Define reusable styles to keep your document formatting consistent and maintainable.
Defining Styles
import { Document, Paragraph, TextRun, Style, Styles } from "@office-open/docx";
const doc = new Document({
styles: {
default: {
document: {
run: {
font: "Calibri",
size: 22,
},
paragraph: {
spacing: { line: 276 },
},
},
},
custom: [
new Style({
id: "MyHeading",
name: "My Heading",
type: "paragraph",
basedOn: "Heading1",
run: {
font: "Arial",
size: 36,
color: "2E74B5",
},
}),
new Style({
id: "CodeInline",
name: "Code Inline",
type: "character",
run: {
font: "Consolas",
size: 20,
shading: { fill: "F2F2F2" },
},
}),
],
},
sections: [
{
children: [
new Paragraph({
style: "MyHeading",
children: [new TextRun("Styled Heading")],
}),
new Paragraph({
children: [
new TextRun("Normal text with "),
new TextRun({ text: "inline code", style: "CodeInline" }),
],
}),
],
},
],
});
Style Types
| Type | ID | Description |
|---|---|---|
| Paragraph | "paragraph" | Applies to entire paragraphs |
| Character | "character" | Applies to runs within paragraphs |
| Table | "table" | Applies to tables |
| Numbering | "numbering" | Applies to list numbering |
Default Styles
Override the document defaults with the default property:
styles: {
default: {
document: {
run: {
font: "Calibri",
size: 22, // 11pt in half-points
color: "333333",
},
paragraph: {
spacing: { line: 276 }, // 1.15 line spacing
},
},
heading1: {
run: {
font: "Calibri Light",
size: 44,
color: "1F3763",
},
},
},
},
Using Styles
Apply styles to paragraphs and runs:
// Paragraph style
new Paragraph({ style: "MyHeading", children: [...] });
// Character style on a run
new TextRun({ text: "styled", style: "CodeInline" });
External Styles
Import styles from an existing document using the styles.external option:
const doc = new Document({
styles: {
external: {
Heading1: { run: { font: "Arial", size: 44 } },
Heading2: { run: { font: "Arial", size: 32 } },
},
},
sections: [
// ...
],
});
Style Options Reference
| Option | Type | Description |
|---|---|---|
id | string | Unique style identifier |
name | string | Display name |
type | "paragraph" | "character" | "table" | "numbering" | Style type |
basedOn | string | Parent style to inherit from |
run | object | Run formatting (font, size, color, bold, etc.) |
paragraph | object | Paragraph formatting (spacing, alignment, etc.) |