如何使用 "docxtemplater" 生成的多个 docx 文件创建一个 zip 文件?

How do I create a zip file with multiple docx files generated by the "docxtemplater"?

最近,我被要求制作一个工具,一旦我们向它提供数据,它应该使用给定的模板自动生成 .docx 文件。经过一番思考,我最终选择了 docxtemplater,并且我成功地生成了一个 .docx 文件,其核心代码如下:

var zip = new PizZip(content); //Using PizZip.js
var doc = new window.docxtemplater(zip);    
var out = doc.getZip().generate({
    type: "blob",
    mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
});
saveAs(out, "output.docx"); //Using FileSaver.js

但是,这还不够,我想创建多个 .docx 文件并将它们放在一个包含 zip 文件的文件中。那么我该如何修改上面的代码,以便我可以生成一个 .zip 文件,其中包含上面的“output.docx”文件和另一个 docx 文件?

我首先将问题理解为:“我可以压缩生成的 docx 文件吗?” .如果有人觉得有用,我将留下这个答案。

默认情况下,生成的 docx 文档是 zip 文件,但未压缩以最大程度地减少压缩时间。你不需要在 docxtemplater 之上创建另一个 zip,你可以告诉 PizZip 压缩文件。

为此,您可以使用以下 compression: "DEFLATE" 参数:

var out = doc.getZip().generate({
    type: "blob",
    compression: "DEFLATE",
    mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
});

来源:https://docxtemplater.readthedocs.io/en/latest/faq.html#generate-smaller-docx-using-compression

您可以创建多个 docx 并将它们添加到一个 zip 文件中:

这里我的示例使用两个 doc1 和 doc2,但它可以以相同的方式处理任意数量的文档。

const doc1 = new Docxtemplater(new JSZip(content1));
const doc2 = new Docxtemplater(new JSZip(content2));
const outputZip = new PizZip();

doc1.setData({a:1}).render();
const buffer1 = doc1.getZip().generate({
    type: "arraybuffer",
    compression: "DEFLATE",
    mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
});
outputZip.file("output1.docx", buffer1);

doc2.setData({b:2}).render();
const buffer2 = doc2.getZip().generate({
    type: "arraybuffer",
    compression: "DEFLATE",
    mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
});
outputZip.file("output2.docx", buffer2);

const outputBlob = outputZip.generate({
    type: "blob",
    compression: "DEFLATE",
    mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
});