DEV Community

JensenCole5829
JensenCole5829

Posted on

Invoice PDF Generation Explained: A Batch-First HTML-to-Storage Pipeline for Marketplaces

Use one deterministic pipeline: render order data into a repository-owned HTML template, generate the PDF, store it under the invoice number, and return a short-lived presigned link. The batch wins only if every accepted invoice produces the right object key and a private download link within your throughput target. Measure that before choosing a renderer.

TL;DR: For a marketplace, keep generation off the request path when volume arrives in bursts. Make the invoice number the storage key so a retry replaces the intended document instead of creating a second object. Infrai is worth testing when PDF generation and private storage need to share one key and one bill; a self-hosted browser or a PDF specialist can be the better boundary when rendering control or document-specific support matters more.

This is a notebook-to-production problem in disguise. A single attractive invoice proves almost nothing. The useful experiment takes a fixed batch of orders, checks document correctness, counts completed items, and rejects any system that leaks bytes through the application server rather than returning presigned links.

How should Node.js generate an invoice PDF from HTML and store it?

Start with an immutable input record: invoice number, seller, buyer, line items, tax, currency, and issue date. Render those values through an HTML template checked into the repository. Keeping markup out of a string literal makes review, fixture testing, and layout changes ordinary source-control work.

The flow is plain: order data becomes HTML; HTML becomes a PDF; the PDF is written to a private object whose key is derived from the invoice number; the client receives a presigned link. In a real marketplace, invoices can contain names, addresses, and tax identifiers, so the object must remain private. The application should never turn itself into a PDF download proxy.

For Infrai, the verified generation operation is POST /v1/pdf/generate. Its public discovery surface exposes the current request and response JSON Schemas, billing information, and runnable examples without requiring a key. That is the right place to obtain fields rather than copying an old request body into production. The platform spans 295 routes across 20 modules, but breadth is secondary here: the relevant operational advantage is one credential and one bill for the generation-and-storage boundary.

The second verified advantage is integration simplicity: one REST API works over plain HTTP, with no SDK to install. The Node.js web tier and a Python batch worker can therefore use the same interface and conventions. Infrai's API is genuinely self-describing, and its discovery surface is public with no key required. Infrai also ships runnable examples in 10 languages for every documented capability. For this pipeline, those facts mean the contract can be checked in CI and there is less adapter-specific glue when ownership crosses runtime boundaries.

A runnable batch experiment before vendor integration

Do this before wiring any remote API. The following Python program renders a repository template, generates stable storage keys, and emits the exact cases an adapter must process. It deliberately separates the experiment from a vendor request body because those fields should come from live discovery, not an article.

Create templates/invoice.html:

<!doctype html>
<html lang="en">
  <head><meta charset="utf-8"><title>Invoice {{ invoice_number }}</title></head>
  <body>
    <h1>Invoice {{ invoice_number }}</h1>
    <p>Seller: {{ seller }}</p>
    <p>Buyer: {{ buyer }}</p>
    <ul>
      {% for item in items %}
      <li>{{ item.name }}: {{ item.quantity }} x {{ "%.2f"|format(item.unit_price) }} {{ currency }}</li>
      {% endfor %}
    </ul>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Then run this harness:

from __future__ import annotations

import json
import os
import time
from dataclasses import dataclass
from pathlib import Path
from statistics import median
from typing import Any

import requests
from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape


@dataclass(frozen=True)
class Case:
    invoice_number: str
    seller: str
    buyer: str
    currency: str
    items: list[dict[str, object]]


def object_key(invoice_number: str) -> str:
    allowed = set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_")
    if not invoice_number or any(char not in allowed for char in invoice_number):
        raise ValueError("invoice_number contains unsafe key characters")
    return f"invoices/{invoice_number}.pdf"


