Skip to Content
NexPDF

Templates

Generate PDFs from Word, HTML and PDF templates filled with JSON data, with loops, conditions, formatters and images, with NexPDF for Rust.

English

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

Document::template_docx_to_pdf(template, data_json, options_json) returns a new Document; nexpdf_sdk::template_docx_fill(template, data_json) returns the filled .docx as Vec<u8>, and nexpdf_sdk::template_docx_fill_with(template, data_json, options_json) does the same with the strict and locale options.

use nexpdf_sdk::Document;
use serde_json::json;

fn main() -> nexpdf_sdk::Result<()> {
    let data = json!({
        "number": "2026-114",
        "customer": {"name": "Ana Silva"},
        "due": "2026-12-31",
        "items": [
            {"description": "Consulting", "qty": 4, "price": 120},
            {"description": "Travel", "qty": 1, "price": 85.5}
        ],
        "total": 565.5,
        "paid": false
    })
    .to_string();

    let template = std::fs::read("invoice.docx")?;
    let doc = Document::template_docx_to_pdf(&template, &data, r#"{"locale":"pt-PT"}"#)?;
    doc.save("invoice-2026-114.pdf")?;

    let filled_docx = nexpdf_sdk::template_docx_fill(&template, &data)?;   // keep it as Word
    std::fs::write("invoice-2026-114.docx", &filled_docx)?;

    // with options: a missing field fails, Portuguese dates and numbers
    let strict_docx =
        nexpdf_sdk::template_docx_fill_with(&template, &data, r#"{"strict":true,"locale":"pt"}"#)?;
    std::fs::write("invoice-2026-114-pt.docx", &strict_docx)?;
    Ok(())
}

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

let html = r#"
<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}}
"#;

let doc = Document::template_html_to_pdf(html, &data, None)?;
doc.save("invoice.pdf")?;

Values are HTML-escaped; {{{raw}}} (three braces) inserts HTML as it is.

PDF templates

template_fill_pdf(data_json, options_json) fills an existing PDF in place (&mut self): 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.

let mut doc = Document::open("form-template.pdf")?;
let filled = doc.template_fill_pdf(&data, r#"{"flatten":true}"#)?;
doc.save("filled.pdf")?;

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).

Header and footer zones. header_height and footer_height (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 and repeated in place on every page, instead of flowing with the content. This is new in 1.1. 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.

doc.template_fill_pdf(&data, r#"{"footer_height":0}"#)?;          // no footer zone
doc.template_fill_pdf(&data, r#"{"header_height":90,"footer_height":36}"#)?;

Characters the page font cannot show are drawn in the font option's font. That text is shaped (OpenType) and laid out in bidi order, and right-to-left text uses that font even when the page font has codes for it, unless font is keep.

Syntax

TagMeaning
{{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. For example, with the base64 crate:

use base64::Engine as _;

let logo = base64::engine::general_purpose::STANDARD.encode(std::fs::read("logo.png")?);
let data = json!({"logo": {"data": logo, "width": 120}, "number": "2026-114"}).to_string();

Options

OptionDefaultMeaning
strictfalseA field missing from the data fails the call, naming the field and where the tag is. Otherwise it renders empty
localeenDefault locale of currency and number (en, de, fr, pt-BR, …)
flattenfalsePDF templates: flatten the form after filling
fieldstruePDF templates: fill AcroForm fields
texttruePDF templates: replace placeholders in the page text
header_height0PDF templates: height in points of the top zone that repeats on every page
footer_height72PDF templates: height in points of the bottom zone that repeats on every page; 0 turns it off
fontbundledPDF templates: font for characters the page font cannot show: bundled, keep, a path to a .ttf, {"path"} or {"data":"<base64>"}
base_dirHTML templates: folder relative images and links resolve against

Syntax errors (an unclosed block, an unknown formatter) always fail. The error is an Error::Engine with the engine's message:

if let Err(e) = Document::template_html_to_pdf("<p>{{missing}}</p>", "{}", r#"{"strict":true}"#) {
    eprintln!("{e}");          // names the field and the tag location
}

On this page