Generate PDFs from an Excel template using JavaScript
Nutrient Web SDK generates documents from Excel templates by merging XLSX files with data. The populated output remains an XLSX file. You can convert it to PDF or PDF/A in the same pipeline.
You can run this flow headlessly or in the Nutrient viewer UI. If your base document is a Word or PowerPoint file, refer to the Word template guide or the PowerPoint template guide. If your base document is already a PDF, refer to the PDF template guide.
This guide covers these tasks:
- Prepare XLSX templates with placeholders.
- Populate templates with structured data.
- Export output as PDF or PDF/A.
General principles
Excel templating uses three inputs:
- An XLSX file that acts as the template.
- A template model with placeholder values.
- Optional delimiter configuration.
populateDocumentTemplate() processes every worksheet in the workbook. It returns an ArrayBuffer that contains a populated XLSX file.
Template model
You can define the template model in an external JSON file. You can also build it in code.
The model includes these fields:
- Optional delimiter configuration with
startandendvalues. The default delimiters are{and}. - At least one placeholder-value pair. Placeholder names must match the placeholders in the XLSX template.
Classes, methods, and properties
This guide uses this SDK entry point:
Populate an Excel template
Nutrient Web SDK supports placeholder replacement, row loops, conditions, and images in XLSX templates. Placeholders work in cells on every worksheet. The SDK supports typed number, date, percentage, and Boolean cells.
Start by preparing an XLSX template with placeholders. This example uses {{ and }} delimiters.
Placeholder naming rules
Placeholder names must follow these rules:
- Simple segments — Avoid whitespace and marker prefix characters, such as
#,^,/,%, and!. - Valid examples —
{{name}},{{firstName}},{{item_1}},{{TOTAL_AMOUNT}}, and{{company.name}}. - Nested values — Use dotted paths, such as
{{company.name}}, to reference object values. - Literal dots — Use
objectDelimiterif a model key contains literal dots.
These rules help the parser read templates and avoid conflicts with special syntax characters.
Prepare data for an invoice template:
const data = { config: { delimiter: { start: "{{", end: "}}", }, }, model: { company: { name: "Nutrient GmbH", address: "Konrad-Zuse-Ring 3", cityStateZip: "10123 Berlin, Germany", }, client: { name: "Acme Corporation", address: "1 Market Street, San Francisco, CA 94105", }, invoiceNo: "INV-2024-0042", issueDate: "2024-06-15", dueDate: "2024-07-15", terms: "Net 30", subtotal: "1050", taxRate: "8.5%", total: "1085", },};Load the XLSX template and replace its placeholders. The method returns an ArrayBuffer with the populated XLSX file:
const buffer = await NutrientViewer.populateDocumentTemplate( { // Other configuration options. document: "invoice-template.xlsx", }, data,);Next, convert the XLSX file to PDF. This example converts to PDF/A-1a. Choose the conformance value you need from the conformance enumeration.
const pdfBuffer = await NutrientViewer.convertToPDF( { // Other configuration options. document: buffer, }, NutrientViewer.Conformance.PDFA_1A,);If you skip conversion, the populated ArrayBuffer remains a valid XLSX file. Download it directly or load it in the viewer with NutrientViewer.load(). The viewer handles it as an Office document through the standalone conversion pipeline.
Row loops
Loops repeat rows based on arrays in your data model. Use row loops for invoice line items, time entries, or inventory lists.
Place the opening tag in the first cell of the row you want to repeat. Place the closing tag in the last cell of the same row.
For each object in the array, the SDK repeats the row and resolves the placeholders inside it. Content below the loop shifts down as rows are inserted.

Step one — Prepare your data
Define the array that the row loop will repeat:
const data = { config: { delimiter: { start: "{{", end: "}}", }, }, model: { lineItems: [ { item: "1", description: "Logo design", amount: "150" }, { item: "2", description: "Website mockups", amount: "600" }, { item: "3", description: "Brand guidelines", amount: "300" }, ], },};Step two — Generate the populated workbook
Pass the template and model to populateDocumentTemplate():
const buffer = await NutrientViewer.populateDocumentTemplate( { // Other configuration options. document: "invoice-template.xlsx", }, data,);The populated workbook contains one row per line item. It removes all template markers.
Image substitution
NutrientViewer.populateDocumentTemplate() supports image substitution in XLSX templates. You can use image markers with text, loops, and conditionals.
Use these markers in your template:
{{%name}}— Inserts an inline image.{{%%name}}— Inserts a centered image.
Set the model entry to an image object with _type: "image":
const data = { config: { delimiter: { start: "{{", end: "}}", }, }, model: { logo: { _type: "image", source: "base64", format: "png", data: "iVBORw0KGgoAAAANSUhEUg...", width: 72, height: 72, altText: "Nutrient logo", }, },};Supported image sources
The source field selects how the image payload is supplied:
source: "base64"— Uses the raw Base64 payload indata.source: "dataUrl"— Uses the data URL payload indataas a Base64 alias.source: "url"— Uses the HTTP(S) URL inurland normalizes it at runtime.
For URL sources, the host must enable cross-origin resource sharing (CORS). If the host doesn’t configure CORS, use Base64 or data URL payloads.
Validation and limitations
Review these image constraints before you build your template:
- For raw Base64 payloads, set
formatexplicitly. For example, usepng,jpg,gif,bmp, ortif. source: "file"isn’t supported in browser public APIs.- Scalable Vector Graphics (SVG) payloads and SVG formats aren’t supported in this release.
- If any image entry is invalid or can’t be resolved, the complete templating request fails.
Image entries also support optional properties such as borders, captions, rotation, link targets, and accessibility metadata. For the full list, refer to the populateDocumentTemplate API reference.
Add conditional logic
Conditionals insert and remove cell content based on conditions in the template. You can combine conditionals with row loops.
Use this syntax:
#condition— Starts a block rendered when the condition istrue.^condition— Starts a block rendered when the condition isfalse./condition— Ends the conditional block.
This example uses hasDiscount in a cell:
{{#hasDiscount}}Discount applied{{/hasDiscount}}{{^hasDiscount}}No discount{{/hasDiscount}}Combine the template with this data:
{ config: { delimiter: { start: "{{", end: "}}" } }, model: { hasDiscount: true }}The populated cell contains Discount applied. The inverse block is removed. Conditions are evaluated per worksheet, so the same model drives conditions on every sheet.
Limitations
Review these Excel templating limitations before you build a template:
- Column loops aren’t supported. Only rows repeat.
- List expansion within a single cell isn’t supported. Use a row loop instead.
- Formula references, structured table ranges, and defined names aren’t adjusted when a row loop inserts rows.
- Update formulas that depend on shifted data after population, or avoid formulas that reference the loop area.
- Merged-cell ranges below inserted rows shift with their contents.
- A merged range on a repeated row is retained only for the first generated row.
Abort template population
To abort the returned promise for an in-progress populateDocumentTemplate() call, pass an AbortSignal(opens in a new tab) through the signal configuration option. This also works with convertToPDF() in the same pipeline:
const controller = new AbortController();
async function generatePdf() { const buffer = await NutrientViewer.populateDocumentTemplate( { document: "invoice-template.xlsx", signal: controller.signal, }, data, );
const pdfBuffer = await NutrientViewer.convertToPDF( { document: buffer, signal: controller.signal, }, NutrientViewer.Conformance.PDFA_1A, );
return pdfBuffer;}
generatePdf().catch((error) => { if (error.name === "AbortError") { console.log("Generation cancelled"); }});
// Abort the returned promise at any point during the pipeline.// Underlying processing may continue in the background.controller.abort();