Setup
Add a dependency on the WordTemplates extension (Manage Dependencies, Ctrl+Q): the 3 actions and the TemplateImage and TemplateTag structures. Store templates in an entity (Binary Data), so business users can update them without a release.
Fill a template (server action)
1. Build a structure with the data, e.g. Invoice with Customer, a Lines list and Total.
2. JSON Serialize it.
3. FillTemplate(Template, DataJson, ImageList, Culture). Culture formats numbers and dates, e.g. en-SG. ImageList is optional.
4. Use the Document output: download it as .docx, attach it to an email or store it. Warnings lists missing data (WarningCount = 0 when everything was found).
Tags
{{Customer.Name}} value
{{Total:N2}} {{Date:dd MMM yyyy}} {{Paid:Yes|No}} {{Name:upper}} formats
{{#each Lines}} in the first cell of a row, {{/each}} at the end of its last cell: one row per item
{{#each X}} and {{/each}} each alone in a paragraph: repeats everything between
{{#if Total > 100}} … {{else}} … {{/if}} also {{#unless}}
{{@number}} {{this}} {{@last}} in loops
{{image:Logo}} {{image:Logo:40}} (40 mm) image from ImageList
Check
ListTemplateTags lists a template's tags. GetSampleData returns a JSON with every value the template uses.
Demo
Open WordTemplatesDemo and log in. Select Use this example, then Fill and download.