有没有一种方法可以通过Node JS读取一个包含占位符(如{text1} / {image1}
)的Word文件(.docx),并将其替换为真实内容。我尝试了几个npm模块,其中我能够创建一个新的docx副本,但无法编辑或替换图像和文本。非常感谢您的帮助。
有没有一种方法可以通过Node JS读取一个包含占位符(如{text1} / {image1}
)的Word文件(.docx),并将其替换为真实内容。我尝试了几个npm模块,其中我能够创建一个新的docx副本,但无法编辑或替换图像和文本。非常感谢您的帮助。
有一个项目https://github.com/open-xml-templating/docxtemplater,用于替换.docx文件中的占位符
。
还支持循环和图片,请查看以下演示:
https://docxtemplater.com/demo/
https://docxtemplater.com/demo/#image-replacement
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}`);
});
开源docx模板库:
https://github.com/guigrpa/docx-templates
提供了许多针对docx文档的模板功能。我昨天第一次使用它,就能够快速实现所需的解决方案。包括简单的标签模板,还有更复杂的表格模板。