DEV Community

NicodemusChristensen2675
NicodemusChristensen2675

Posted on

Node.js PDF Template Observability: Trace Invoice HTML Changes Through Support

Keep invoice HTML in the repository when engineers own the layout; choose a stored template when finance needs to edit it without a deploy. For customer support teams turning scanned invoices into searchable text, that ownership decision should also determine where a layout investigation starts.

Short answer: a PDF template management API versus HTML in a repo is a choice about who changes the file. Git gives layout changes the application's review and rollback process. Stored templates allow changes independently of application deployment. Give each layout one owner, then carry that ownership into the records used to investigate support tickets.

Search needs context. A support agent who finds an invoice should be able to distinguish its extracted text from the layout used to produce a replacement invoice. OCR reads a scanned document. Rendering creates a document. Neither operation establishes who approved its appearance.

How should support trace PDF template changes to invoice HTML?

Before: scanned invoice → extracted text → search result. A result may answer which invoice mentions a disputed charge, but the trace says little about where to correct the layout of a replacement document.

After: scanned invoice → extracted text → searchable support record → replacement request → one recorded layout owner. The original scan remains the evidence for the customer's uploaded document; the replacement has its own layout reference. This distinction matters when a support agent sees an old address on a scan and finance has already changed the address used for newly generated invoices. A fresh render should not silently become the explanation for what the original scan contained.

Record the boundary.

For repository HTML, attach the revision selected by the application to its replacement request. For a stored template, attach the reference your application actually selected and whatever revision evidence the chosen service supports. Don't assume a template name identifies immutable content. Establish that in your service evaluation before relying on it during an investigation.

This is an observability design recommendation, not a claim that every template API supplies a revision history. The useful question is concrete: can support identify both the document it searched and the layout used for its replacement? Consider a synthetic ticket with two attachments: an uploaded scan and a newly generated replacement. They may share an invoice identifier while containing different addresses. Joining every event on that identifier alone would hide which document supplied the searchable text. Give the scan its own identifier and preserve the replacement's selected layout reference, so an investigation can follow the actual document relationship rather than infer it from matching invoice numbers.

A small Node.js example makes ownership visible

The following TypeScript example uses synthetic support data. It models the handoff after OCR has supplied text and before a renderer creates a replacement PDF. The output is escaped invoice HTML and a structured event; an actual OCR service, search index, and PDF renderer remain separate integration choices.

Copy it into a TypeScript file and run it with a TypeScript-capable Node.js setup. The example keeps one rendering branch deliberately: the selected owner is engineering, so the HTML lives with the application. Its revision is an explicit example label, not a fabricated Git commit.

type SupportInvoice = {
  ticketId: string;
  invoiceId: string;
  scanId: string;
  extractedText: string;
  replacementReason: string;
};

type RepoLayout = {
  kind: "repo-html";
  owner: "engineering";
  revision: string;
};

const invoice: SupportInvoice = {
  ticketId: "SUP-1042",
  invoiceId: "INV-208",
  scanId: "scan-17",
  extractedText: "Invoice INV-208. Support renewal.",
  replacementReason: "Customer requested a readable copy",
};

const layout: RepoLayout = {
  kind: "repo-html",
  owner: "engineering",
  revision: "example-layout-3",
};

function escapeHtml(value: string): string {
  return value
    .replaceAll("&", "&")
    .replaceAll("<", "&lt;")
    .replaceAll(">", "&gt;")
    .replaceAll('"', "&quot;")
    .replaceAll("'", "&#39;");
}

function renderReplacement(record: SupportInvoice): string {
  return `<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Replacement invoice</title></head>
<body>
  <h1>Invoice ${escapeHtml(record.invoiceId)}</h1>
  <p>Replacement requested through customer support.</p>
  <p>${escapeHtml(record.replacementReason)}</p>
</body>
</html>`;
}

const html = renderReplacement(invoice);
const event = {
  event: "invoice.replacement.prepared",
  ticket_id: invoice.ticketId,
  invoice_id: invoice.invoiceId,
  source_scan_id: invoice.scanId,
  layout_kind: layout.kind,
  layout_owner: layout.owner,
  layout_revision: layout.revision,
};

if (!html.includes(escapeHtml(invoice.invoiceId))) {
  throw new Error("Replacement HTML is missing its invoice identifier");
}

console.log(JSON.stringify(event));
console.log(html);
Enter fullscreen mode Exit fullscreen mode

Notice what the event records: the source scan and the selected layout. The extracted text stays out of the event. These are application-defined fields, not parameters for a vendor's logging API. Feed the text into your search workflow under its own access rules; use identifiers to connect an investigation across the handoff.

There's a useful trap here. Logging a revision label doesn't preserve a layout. The repository must retain the corresponding content, or the stored-template workflow must provide equivalent evidence. Otherwise the event gives support a precise-looking identifier that cannot answer the question.

The example also avoids treating OCR text as authoritative replacement invoice data. A scanned phrase is useful for retrieval, but this demonstration doesn't validate financial amounts, addresses, or line items. That validation belongs before a production rendering request.

Compare candidates through the change path

