DOCX
补丁
通过替换占位符修改现有 .docx 文件
通过替换 {{占位符}} 标记来修补现有 .docx 模板,支持替换为段落、表格、图片、超链接等内容。
patchDocument
替换现有 .docx 文件中的占位符:
import {
patchDocument,
PatchType,
TextRun,
Paragraph,
Table,
TableRow,
TableCell,
} from "@office-open/docx";
import { readFileSync, writeFileSync } from "node:fs";
const result = await patchDocument({
outputType: "nodebuffer",
data: readFileSync("template.docx"),
patches: {
name: {
type: PatchType.PARAGRAPH,
children: [new TextRun("John Doe")],
},
},
});
writeFileSync("output.docx", result);
PatchType
| 类型 | 说明 |
|---|---|
PatchType.PARAGRAPH | 用内联运行级内容替换占位符 |
PatchType.DOCUMENT | 用块级内容替换占位符 |
PARAGRAPH
将段落中的占位符文本替换为新的文本块。默认保留原 run 的格式属性(字体、大小、颜色、加粗等)。
patches: {
title: {
type: PatchType.PARAGRAPH,
children: [
new TextRun({ text: "Hello ", bold: true }),
new TextRun("World"),
],
},
}
DOCUMENT
用块级元素(段落、表格等)替换占位符。保留周围的上下文。
patches: {
content: {
type: PatchType.DOCUMENT,
children: [
new Paragraph("第一段"),
new Paragraph("第二段"),
new Table({
rows: [
new TableRow({
children: [
new TableCell({ children: [new Paragraph("单元格")] }),
],
}),
],
}),
],
},
}
图片
用图片替换占位符:
patches: {
logo: {
type: PatchType.PARAGRAPH,
children: [
new ImageRun({
data: readFileSync("logo.png"),
transformation: { width: 200, height: 100 },
type: "png",
}),
],
},
}
超链接
在补丁内容中包含超链接:
patches: {
website: {
type: PatchType.PARAGRAPH,
children: [
new TextRun("访问 "),
new ExternalHyperlink({
children: [new TextRun("我们的网站")],
link: "https://example.com",
}),
],
},
}
自定义分隔符
默认分隔符为 {{ 和 }}。使用 placeholderDelimiters 自定义:
await patchDocument({
outputType: "nodebuffer",
data: templateBuffer,
patches: { name: { type: PatchType.PARAGRAPH, children: [new TextRun("John")] } },
placeholderDelimiters: { start: "<<", end: ">>" },
});
选项
| 选项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
outputType | string | — | 输出格式(见导出页面) |
data | Buffer | Uint8Array | ... | — | 输入 .docx 文件数据 |
patches | Record<string, IPatch> | — | 占位符名称到补丁内容的映射 |
keepOriginalStyles | boolean | true | 保留原始 run 格式属性 |
placeholderDelimiters | { start: string, end: string} | { {{, }} } | 自定义占位符分隔符 |
recursive | boolean | true | 替换所有出现(而非仅第一个) |
patchDetector
在修补之前扫描模板以发现所有占位符键:
import { patchDetector } from "@office-open/docx";
const placeholders = await patchDetector({
data: readFileSync("template.docx"),
});
// ["name", "title", "content", ...]
提示
- Word 中跨分割运行的占位符会被库自动处理。
- 使用
keepOriginalStyles: true(默认)可在替换文本时继承模板的 run 格式(字体、大小、颜色等)。 recursive: true(默认)替换每个占位符的所有出现;设为false仅替换第一个。- 补丁内容中的图片和超链接会自动添加到文档的关系中。