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

问题描述 投票:0回答:3

有没有一种方法可以让我通过 Node JS 读取包含

{text1} / {image1}
等占位符的 Word 文件(.docx),并将其替换为真实的占位符。我尝试了几个 npm 模块,其中我能够创建 docx 的新副本,但无法编辑或替换图像和文本。感谢您的帮助。

javascript node.js ms-word docx
3个回答
13
投票

0
投票

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


0
投票

您需要 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}`);
});

© www.soinside.com 2019 - 2024. All rights reserved.