有没有一种方法可以让我通过 Node JS 读取包含
{text1} / {image1}
等占位符的 Word 文件(.docx),并将其替换为真实的占位符。我尝试了几个 npm 模块,其中我能够创建 docx 的新副本,但无法编辑或替换图像和文本。感谢您的帮助。
有一个项目 https://github.com/open-xml-templater/docxtemplater 用于替换 .docx 文件中的
placeholders
。
还支持循环和图像,请查看以下演示:
https://docxtemplater.com/demo/
https://docxtemplater.com/demo/#image-replacement
开源 docx 模板库:
https://github.com/guigrpa/docx-templates
许多 docx 文档的模板功能。我昨天才第一次使用它,并且能够快速实现所需的解决方案。包括简单的标签模板,也包括更复杂的表格模板。
您需要 npm lib“docx”(doc) 中的“Patcher”。
下面是简单的代码示例
import * as fs from 'fs';
import {
Paragraph,
patchDocument,
PatchType,
} from 'docx';
const editDocx = async () => {
try {
const doc = await patchDocument(fs.readFileSync('TestTemplate.docx'), {
patches: {
my_tag_here: {
type: PatchType.DOCUMENT,
children: [
new Paragraph({text: 'Replaced text'}),
],
},
},
});
fs.writeFileSync('Result.docx', doc);
} catch (error) {
console.error(`Error: ${error}`);
}
};
editDocx()
.then(() => {
console.log('Document edited successfully.');
})
.catch((error) => {
console.error(`Failed to edit document: ${error}`);
});