Templates
Generate PDFs from Word, HTML and PDF templates filled with JSON data, with loops, conditions, formatters and images, with NexPDF for Go.
License module
Templates need the conversion module (Startup tier and above).
A template is a Word document, an HTML page or a PDF with placeholders such as
{{customer.name}}. NexPDF fills it from a JSON object and gives you a PDF (or, for Word, a filled
.docx). The three kinds share one syntax.
Word templates
values := map[string]any{
"number": "2026-114",
"customer": map[string]any{"name": "Ana Silva"},
"due": "2026-12-31",
"items": []map[string]any{
{"description": "Consulting", "qty": 4, "price": 120},
{"description": "Travel", "qty": 1, "price": 85.5},
},
"total": 565.5,
"paid": false,
}
data, _ := json.Marshal(values)
template, err := os.ReadFile("invoice.docx")
if err != nil {
log.Fatal(err)
}
doc, err := nexpdf.TemplateDOCXToPdf(template, string(data), `{"locale":"pt-PT"}`)
if err != nil {
log.Fatal(err)
}
defer doc.Close()
doc.Save("invoice-2026-114.pdf", false)
filledDocx, err := nexpdf.TemplateDOCXFill(template, string(data)) // keep it as Word
filledPt, err := nexpdf.TemplateDOCXFillWith(template, string(data), `{"strict":true,"locale":"pt-PT"}`)TemplateDOCXFillWith is TemplateDOCXFill with the strict and locale options.
Placeholders work even when Word splits them over several runs. A table row that holds an
{{#each items}} tag is repeated once per item, and a paragraph that holds only a block tag
disappears from the output. Headers, footers, footnotes and endnotes are filled too.
HTML templates
html := `
<h1>Invoice {{number}}</h1>
<p>{{customer.name}}, due {{due | date:"dd/MM/yyyy"}}</p>
<table>
{{#each items}}<tr><td>{{@number}}</td><td>{{description}}</td><td>{{price | currency:"EUR"}}</td></tr>{{/each}}
</table>
{{#if paid}}<p>Paid</p>{{else}}<p>Total due: {{total | currency:"EUR"}}</p>{{/if}}
`
doc, err := nexpdf.TemplateHTMLToPdf(html, string(data), "")
if err != nil {
log.Fatal(err)
}
defer doc.Close()
doc.Save("invoice.pdf", false)Values are HTML-escaped; {{{raw}}} (three braces) inserts HTML as it is.
PDF templates
TemplateFillPdf(dataJson, optionsJson) fills an existing PDF in place: AcroForm fields by name
(dotted names such as customer.name follow the data tree) and placeholders in the page's text
lines. It returns the number of fields and text lines filled.
doc, err := nexpdf.Open("form-template.pdf")
if err != nil {
log.Fatal(err)
}
defer doc.Close()
filled, err := doc.TemplateFillPdf(string(data), `{"flatten":true}`)
if err != nil {
log.Fatal(err)
}
fmt.Println(filled, "fields and lines filled")
doc.Save("filled.pdf", false)Page flow, header and footer
Rows that no longer fit break onto new pages; rows taller than a page are cut between lines, and
graphics after the last row move with the end of the content (onto their own page if they do not
fit). The header_height and footer_height options (in points) mark the text rows and graphics
at the top and bottom edge that repeat in place on every page.
The default is no header and a 72 pt footer. A text row that starts in the bottom 72 pt (one
inch) of the page is treated as footer: it is repeated in place on every page instead of flowing
with the content. If a row near the bottom of your template should flow, set "footer_height":0
to turn the footer zone off (no row is a footer, and flowing rows may then run to the bottom edge),
or give a small value such as 36 to keep a margin without catching rows. Without
footer_height the flow keeps a 36 to 72 pt bottom margin.
Fonts
Characters the page font cannot show are drawn in an embedded subset of a Unicode font, chosen
with the font option. That text is shaped with OpenType and laid out in Unicode bidi order.
Right-to-left text uses the fallback font even when the page font has codes for it, unless font
is keep. Right-to-left text without explicit alignment starts at the right.
Syntax
| Tag | Meaning |
|---|---|
{{customer.name}}, {{items.0.price}} | A value from the data |
{{total | currency:"EUR"}} | A value through a formatter |
{{#each items}}…{{/each}} | Repeats for each item; inside, this, @index, @number, @first, @last, @key, ../name and @root.name |
{{#if paid}}…{{else}}…{{/if}} | Condition; comparisons such as {{#if total > 1000}} work |
{{#unless paid}}…{{/unless}} | Inverse condition |
{{% logo}} | An image from the data |
{{! note}} | A comment, not printed |
Formatters: upper, lower, capitalize, trim, currency:"EUR" (optionally with a locale,
currency:"EUR","de"), number[:decimals[,"locale"]], percent[:decimals], round[:decimals],
date:"yyyy-MM-dd" (ISO dates or Unix seconds), default:"text", join[:", "] and length.
An image value is base64 text or a data: URL of a PNG, JPEG or GIF, or an object
{"data": "...", "width": 120, "height": 40} with a size in points:
logo, _ := os.ReadFile("logo.png")
values["logo"] = map[string]any{"data": base64.StdEncoding.EncodeToString(logo), "width": 120}
data, _ = json.Marshal(values)Options
| Option | Default | Meaning |
|---|---|---|
strict | false | A field missing from the data fails the call, naming the field and where the tag is. Otherwise it renders empty |
locale | en | Default locale of currency and number (en, de, fr, pt-BR, …) |
flatten | false | PDF templates: flatten the form after filling |
fields | true | PDF templates: fill AcroForm fields |
text | true | PDF templates: replace placeholders in the page text |
header_height | none | PDF templates: height in points of the header zone, from the top edge, repeated on every page |
footer_height | 72 | PDF templates: height in points of the footer zone, from the bottom edge, repeated on every page. 0 turns it off |
font | bundled | PDF templates: font for characters the page font cannot show: bundled, keep (no substitution, such a character is an error), a font file path, {"path": "..."} or {"data": "<base64>"} |
base_dir | none | HTML templates: folder that relative image, style sheet and font URLs resolve against (files are read only inside it). Without it only data: URLs are used |
Pass "" for the data (an empty object) or the options (the defaults). Syntax errors (an unclosed
block, an unknown formatter) always fail. The error is a *nexpdf.Error with the engine's message:
_, err := nexpdf.TemplateHTMLToPdf("<p>{{missing}}</p>", "{}", `{"strict":true}`)
var e *nexpdf.Error
if errors.As(err, &e) {
fmt.Println(e.Message) // names the field and the tag location
}