DOCX
样式与主题
用于字符和段落格式化的声明式样式系统
定义可复用的样式,使文档格式保持一致且易于维护。
定义样式
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" }),
],
}),
],
},
],
});
样式类型
| 类型 | ID | 说明 |
|---|---|---|
| 段落样式 | "paragraph" | 应用于整个段落 |
| 字符样式 | "character" | 应用于段落中的文本片段 |
| 表格样式 | "table" | 应用于表格 |
| 编号样式 | "numbering" | 应用于列表编号 |
默认样式
使用 default 属性覆盖文档默认值:
styles: {
default: {
document: {
run: {
font: "Calibri",
size: 22, // 11pt(半点为单位)
color: "333333",
},
paragraph: {
spacing: { line: 276 }, // 1.15 倍行距
},
},
heading1: {
run: {
font: "Calibri Light",
size: 44,
color: "1F3763",
},
},
},
},
使用样式
将样式应用于段落和文本片段:
// 段落样式
new Paragraph({ style: "MyHeading", children: [...] });
// 文本片段上的字符样式
new TextRun({ text: "styled", style: "CodeInline" });
外部样式
使用 styles.external 选项从现有文档导入样式:
const doc = new Document({
styles: {
external: {
Heading1: { run: { font: "Arial", size: 44 } },
Heading2: { run: { font: "Arial", size: 32 } },
},
},
sections: [
// ...
],
});
Style 选项参考
| 选项 | 类型 | 说明 |
|---|---|---|
id | string | 唯一样式标识符 |
name | string | 显示名称 |
type | "paragraph" | "character" | "table" | "numbering" | 样式类型 |
basedOn | string | 继承的父样式 |
run | object | 文本格式(字体、字号、颜色、粗体等) |
paragraph | object | 段落格式(间距、对齐等) |