Ask Anvil

Answers to questions about automating PDFs, e-signatures, Webforms, and other paperwork problems.
PDFs
Categories

How do I generate a contract PDF with conditional clauses from customer data?

Keep one HTML template and branch the variable parts with ordinary code, then hand the finished HTML to a PDF generation API. You do not need a special conditional-clause feature: an if/else for optional clauses and an array map for repeating line items cover almost every contract.

Build the HTML with conditional clauses

Merge your customer data into an HTML string. Plain JavaScript handles the logic, so enterprise terms, optional auto-renewal, and a variable list of line items all live in one function:

// Build the contract HTML from customer data.
// Conditional clauses are plain if/else; repeating rows are an array map.
function buildContractHtml(customer) {
  const lineItems = customer.items
    .map((item) => `<tr><td>${item.name}</td><td>$${item.price}</td></tr>`)
    .join('')

  const liabilityClause = customer.plan === 'enterprise'
    ? '<p>Liability is capped at 12 months of fees paid.</p>'
    : '<p>Liability is capped at fees paid in the prior 3 months.</p>'

  const renewalClause = customer.autoRenew
    ? '<p>This agreement renews automatically each year.</p>'
    : ''

  return `
    <h1>Service Agreement</h1>
    <p>Prepared for ${customer.company}.</p>
    <table>${lineItems}</table>
    ${liabilityClause}
    ${renewalClause}
  `
}

Send it to a PDF generation API

Send that HTML to the API and write the returned PDF to disk. Anvil's generatePDF accepts either HTML and CSS or Markdown and returns the file as a buffer:

const Anvil = require('@anvilco/anvil')

const client = new Anvil({ apiKey: process.env.ANVIL_API_KEY })

const { statusCode, data } = await client.generatePDF({
  title: 'Service Agreement',
  type: 'html',
  data: {
    html: buildContractHtml(customer),
  },
})

if (statusCode === 200) {
  require('fs').writeFileSync('agreement.pdf', data)
}

Caveats

A few things to watch. Escape any user-supplied values before injecting them into the HTML, or a stray angle bracket will break the layout. Keep the template in version control so legal can review clause changes over time. And store the generated file right after the call, since the API returns the bytes once and does not keep a copy for you. Generating a PDF over Anvil's PDF generation API is metered at $0.10 per document, with 2,500 credits included when you add a card.

Back to All Questions

The fastest way to build software for documents

Anvil Document SDK is a comprehensive toolbox for product teams launching document flows where PDF filling, signing, and complex conditional scenarios are necessary.
Explore Anvil
Anvil Webforms