The reliable pattern here is a template registry plus a render step. Keep one HTML or Markdown template per document type, look up the right template for a database record, merge the record's fields into the markup, then post the rendered markup to a PDF generation endpoint. Here is the shape in Node:
import Anvil from '@anvilco/anvil'
const anvilClient = new Anvil({ apiKey: process.env.ANVIL_API_KEY })
// One template per document type. Use {{tokens}} for record fields.
const templates = {
nda: "<h1>Mutual NDA</h1><p>Between {{partyA}} and {{partyB}}, effective {{date}}.</p>",
msa: "<h1>Master Services Agreement</h1><p>{{clientName}} engages {{vendorName}} on {{date}}.</p>",
}
function render(template, row) {
return template.replace(/{{(\w+)}}/g, (_, key) => row[key] ?? '')
}
async function generateFromRecord(row) {
const html = render(templates[row.docType], row)
const { statusCode, data } = await anvilClient.generatePDF({
title: `${row.docType}-${row.id}`,
type: 'html',
data: { html },
})
if (statusCode !== 200) throw new Error(`Generation failed: ${statusCode}`)
return data // PDF bytes; write to disk with { encoding: null }
}Why a template registry
Each document type is one reusable template, kept separate from your application logic. Adding a new contract type means adding a template entry, not branching your code. You can also move the templates out of code and into your database or object storage, then load them by key, so non-engineers can edit wording without a deploy.
Handling variable-length content
When a record has line items or other repeating sections, build that part of the markup in your render step by looping over the array before you send it. Anvil also supports repeating PDF pages for data that spans an unknown number of rows. If you prefer lighter formatting than full HTML and CSS, send a Markdown template instead by setting type to markdown; Markdown tables are supported.
Two things to watch
Generation is a server-side call, so keep your API key on the server and never expose it in a browser. Development keys are free but add a watermark to the output, so switch to a production key for final documents. Anvil bills generation at $0.10 per PDF after the 2,500 free credits you get when you add a card; the PDF generation docs cover headers, footers, page numbers, and custom fonts.
Back to All Questions