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

1.4k views Asked by At

Recently, I have been asked to make a tool that should automatically generate .docx files using a given template once we feed data to it. After some thinking, I eventuall opted for the docxtemplater, and I did manage to generate a .docx file, with the core code like this:

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

However, that is insufficient, and I want to create multiple .docx file(s) and put them in one containing zipfiles. So how do I modify the code above so that I can generate a .zip file that contains the above "output.docx" file in it, and another docx file ?

2

There are 2 answers

0
edi9999 On BEST ANSWER

You can create multiple docx and add them to a zip file :

Here my example works with two doc1 and doc2 but it could work the same way with any number of documents.

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",
});
1
edi9999 On

I first understood the question, as : "can I compress the generated docx file ?" . I'm leaving this answer if some people find it useful.

By default, the generated docx documents are zip files but which are uncompressed to minimize time of compression. You don't need to create another zip on top of docxtemplater, you can just tell PizZip to compress the files.

To do that, you can use the following compression: "DEFLATE" parameter:

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

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