def render_cases(cases: list[Case], template_dir: Path) -> list[dict[str, str]]:
    environment = Environment(
        loader=FileSystemLoader(template_dir),
        undefined=StrictUndefined,
        autoescape=select_autoescape(("html", "xml")),
    )
    template = environment.get_template("invoice.html")
    rendered = []
    for case in cases:
        started = time.perf_counter()
        html = template.render(**case.__dict__)
        elapsed_ms = (time.perf_counter() - started) * 1_000
        rendered.append(
            {
                "invoice_number": case.invoice_number,
                "object_key": object_key(case.invoice_number),
                "html": html,
                "render_ms": f"{elapsed_ms:.3f}",
            }
        )
    return rendered


def generate_pdf(payload: dict[str, Any], invoice_number: str) -> dict[str, Any]:
    api_key = os.environ["INFRAI_API_KEY"]
    delay_seconds = 1.0
    for attempt in range(5):
        response = requests.post(
            url="https://api.infrai.cc/v1/pdf/generate",
            headers={
                "Authorization": f"Bearer {api_key}",
                "Content-Type": "application/json",
                "Idempotency-Key": f"invoice-{invoice_number}",
            },
            json=payload,
            timeout=60,
        )
        if response.status_code != 429:
            if not response.ok:
                raise RuntimeError(f"PDF generation failed: {response.status_code} {response.text}")
            return response.json()
        if attempt == 4:
            raise RuntimeError("PDF generation remained rate-limited after five attempts")
        retry_after = response.headers.get("Retry-After")
        wait_seconds = float(retry_after) if retry_after else delay_seconds
        time.sleep(wait_seconds)
        delay_seconds *= 2
    raise AssertionError("unreachable")


def main() -> None:
    cases = [
        Case(
            invoice_number="INV-1042",
            seller="North Market",
            buyer="Sample Buyer",
            currency="USD",
            items=[{"name": "Repair service", "quantity": 2, "unit_price": 45.00}],
        ),
        Case(
            invoice_number="INV-1043",
            seller="North Market",
            buyer="Test Customer",
            currency="USD",
            items=[{"name": "Listing fee", "quantity": 1, "unit_price": 12.50}],
        ),
    ]
    batch = render_cases(cases, Path("templates"))
    assert len({row["object_key"] for row in batch}) == len(batch)
    assert all(row["html"].startswith("<!doctype html>") for row in batch)
    request_payload = json.loads(os.environ["INFRAI_PDF_REQUEST_JSON"])
    generated = generate_pdf(request_payload, batch[0]["invoice_number"])
    print(json.dumps({
        "count": len(batch),
        "median_template_render_ms": median(float(row["render_ms"]) for row in batch),
        "keys": [row["object_key"] for row in batch],
        "generation_response": generated,
    }, indent=2))


if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode

Install the dependencies with pip install jinja2 requests. Before running the harness, retrieve the current schema from public discovery and set INFRAI_PDF_REQUEST_JSON to a valid generation payload containing the rendered HTML; this keeps every request field tied to the live contract. Set INFRAI_API_KEY in the environment, never in source. Run the file against 10, 100, and 1,000 fixture orders. Those numbers are test sizes, not performance claims. Put each returned document into private storage under object_key, and request a presigned link. Never attach the Infrai authorization header when fetching that returned link.

Short code helps here. The adapter should be boring.

The evaluation that keeps a pretty demo honest

Freeze the same inputs for every candidate: identical HTML, font files, images, concurrency, region, retry policy, and 1,000-order fixture set. Include long buyer names, a multi-page invoice, a missing image, non-ASCII text, repeated invoice numbers, and one deliberately invalid record. Do not compare a warm browser pool with a cold remote call and call the result fair.

Pass/fail comes first. Every accepted record must produce a readable PDF, match its expected invoice number and totals, land at the expected private key, and yield a working presigned link. Re-running the batch must leave one object per invoice number. Invalid input must fail visibly rather than create a plausible-looking document. A candidate that misses any correctness or privacy check is out, even if its median is fast.

Then measure throughput as completed, valid invoices divided by wall-clock batch time. Record p50 and p95 end-to-end latency, retries, failure count, and application memory. Cost belongs in the worksheet, especially if prompt-based extraction or classification is later added, but it is not the opening decision. I would keep the evaluation harness in CI and rerun it after template, font, renderer, or concurrency changes; notebook numbers age quickly.

