guigrpa / docx-templates

Template-based docx report creation

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Docx file corrupted when image in header

griprkevin opened this issue · comments

Hi!
I have an issue when creating reports with image in the docx header.

Example code

const { createReport } = require("docx-templates");
const sharp = require("sharp");

(async () => {
  const template = fs.readFileSync("./docx_template.docx");

  const data = {
    companyName: "My company",
    companyNr: "123",
    companyAddress: "Company street 1",
    companyZip: "12345",
    companyPlace: "Company city",
    companyPhone: "123456789",
    fileVersion: "1.0",
    fileUpdatedAt: "2021-01-01",
  };

  const reportOptions = {
    template,
    data,
    cmdDelimiter: ["{", "}"],
    noSandbox: true,
  };

  reportOptions.additionalJsContext = {
    companyLogo: async () => {
      const source = await sharp({
        create: {
          width: 200,
          height: 100,
          channels: 4,
          background: { r: 0, g: 0, b: 0, alpha: 0 },
        },
      })
        .png()
        .toBuffer();
      const data = source.toString("base64");

      return { width: 6, height: 6, data, extension: ".png" };
    },
  };

  const report = await createReport(reportOptions);

  fs.writeFileSync("report.docx", report);
})();

Example template: docx_template.docx

Result

The file wont open, it looks corrupted
image

Notes

I tested on node version "20.9.0" using docx-templates version "4.11.4"
The docx was made with the MS word online editor

If you need additional information, please let me know