Workflow pattern: invoice or certificate PDF from a record, saved to an attachment field

Turning a record into a PDF comes up here a lot (Create PDF, printable delivery notes, invoices with line items), so here is a workflow pattern that renders a record to PDF and stores the file in an attachment field on the same record. If you have the Template Print plugin, that is the built-in route. This pattern is for when you want to lay the document out in HTML and CSS, or use a renderer you already run.

It builds on hongboji’s answer in Workflow pattern: sending an attachment image to an external image-to-image API: no single node saves a remote file into an attachment field, so one JavaScript node fetches the file and uploads it through the file HTTP API.

Example collection invoices: invoice_no, status, many-to-one customer, one-to-many items (description, qty, unit_price), and an attachment field pdf.

1. Trigger: Collection event

  • Collection: invoices
  • Trigger on: After record added or updated. Pick status as the changed field and add a condition such as status equals issued, so drafts don’t render.
  • Preload associations: customer and items, so later nodes can read them.

2. JavaScript node: build the HTML

The default safe mode is enough here. Add an argument invoice set to the trigger data, then:

const esc = (v) => String(v ?? '').replace(/[&<>"']/g, (c) =>
  ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
let total = 0;
const rows = (invoice.items || []).map((it) => {
  const line = Number(it.qty) * Number(it.unit_price);
  total += line;
  return `<tr><td>${esc(it.description)}</td><td class="n">${esc(it.qty)}</td><td class="n">${line.toFixed(2)}</td></tr>`;
}).join('');
return `<!doctype html><html><head><meta charset="utf-8"><style>
body { font-family: Arial, sans-serif; font-size: 12px; }
table { width: 100%; border-collapse: collapse; }
thead { display: table-header-group; }
tr { break-inside: avoid; }
th, td { padding: 6px; border-bottom: 1px solid #ddd; text-align: left; }
.n { text-align: right; }
</style></head><body>
<h1>Invoice ${esc(invoice.invoice_no)}</h1>
<p>${esc(invoice.customer?.name)}</p>
<table><thead><tr><th>Item</th><th class="n">Qty</th><th class="n">Amount</th></tr></thead>
<tbody>${rows}</tbody></table>
<p class="n"><strong>Total ${total.toFixed(2)}</strong></p>
</body></html>`;

thead { display: table-header-group } repeats the table header when a long invoice runs onto page two, and break-inside: avoid keeps a row from splitting across pages.

3. JavaScript node: render, download and upload

The HTML from step 2 is full of quotes and line breaks, so pasting it into a JSON body in an HTTP request node is fragile. It is cleaner to make the render call from a script, and a script is needed anyway to get the file into an attachment field, because no built-in node saves a remote file there.

Safe mode has no network access, so this node needs modules. Set this on the server and restart:

WORKFLOW_SCRIPT_MODULES=axios,form-data,timers

That switches script nodes from the QuickJS sandbox to Node’s vm, which the docs warn is not a security boundary, so only do it if everyone who can edit workflows is trusted. Create an API key (API keys plugin) for a role allowed to upload, and keep both keys in Variables and secrets.

Arguments: html (step 2 result), invoiceId, invoiceNo, renderKey, nbUrl (your app URL), nbKey. Set the node’s Timeout to something like 120000.

This example uses thirds.ai, which answers with a JSON job rather than the file. status is queued, running, succeeded, failed or cancelled, so HTTP 200 alone does not mean it worked. Once it has succeeded, download.url is a path like /v1/downloads/... on thirds.ai. That link needs no key and expires after 15 minutes, which is why the script saves the file itself rather than the link.

const axios = require('axios');
const FormData = require('form-data');
const { setTimeout: sleep } = require('timers/promises');

// Render. The Idempotency-Key makes a retried run return the same job.
const auth = { Authorization: `Bearer ${renderKey}` };
let j = (await axios.post('https://thirds.ai/v1/pdf', {
  html,
  pdf: { format: 'A4' },
}, { headers: { ...auth, 'Idempotency-Key': `invoice-${invoiceId}` } })).data;

// Wait for the job if it was still queued or running
for (let i = 0; j.status === 'queued' || j.status === 'running'; i++) {
  if (i >= 20) throw new Error('render still running');
  await sleep(3000);
  j = (await axios.get(`https://thirds.ai/v1/pdf/${j.id}`, { headers: auth })).data;
}
if (j.status !== 'succeeded') throw new Error(`render ${j.status}`);
const pdf = await axios.get(`https://thirds.ai${j.download.url}`, { responseType: 'arraybuffer' });

// With Gotenberg (self-hosted, returns the PDF bytes directly),
// replace everything above from "Render" with:
// const g = new FormData();
// g.append('files', html, { filename: 'index.html', contentType: 'text/html' });
// const pdf = await axios.post(`${gotenbergUrl}/forms/chromium/convert/html`, g,
//   { headers: g.getHeaders(), responseType: 'arraybuffer' });

const form = new FormData();
form.append('file', pdf.data, { filename: `invoice-${invoiceNo}.pdf`, contentType: 'application/pdf' });
const up = await axios.post(`${nbUrl}/api/attachments:create?attachmentField=invoices.pdf`, form, {
  headers: { ...form.getHeaders(), Authorization: `Bearer ${nbKey}` },
});
return up.data.data; // the new file record

attachmentField=invoices.pdf makes the upload use the storage configured on that field.

4. Update record node

  • Collection: invoices. Mode: Update one by one (bulk mode doesn’t set association fields).
  • Filter: id equals the trigger data id.
  • Field pdf: the step 3 result.

Because the trigger only watches status, writing pdf doesn’t start the workflow again.

5. Mailer node (optional)

Send the customer’s email from the preloaded customer, and under Attachments pick the step 3 result. The node only accepts variables that resolve to file records, and that result is one.

Only the top of step 3 is tied to a renderer, so any HTML to PDF service fits: Gotenberg if you self-host, or a hosted API. The thirds.ai quickstart shows the job JSON and download step used above.

I wrote the step 3 script from the docs and haven’t run it end to end on a 2.x instance yet, so try it on a copy of your app first, and I’ll fix anything that’s off.

If anyone has saved a remote file into an attachment field without enabling modules, for example with a custom node, I’d like to hear how you did it.

(Disclosure: I’m connected to thirds.ai.)