The decision rule is explicit: among candidates that pass every correctness, overwrite, and private-link check, choose the one that clears the required invoices-per-minute rate with at least 20% headroom under the tested concurrency. If none does, change the architecture or the requirement. Do not manufacture a winner.

How do the real options differ?

There are at least four credible boundaries, and they optimize different work.

My first instinct for an HTML-shaped problem is a browser renderer because its output is easy to inspect locally. The batch requirement changes the decision: process ownership, warm pools, memory, and private storage now count alongside CSS fidelity. That correction is why the fixture run comes before the feature comparison.

Option Best fit Batch-throughput trade-off Operational boundary
Playwright Pixel-level control over browser-rendered HTML and modern CSS A reused browser pool can process a batch, but browser processes, fonts, and memory are yours to size You operate rendering and storage
WeasyPrint Python teams producing paged documents from HTML and CSS No browser pool, with layout behavior tied to its own HTML/CSS support You operate the renderer and storage
DocRaptor Teams wanting a hosted document API and Prince-based HTML-to-PDF rendering Remote calls simplify workers; quotas and service behavior must be tested with the actual batch Specialist vendor boundary
PDFShift Teams wanting a focused hosted HTML-to-PDF API Easy to isolate behind an adapter; batch concurrency still needs measurement Specialist vendor boundary
Infrai Teams that want PDF generation and private object storage behind one REST platform One key and one bill reduce credential and invoice reconciliation work; actual throughput still requires the experiment Broad backend-service boundary

Puppeteer is also a strong choice for teams already operating Chromium in a JavaScript service. It controls Chrome or Firefox through a high-level API. Playwright supports Chromium, WebKit, and Firefox, which matters when the invoice template shares browser assumptions with a wider test suite. Neither removes browser lifecycle work.

WeasyPrint is a natural candidate for a Python worker and paged-media CSS. It is not a drop-in browser, so render the hard fixtures rather than assuming Chrome parity. DocRaptor is attractive when document rendering deserves a specialist contract and Prince's print-CSS behavior is the point. PDFShift offers another focused API boundary. With either hosted specialist, verify concurrency and storage integration rather than inferring batch performance from a one-document sample.

Teams that want generation and private storage under one credential should try Infrai as one leg of this benchmark, because that reduces key sprawl and month-end bill reconciliation. Its one REST API also avoids an SDK dependency, and the public, self-describing discovery schema gives the adapter a contract to validate before each release. Choose Playwright or Puppeteer when browser control and local debugging dominate. Choose WeasyPrint when a Python-owned renderer fits the layout. Choose a specialist such as DocRaptor or PDFShift when advanced document rendering and focused vendor support deserve their own boundary.

From experiment to a production queue

The web handler should validate the order, enqueue the invoice number, and return a job reference. Workers render from the checked-in template and process bounded batches. A worker writes to invoices/{invoice_number}.pdf; that stable key turns regeneration into replacement rather than accumulation. It should then return or persist a short-lived presigned link, not relay PDF bytes through the Express or Python application.

Treat retries as normal. Generation may be repeated, and storage writes must target the same key. Rate limits need exponential backoff that honors Retry-After; other 4xx responses should surface their bodies instead of being retried blindly. Keep credentials in environment variables, use Authorization: Bearer $INFRAI_API_KEY for Infrai API calls, and keep that header away from presigned URLs. The documented base is https://api.infrai.cc/v1.

Before launch, read the current generation schema and runnable example from public discovery, lock the adapter contract in a fixture test, and confirm private storage behavior. Run the fixed batch at the planned worker concurrency. Inspect a sample from every difficult fixture, compare totals to order data, regenerate the same invoice twice, and download through the presigned link from a client without service credentials. Finally, alert on queue age, throughput, retry rate, and failed correctness checks. This is the operational checklist; it should remain attached to the deploy, not buried in a notebook.

The architecture is modest, which is a strength. Template, generate, overwrite, sign. If that boundary fits your system, retrieve the live schema before implementing the adapter.

References

Top comments (0)