gpt4 book ai didi

javascript - 如何在docx文件nodejs的第一页附加图像?

转载 作者:行者123 更新时间:2023-12-03 14:36:56 25 4
gpt4 key购买 nike

现在我想实现一个功能,在 nodejs 中现有 docx 文件的第一页添加二维码图像。
这三种方法我都试过了,但都不能解决。

  • 我试过 docx包,但它只允许从头开始构建 docx 文件。
  • 我试过 docxtemplater , 但它只允许替换{%image}成图像文件。
  • 我尝试生成一个仅包含二维码图像的新 docx 文件,并将其与原始 docx 文件合并。但是找不到任何适合 docx 合并的包。

  • 这里有什么解决办法吗?提前致谢。

    最佳答案

    实际上,很难将图像直接附加到 docx 文件。
    为此,您需要将图像添加到 word/media文件夹,更新 word/_rels/document.xml.rels 中的关系文件并将代表图像的正确 xml 字符串添加到 word/document.xml文件。
    但它不适用于大多数文件,即使文件是可恢复的,它也会损坏。
    所以我的建议是添加{%image}将文本转换为 docx 文件并使用 将其替换为图像.
    添加 {%image}到 docx 文件中,你需要添加这个 xml 字符串 <w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t xml:space="preserve">{%image}</w:t></w:r></w:p>进入 word/document.xml .

        const originFile = fs.readFileSync(path.resolve('origin.docx'), 'binary');
    const originZip = await JSZip.loadAsync(originFile);

    const originDocumentFile = originZip.file(/^word\/document[0-9]*.xml$/)[0];
    let originDocumentXml = await originDocumentFile.async("string");
    const startIndex = originDocumentXml.indexOf("<w:body>") + 8;
    originDocumentXml = originDocumentXml.slice(0, startIndex) + '<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:t xml:space="preserve">{%image}</w:t></w:r></w:p>' + originDocumentXml.slice(startIndex);
    originZip.file(originDocumentFile.name, originDocumentXml);

    const updateFile = await originZip.generateAsync({ type: 'nodebuffer' });
    fs.writeFile("output.docx", updateFile, function(err) {/*...*/});

    关于javascript - 如何在docx文件nodejs的第一页附加图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66669593/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com