Templates
Generate PDFs from Word, HTML and PDF templates filled with JSON data, with loops, conditions, formatters and images, with NexPDF for Android.
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
import com.nexdevit.nexpdf.NexPdfDocument
import com.nexdevit.nexpdf.NexPdfJni
import org.json.JSONArray
import org.json.JSONObject
val data = JSONObject()
.put("number", "2026-114")
.put("customer", JSONObject().put("name", "Ana Silva"))
.put("due", "2026-12-31")
.put("items", JSONArray()
.put(JSONObject().put("description", "Consulting").put("qty", 4).put("price", 120))
.put(JSONObject().put("description", "Travel").put("qty", 1).put("price", 85.5)))
.put("total", 565.5)
.put("paid", false)
val template = assets.open("invoice.docx").use { it.readBytes() }
NexPdfDocument.fromDocxTemplate(template, data.toString(), """{"locale":"pt-PT"}""").use { doc ->
File(filesDir, "invoice-2026-114.pdf").writeBytes(doc.saveBytes())
}
val filledDocx = NexPdfDocument.fillDocxTemplate(template, data.toString()) // keep it as Word
check(filledDocx.isNotEmpty()) { NexPdfJni.lastError() }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.
Filling a .docx with the strict and locale options is the engine's
template_docx_fill_with(template, data_json, options_json). NexPdfJni has no typed method for
it: call it through NexPdfJni.invoke ({"fn":"template_docx_fill_with","args":[<template as base64>, dataJson, optionsJson]}; the result is the .docx as base64).
HTML templates
val 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}}
"""
NexPdfDocument.fromHtmlTemplate(html, data.toString(), null).use { doc ->
File(filesDir, "invoice.pdf").writeBytes(doc.saveBytes())
}Values are HTML-escaped; {{{raw}}} (three braces) inserts HTML as it is.
PDF templates
fillTemplate(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, or -1 on failure.
NexPdfDocument.openBytes(formTemplate).use { doc ->
val filled = doc.fillTemplate(data.toString(), """{"flatten":true}""")
check(filled >= 0) { NexPdfJni.lastError() }
File(filesDir, "filled.pdf").writeBytes(doc.saveBytes())
}For a raw handle the calls are NexPdfJni.templateDocxToPdf(template, dataJson, optionsJson) and
templateHtmlToPdf(html, dataJson, optionsJson) (a new handle, 0 on failure; free it with
NexPdfJni.free), templateDocxFill(template, dataJson) and
templateFillPdf(handle, dataJson, optionsJson). null data is {}.
Rows that no longer fit after filling break onto new pages. The text rows and graphics at the top and bottom edge of the page can be marked as a header and a footer, which repeat in place on every page instead of flowing with the content:
| Option | Default | Meaning |
|---|---|---|
header_height | 0 (no header) | Points from the top edge that hold the header |
footer_height | 72 | Points from the bottom edge that hold the footer |
Footer zone by default
With the default, a text row that starts in the bottom 72 pt (one inch) of the page is treated as
footer and repeated in place on every page; it does not flow with the content. 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. A small value such as 36 keeps a margin without catching rows.
Without footer_height the flow keeps a bottom margin of 36 to 72 pt. Rows taller than a page are
cut between lines. Graphics after the last row move with the end of the content, onto a page of
their own when they do not fit.
Text is shaped with OpenType and ordered with Unicode bidi; right-to-left text without explicit
alignment starts at the right. The font option picks the font for characters the page font cannot
show: "bundled" (the default), "keep", a path such as "/path/to/font.ttf", {"path": ...} or
{"data": "<base64>"}. Right-to-left text uses that font even when the page font has codes for it,
unless font is "keep".
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:
import android.util.Base64
val logo = assets.open("logo.png").use { it.readBytes() }
data.put("logo", JSONObject().put("data", Base64.encodeToString(logo, Base64.NO_WRAP)).put("width", 120))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, footer_height, font | PDF templates: see PDF templates | |
base_dir | HTML templates: the folder relative image paths are read from |
Syntax errors (an unclosed block, an unknown formatter) always fail. fromDocxTemplate and
fromHtmlTemplate then throw IllegalArgumentException with the engine's message; the other calls
return their failure value and NexPdfJni.lastError() has the message:
try {
NexPdfDocument.fromHtmlTemplate("<p>{{missing}}</p>", "{}", """{"strict":true}""").close()
} catch (e: IllegalArgumentException) {
Log.w("NexPDF", e.message ?: "") // names the field and the tag location
}