HTML to PDF API: Generate Invoices and Reports From Your App

Almost every app ends up generating PDFs: invoices, receipts, order confirmations, monthly reports, certificates. The easiest way to design them is the way you already design everything else, in HTML and CSS. The hard part is turning that HTML into a PDF on a server. This guide shows the one-request version with the PrivConvert file conversion API, and the template details that decide whether the PDF comes out right.

The usual options, and why teams move off them

  • Old HTML-to-PDF command line tools. Many are unmaintained and render with an outdated engine, so modern CSS such as flexbox and grid breaks. One of the most popular is now archived (see what to use instead of wkhtmltopdf).
  • Running a headless browser yourself. It produces good PDFs, but you now operate a large browser install in your containers: memory spikes, stuck processes, font packages and security updates every few weeks.
  • A conversion API. You send the HTML, you get the PDF. The rendering engine is someone else's problem to scale and patch.

Step 1: a template that renders the same everywhere

Write the invoice as a normal HTML page. Keep the CSS in a <style> tag, embed the logo as a data URI, and mark where pages may and may not break:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
  body { font-family: Arial, Helvetica, sans-serif; color: #222; margin: 0; }
  h1 { color: #c33; margin-bottom: 4px; }
  table { width: 100%; border-collapse: collapse; margin-top: 24px; }
  th, td { padding: 8px; border-bottom: 1px solid #ddd; text-align: left; }
  tr { break-inside: avoid; }
  .total { text-align: right; font-weight: bold; margin-top: 16px; }
  .terms { break-before: page; }
</style>
</head>
<body>
  <img src="data:image/png;base64,iVBORw0KGgo..." width="120" alt="Acme">
  <h1>Invoice {{ number }}</h1>
  <p>{{ customer.name }}<br>{{ customer.address }}</p>
  <table>
    <tr><th>Item</th><th>Qty</th><th>Amount</th></tr>
    {% for line in lines %}
    <tr><td>{{ line.item }}</td><td>{{ line.qty }}</td><td>{{ line.amount }}</td></tr>
    {% endfor %}
  </table>
  <p class="total">Total: {{ total }}</p>
  <section class="terms">Payment terms ...</section>
</body>
</html>

Two CSS properties do most of the work for documents that run over several pages: break-inside: avoid on table rows keeps a line item from being split across two pages, and break-before: page starts a section (terms, appendix) on a fresh page.

Step 2: render it and convert

Fill the template with your usual engine and send the result. New accounts can start a free trial of 25 conversions without a card.

Python

from jinja2 import Template
from privconvert import PrivConvert

pc = PrivConvert()  # reads PRIVCONVERT_API_KEY
html = Template(open("invoice.html").read()).render(invoice)

result = pc.convert("html-to-pdf", html.encode(), filename="invoice.html")
result.save(f"invoice-{invoice['number']}.pdf")

Node.js

import { PrivConvert } from "privconvert";

const pc = new PrivConvert(); // reads PRIVCONVERT_API_KEY
const html = renderInvoice(invoice); // your template engine

const result = await pc.convert("html-to-pdf", Buffer.from(html), {
  filename: "invoice.html",
});
await result.save(`invoice-${invoice.number}.pdf`);

PHP and Laravel

use PrivConvert\PrivConvert;
use PrivConvert\File;

$pc = new PrivConvert();
$html = view('invoices.pdf', ['invoice' => $invoice])->render(); // Blade, Twig, ...

$pdf = $pc->convert('html-to-pdf', File::fromString($html, 'invoice.html'));
$pdf->save(storage_path("invoices/{$invoice->number}.pdf"));

Any language

It is one multipart request with the HTML in a field called file. The PDF is the response body:

curl -X POST https://privconvert.com/api/convert/html-to-pdf \
  -H "Authorization: Bearer $PRIVCONVERT_API_KEY" \
  -F "[email protected]" \
  -o invoice.pdf

In our own measurements a simple one-page invoice takes about 1.4 seconds to render on our side, plus the time to upload the HTML and download the PDF.

Images and fonts must be inside the document

The renderer has no network access. That is a deliberate security choice: a template that loads remote resources can be abused to make the server fetch internal addresses, a classic weakness of PDF services. The practical consequence is simple. Anything the page needs must be in the HTML:

# Python: turn a logo file into a data URI for the template
import base64
logo = "data:image/png;base64," + base64.b64encode(open("logo.png", "rb").read()).decode()

/* CSS: embed a web font the same way */
@font-face {
  font-family: "Brand";
  src: url("data:font/woff2;base64,d09GMgABAAAA...") format("woff2");
}

A link to a stylesheet or an image on your CDN will not load: the styles are simply missing, and an image shows up as a small broken-image icon. If something is missing from your PDF, this is almost always why.

Page size, margins and backgrounds

Pages are A4 with 12 mm top and bottom and 10 mm side margins, and background colours and images are printed, so coloured table headers and shaded totals come out as designed. If you print for US Letter, keep the content inside a width that fits both (about 190 mm) and the same template works for either paper.

JavaScript, charts and dynamic content

Scripts run before printing, so a report can draw its charts with an inline charting library. Rendering waits until the page goes idle, within a time limit, so avoid timers and anything that polls. Better still, compute values in your backend and send finished HTML: it renders faster and the output is predictable.

Many documents at once

For a month-end run, send up to 20 HTML files in one batch request and get a ZIP of PDFs back, or submit each one as an async job and collect the results by webhook. Converting thousands of files covers large runs, and which API errors to retry covers what to do when you hit a limit.

Invoices are personal data

An invoice carries names, addresses, purchases and amounts. With PrivConvert the HTML is rendered in memory and the PDF goes straight back in the response: nothing is written to disk and nothing is kept, so there is no copy to delete or to leak. Every PDF we return also has the rendering engine's name and the conversion timestamps removed from its metadata. More on that approach in a file conversion API that does not store files.

FAQ

Can the HTML load images, CSS or fonts from a URL?

No. The page is rendered with network access switched off, so nothing on the internet (or on your network) can be fetched while your document is open. Put the CSS in a style tag and embed images and fonts as data URIs. This also means a template can never be tricked into making requests on your behalf.

What page size and margins are used?

A4 with 12 mm top and bottom and 10 mm side margins, with background colours and images printed. Design for that page in your CSS and use break-before, break-after and break-inside to control where pages end.

Does JavaScript run?

Yes. Scripts in the document run before the PDF is printed, so charts drawn by an inline library appear in the output. Rendering waits until the page is idle, with a time limit, so keep scripts short and self-contained.

Can I convert a live URL instead of HTML?

Not through the API. Rendering pages from arbitrary URLs is how PDF services get abused to reach internal networks, so the API accepts the HTML document itself. If you need to, fetch the page yourself and send the HTML, with its styles and images inlined.

Is the invoice stored anywhere?

No. The HTML is rendered in memory and the PDF is streamed back in the same response. Nothing is written to disk and no copy is kept, which matters for documents full of customer names, addresses and amounts.

Developer resources:
Official SDKs Error reference Plans & free trial HTML to PDF online