Skip to Content
NexPDF

Templates

Generate PDFs from Word, HTML and PDF templates filled with JSON data, with loops, conditions, formatters and images, in the Electron main process with NexPDF.

English

License module

Templates need the conversion module (Startup tier and above), activated for the document API.

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. The three kinds share one syntax.

The window has no template tools. These calls run in the main process through the document API: WasmDocument from documents() and doc.raw on an open document. Show the result in a window with openDocument(pdf.engine, bytes, name).

Word templates

WasmDocument.templateDocxToPdf(templateBytes, dataJson, optionsJson) fills a .docx and converts it to PDF. It returns a WasmDocument; free it with free() when you are done.

const fs = require('node:fs');
const { documents } = require('@nexdevit/nexpdf-electron');
const { WasmDocument } = documents();

const data = {
  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,
};

const raw = WasmDocument.templateDocxToPdf(fs.readFileSync('invoice.docx'), JSON.stringify(data), '{"locale":"pt-PT"}');
try {
  fs.writeFileSync('invoice-2026-114.pdf', raw.saveBytes());
} finally {
  raw.free();
}

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.

To keep the result as Word, templateDocxFillWith(templateBytes, dataJson, optionsJson) from documents() returns the filled .docx bytes; it takes the strict and locale options (templateDocxFill(templateBytes, dataJson) uses the defaults):

const { templateDocxFillWith } = documents();
fs.writeFileSync('invoice-2026-114.docx', templateDocxFillWith(fs.readFileSync('invoice.docx'), JSON.stringify(data), '{"locale":"pt-PT"}'));

HTML templates

const 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}}
`;

const raw = WasmDocument.templateHtmlToPdf(html, JSON.stringify(data), null);
fs.writeFileSync('invoice.pdf', raw.saveBytes());
raw.free();

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

PDF templates

doc.raw.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.

const { openDocumentFile } = require('@nexdevit/nexpdf-electron');

const doc = await openDocumentFile('form-template.pdf');
const filled = doc.raw.templateFillPdf(JSON.stringify(data), '{"flatten":true}');
await doc.save('filled.pdf');
doc.close();

Pages that overflow

Rows that no longer fit, for example after an {{#each}} grew a table, break onto new pages. Text rows and graphics at the top and bottom edge of the page repeat in place on every page:

OptionDefaultMeaning
header_heightnonePoints from the top edge: rows and graphics there are a header, repeated on every page
footer_height72Points from the bottom edge: rows and graphics there are a footer, repeated on every page

The footer zone is on by default

Without footer_height, 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. 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, and graphics after the last row move with the end of the content (onto a page of their own when they do not fit).

Text in characters the page font cannot show is drawn in a fallback font, shaped with OpenType and in bidi visual order; right-to-left text uses the fallback font even when the page font has codes for it. The font option picks that font: bundled (the default: the Liberation font of the same family and style), keep (no substitution: a character the page font cannot show is an error), or {"data": "<base64>"} with TrueType or OpenType data. The engine runs in WebAssembly, without access to the file system, so pass the font's bytes rather than a path:

const options = { font: { data: fs.readFileSync('NotoSansArabic-Regular.ttf').toString('base64') }, footer_height: 36 };
const form = await openDocumentFile('form-template.pdf');
form.raw.templateFillPdf(JSON.stringify(data), JSON.stringify(options));
await form.save('filled.pdf');

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:

data.logo = { data: fs.readFileSync('logo.png').toString('base64'), width: 120 };

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_height, footer_heightnone, 72PDF templates: the header and footer zones, in points (see Pages that overflow)
fontbundledPDF templates: the font for characters the page font cannot show

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

try {
  WasmDocument.templateHtmlToPdf('<p>{{missing}}</p>', '{}', '{"strict":true}');
} catch (e) {
  console.log(e.message);     // names the field and the tag location
}

On this page