使用Node JS动态编辑Word文档并替换文本和图像占位符

15

有没有一种方法可以通过Node JS读取一个包含占位符(如{text1} / {image1})的Word文件(.docx),并将其替换为真实内容。我尝试了几个npm模块,其中我能够创建一个新的docx副本,但无法编辑或替换图像和文本。非常感谢您的帮助。


你已经尝试了什么?你面临的具体问题是什么? 感谢您考虑如何提出一个好问题?如何创建一个最小化、可重现的示例 - Christian Baumann
@ChristianBaumann - 我知道。但问题是我找不到编辑这个单词的方法。而且我已经提到了尝试过的npm模块无法帮助编辑docx并替换图像。 - Vignesh Gopalakrishnan
这个回答解决了你的问题吗?使用Node.js NPM库访问和修改Microsoft Word文档 - Marian
3个回答

13

2
Docxtemplater存在许多问题。 - Md Misbauddin Chowdhury
1
你还在 Docxtemplater 中看到哪些问题?我是 docxtemplater 的维护者和创建者。 - edi9999
模块的价格似乎是自制解决方案的问题。 :D 想使用您的软件包创建简单的docx文件。其中一个需求是创建表格,但我刚刚注意到每个模块需要500欧元/年。我猜你的目标是企业。祝好运! 我将转向另一个docx库,或者将在LaTeX中创建模板。最终我需要编译为pdf。 - shemekh

0
你需要从npm库"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}`);
});

TestTemplate.docx Result.docx


0

开源docx模板库:
https://github.com/guigrpa/docx-templates
提供了许多针对docx文档的模板功能。我昨天第一次使用它,就能够快速实现所需的解决方案。包括简单的标签模板,还有更复杂的表格模板。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接