Skip to content

Functions:generateDocx

Emiel Wit edited this page Nov 16, 2022 · 4 revisions

Generate Docx

With the generateDocx helper you can generate docx files. This helper uses the docxtemplater package.

The generateDocx helper expects the following arguments: a URL for the template file, an object containing the data you want to use, and the docx options used by the docxtemplater. It returns a promise that once resolved, results in an ArrayBuffer. You can use the storeFile helper to store this ArrayBuffer as a file in the asset store.

interface Options {
  delimiters?: { start: string; end: string };
  paragraphLoop?: boolean;
  parser?(tag: string): Parser;
  errorLogging?: boolean | string;
  linebreaks?: boolean;
  nullGetter?(part: Part): any;
}

const generateDocx = async (
  templateUrl: string,
  data: Record<string, unknown>,
  docxOptions: Options
): Promise<ArrayBuffer>

See the documentation of docxtemplater for further information about the options.

Example function:

const generateDocument = async ({
  templateUrl: { url: templateUrl },
  model: { name: modelName },
  property: [{ name: propertyName }],
  fileName,
}) => {
  const buffer = await generateDocx(
    templateUrl,
    {
      users: [
        {
          firstName: 'John',
          lastName: 'Doe',
          email: null,
        },
        {
          firstName: 'Jane',
          lastName: 'Doe',
          email: '[email protected]',
        },
      ],
      inline: "<i><b>hello world</b></i>",
      html: "<h1>Hello World!</h1>",
      image: "https://docxtemplater.com/xt-pro-white.png",
      secondImage: "https://docxtemplater.com/xt-pro-white.png",
    },
    {
      linebreaks: true,
      paragraphLoop: true,
    }
  );

  const reference = await storeFile(modelName, propertyName, {
    contentType:
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    extension: 'docx',
    fileName,
    fileBuffer: buffer,
  });

  return {
    reference: reference,
  };
};

export default generateDocument;
Clone this wiki locally