Search code examples
javascriptdocxtemplater

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


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 ?


Solution

  • 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",
    });