0

Fill Word template

by
Published today

Fill a .docx template from Windmill object storage with `data` and write the result back to object storage, returning its S3 reference. The template uses docxtemplater tags: `{name}` for a value, `{#items}...{/items}` to repeat a block per array element or show it when truthy, `{^items}...{/items}` when empty. A tag with no matching key is left blank. Needs no Microsoft connection and works with any workspace object storage; for a PDF, upload the result with the OneDrive Upload File script and download it with `convert_to_pdf`.

Script ms_word Verified

The script

Submitted by hugo989 Bun
Verified 4 hours ago
1
import * as wmill from "windmill-client"
2
import { S3Object } from "windmill-client"
3
import Docxtemplater from "docxtemplater"
4
import PizZip from "pizzip"
5

6
/**
7
 * Fill Word template
8
 * Fill a .docx template from Windmill object storage with `data` and write the result back to object storage, returning its S3 reference. The template uses docxtemplater tags: `{name}` for a value, `{#items}...{/items}` to repeat a block per array element or show it when truthy, `{^items}...{/items}` when empty. A tag with no matching key is left blank. Needs no Microsoft connection and works with any workspace object storage; for a PDF, upload the result with the OneDrive Upload File script and download it with `convert_to_pdf`.
9
 */
10
export async function main(
11
  template: S3Object,
12
  data: { [key: string]: any },
13
  destination: S3Object
14
) {
15
  const bytes = await wmill.loadS3File(template)
16
  if (!bytes) throw new Error("template not found in object storage")
17

18
  const doc = new Docxtemplater(new PizZip(bytes), {
19
    paragraphLoop: true,
20
    linebreaks: true,
21
    nullGetter: () => "",
22
  })
23
  doc.render(data)
24

25
  await wmill.writeS3File(
26
    destination,
27
    new Blob([doc.getZip().generate({ type: "uint8array" })])
28
  )
29
  return destination
30
}
31