javascriptimagedocxtemplater

What filetype do I need to make image in docs to work?


I use docxtemplater to place my image in docx file but it keeps ending up an error image Like this

I tried sending it as filelist, base64 , buffer but it never works

this is my code, thank you in advanced.

export const generateDocument = async (data, file, setFile) => {

  const opts = {
    centered: true,
    getImage: function (tagValue, tagName) {

      return PizZipUtils.getBinaryContent(data.imageData[0], (error, content) => content);
    },
    getSize: function (img, tagValue, tagName) {
      return [110, 130];
    },
  };

  loadFile(data.logo === "BBS" ? './BBS.docx' : "./PPT.docx", (error, content) => {
    if (error) {
      throw error;
    }
    let zip = new PizZip(content);
    let doc = new Docxtemplater(zip, {
      modules: [new ImageModule(opts)],
      paragraphLoop: true,
      linebreaks: true
    });
    doc.setData({...data});


    // render the document (replace all occurences of {first_name} by John, {last_name} by Doe, ...)
    doc.render();

    let out = doc.getZip().generate({
      type: "blob",
      mimeType: "docxType",
    });
    saveAs(out, 'Resume.docx');
  });

Solution

  • There may be other ways, but it definitely works if your getImage() function returns an ArrayBuffer with the image data. Buffer seems to be part of node.js. If your code runs in the browser, you can npm install buffer.

    If your image data is base64 encoded, you could use this conversion function:

    import { Buffer } from "buffer";
    
    function base64DataURLToArrayBuffer(stringBase64) {
      const binaryString = window.atob(stringBase64);
      const len = binaryString.length;
      const bytes = Buffer.alloc(len, 0);
      for (let i = 0; i < len; i += 1) {
        const ascii = binaryString.charCodeAt(i);
        bytes[i] = ascii;
      }
      return bytes;
    }