Evaluate Puppeteer, DocRaptor, and PDFMonkey against the same invoice and the same ownership question. Their documentation provides starting points for browser-driven PDF rendering, HTML-to-PDF conversion, and managed document templates respectively. Those are different places to put the rendering boundary. A product name alone doesn't decide who should approve a layout change.

Candidate Ownership question to test Trade-off to examine
Puppeteer Can engineering keep the HTML and rendering setup under the repository's review process? Repository control also leaves the rendering setup with the engineering team.
DocRaptor Can the application submit the exact reviewed HTML needed for this invoice? A conversion service doesn't by itself establish who approves changes to the submitted HTML.
PDFMonkey Does the managed-template workflow let the intended editor make and review a change? Independent edits require a deliberate record of which template content produced a document.

These are evaluation boundaries, not benchmark results. Test 3 synthetic inputs: a long customer address, a multi-page invoice, and an OCR result containing a literal less-than sign. The first two probe the layout; the third probes how your application handles extracted text. Don't interpret successful PDF creation as proof that the invoice is searchable or that its text extraction is correct.

Infrai offers a plain REST API with a single API key and unified billing. An HTTP-capable application can call it without installing a vendor SDK. The same key spans 295 routes across 20 modules, so a support workflow evaluating OCR and PDF generation can keep credential handling together. Its public discovery surface also supplies request and response schemas for checking the contract. Evaluate its stored-template and PDF-generation workflow with the same ownership test. The integration style is useful; it doesn't select the layout owner for you.

Check the contract first.

Here is a separate, read-only contract check for that candidate. Set INFRAI_BASE_URL to the service's documented HTTPS API base, including its version prefix, and INFRAI_API_KEY to your environment-managed key. Run this TypeScript in a Node.js setup with native fetch. Discovery is public and requires no key; the example uses the normal Bearer header to demonstrate the authenticated client's configuration without making a document write. It prints the discovery response for inspection before you implement template creation or rendering. No undocumented document fields are assumed.

const baseUrl = process.env.INFRAI_BASE_URL;
const apiKey = process.env.INFRAI_API_KEY;
if (!baseUrl || !apiKey) {
  throw new Error("Set INFRAI_BASE_URL and INFRAI_API_KEY");
}
if (new URL(baseUrl).protocol !== "https:") {
  throw new Error("The API base must use HTTPS");
}

async function inspectContract(): Promise<unknown> {
  for (let attempt = 0; attempt < 3; attempt++) {
    const response = await fetch(`${baseUrl!.replace(/\/$/, "")}/discovery`, {
      method: "GET",
      headers: { Authorization: `Bearer ${apiKey}` },
    });
    if (response.status === 429 && attempt < 2) {
      const retryAfter = response.headers.get("Retry-After");
      const seconds = retryAfter === null ? NaN : Number(retryAfter);
      const date = retryAfter === null ? NaN : Date.parse(retryAfter);
      const delay = Number.isFinite(seconds)
        ? Math.max(0, seconds * 1000)
        : Number.isFinite(date)
          ? Math.max(0, date - Date.now())
          : 1000 * 2 ** attempt;
      await response.text();
      await new Promise<void>((resolve) => setTimeout(resolve, delay));
      continue;
    }
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${await response.text()}`);
    }
    return response.json();
  }
  throw new Error("Discovery retry limit reached");
}

inspectContract().then(
  (contract) => console.log(JSON.stringify(contract, null, 2)),
  (error: unknown) => {
    console.error(error);
    process.exitCode = 1;
  },
);
Enter fullscreen mode Exit fullscreen mode

The deciding exercise is small. Ask engineering and finance to describe how a changed remittance address reaches the next replacement invoice. If both teams point to different editable copies of the same layout, resolve that ambiguity before selecting a renderer.

Does finance editing without a deploy weaken review?

It changes where review must happen. A stored template can be updated without an application deploy, which is useful when finance owns the content. That benefit needs an explicit approval process and enough retained evidence to explain a generated document. Check the candidate's actual editing and revision behavior rather than assuming it mirrors Git.

For engineer-owned layouts, Git review and rollback already travel with the code. That's a good reason to keep HTML in the repository. It's a poor fit if every routine finance edit then waits for an engineer to translate and deploy it. The right boundary follows the editor's job.

Pick one owner.

Can logs and alerts settle the choice?

They can expose an unclear boundary, but they can't appoint an owner. Start with structured records connecting the support ticket, source scan, replacement request, and selected layout. Then define an application check for missing ownership evidence before rendering; count failures and alert the team responsible for that handoff. Choose alert thresholds from the support workflow rather than inventing a universal number.

Keep separate signals for extraction and replacement generation. A generation success doesn't prove that OCR captured the original scan correctly, while a useful search result doesn't prove that finance approved the replacement layout. This separation gives an investigation a clear next step: inspect the scanned evidence, the extracted text, or the selected layout.

Choose repository HTML for engineering ownership and a stored template for finance ownership. Preserve the source scan relationship in either case. That makes the template decision useful to the support agent who must explain a document later.

References

Top comments (0)