Quotes, invoices and contracts as PDF: how to build document generation into your software
Document generation looks like one job and is really three decisions: what you write the template in, which engine renders it, and where the finished file freezes. Putting a "Download PDF" button on a quote screen genuinely is a day of work. Producing three thousand invoices on the last day of the month, reproducing one of them two years later with the same layout, and rendering a customer's free-text note on your server without opening a door into your internal network are not the same job. The button ships in a day. The other three need decisions that most teams never make on purpose, and then discover.
Browser, layout engine, or PDF library?
There are three families of tools, and each is good at something different.
A headless browser (Chromium driven by Puppeteer or Playwright) is the familiar option. Your team already writes HTML and CSS, charting libraries work, and the on-screen preview and the printed file come from the same code. The cost is a browser process per render, with the memory that implies.
Print layout engines are the second family: WeasyPrint, Prince, Vivliostyle. These actually implement CSS Paged Media. WeasyPrint's feature list spells it out: @page with margin boxes, named strings via string-set for running headers, target-counter for page references in a table of contents, footnotes through float: footnote, PDF/A and PDF/UA output, and bookmarks generated from h1 to h6 (WeasyPrint API reference). In exchange they run no JavaScript, so a chart has to arrive as ready-made SVG.
The third family writes PDF directly: pdf-lib, PDFKit, Apache PDFBox, ReportLab. You place text and lines by coordinate. That is the right tool for barcode labels, fixed official forms, and filling fields in an existing PDF. Building a multi-page document with variable-length tables this way means writing your own pagination.
A rough rule for choosing: if the document is also shown on screen and marketing will have opinions about its design, use a browser. For contracts, catalogues and long reports where page discipline matters, use a layout engine. For fixed-format labels and forms, use a library.
Two warnings. wkhtmltopdf was the default answer for years, but its repository was archived on 2 January 2023 and is read-only (wkhtmltopdf repository). It is not where a new project should start. The second is licensing: the community edition of iText ships under the AGPL, and using it inside a closed-source product requires a commercial licence. Settle questions like this before the first release, since open source licence compliance is one of the most expensive things to fix after the fact.
Screen layout and page layout are different problems
The first surprise arrives here: HTML that looks perfect in the browser splits a table straight down the middle in the PDF. A screen is one infinitely long surface. Paper is not.
Three CSS properties solve half the problem. @page sets paper size and margins. break-inside: avoid keeps a card, a signature block or a line item from being cut across two pages. And in long tables, repeating the thead on every page is the difference between a readable document and a stack of unlabelled columns two pages in.
On the Puppeteer side, three settings get forgotten over and over. printBackground is off by default, so background colours and fills do not print. Unless preferCSSPageSize is enabled, the @page size in your CSS is ignored and content is scaled to the paper. Headers and footers come from displayHeaderFooter plus headerTemplate and footerTemplate, where the classes date, title, url, pageNumber and totalPages are filled in with the matching values (Puppeteer PDFOptions). Two traps come with them: those templates do not inherit the page's CSS, so styles must be inline, and if you leave no margin they simply do not appear.
What Chromium will not do is a running header fed by the content. "Print the current section name at the top of every page" is a string-set job, and that stays in layout-engine territory. If that line is in the requirements, the engine choice changes on day one, because moving later means rewriting the template.
Fonts are where documents fail quietly
Which fonts are installed on your render server? Most teams ask that question for the first time when a customer reports that the invoice shows boxes where the accented characters should be. Container images ship lean, and their font list is nothing like the one on a developer laptop. A missing glyph sometimes becomes a box and sometimes falls back silently to another typeface. The silent case is worse, because the output is not broken, only different, and nobody notices.
Three rules close this. Install fonts into the image explicitly and pin the version instead of trusting system defaults. If you use web fonts, do not trigger the render before font loading finishes, or the same template will break lines differently between two runs. And if the typeface is commercial, check that the licence permits embedding, which is usually a separate clause.
Number and date formats belong in the same bucket. Decimal separators, thousands separators and the position of the currency symbol change by locale, and so does the order of day and month. Solve this in the data layer rather than formatting by hand in the template: the decisions you made about multi-currency handling and dates and time zones show up directly in the document.
Is a document data, or is it a file?
The answer to that question drives the rest of the architecture. A quote is still a mutable record, so regenerating it on every open is fine. An invoice is not. A signed contract certainly is not.
Here is the problem. Take today's data, render it with today's template, then regenerate the same document two years later with the same code, and you will not get the same file. The template has changed, the logo was refreshed, a tax rate was updated, the customer's address was corrected, the font shipped a new version. The document the customer received and the document your system produces today disagree, and the first person to notice that is usually an accountant.
For documents that must not change, store three things together: the generated file itself (in object storage, with its hash), a snapshot of the input that produced it (plain JSON is enough), and the version number of the template used. Printing the template version in a corner of the document turns "why does this output look like that" into a five-minute answer years later. Decide the retention period up front as part of your retention and archiving policy, because generated documents are one of the fastest growing line items in object storage.
Generate in a queue, not inside the request
Rendering a single quote when the user clicks is fine. Producing three thousand invoices at month end cannot use the same path.
Starting a browser is expensive, it eats memory, and it is the first thing to exhaust a server as concurrency climbs. The pattern is well established: hand the document to a background job, keep browser processes in a pool, put a timeout on each job, and do not render the same document twice when it is requested twice. For bulk runs, a progress indicator and a notification on completion stop users from refreshing the page and triggering the work three times over.
There is also a numbering trap. Assigning the invoice number at render time means skipping a number on every failed attempt. Issue the number as part of the accounting transaction and let the document be a rendering of that number. Make retries idempotent: a second request with the same job id should return the existing file, not produce a new one.
Month end is a predictable spike, which means it is measurable. Measuring once with a load test how long three thousand documents actually take is cheaper than finding out on the last day of the month.
For teams who would rather not run this themselves, a ready-made service like Gotenberg is a reasonable middle path. It is a Docker-based API that puts Chromium and LibreOffice in one container, converts HTML and office files to PDF, merges, stamps and signs them, and offers validation and remediation for PDF/A and Factur-X conformance (Gotenberg).
You are rendering user-supplied content on your server
This is the security half of the subject, and in most teams it is the half nobody has discussed. A PDF generator that renders HTML server side hands an attacker a tool that makes requests from inside your network the moment outside text reaches the template.
The mechanics are simple. If HTML can be injected into a quote description or a customer name, an embedded iframe fetches an internal address and the response appears inside the generated PDF. If iframes are blocked, fetch or XMLHttpRequest is tried next. If the file:// scheme is allowed, server files get printed into the document. In cloud environments the real target is the metadata endpoint, because the response can carry temporary credentials (Intigriti, SSRF in PDF generators). Even a blind injection lets an attacker map the internal network through tags like img, link and meta refresh.
No single setting defends against this. You need four layers. Treat user input as text rather than HTML, and watch for the shortcuts that disable a template engine's automatic escaping. Run the renderer in its own container on a network where outbound traffic is denied by default and only the addresses you actually need are opened. Turn off local file access and any protocol you do not use, which WeasyPrint supports through allowed_protocols along with an option to refuse redirects. Finally, keep no secrets on the render host and cut its access to the cloud metadata service, which is the most commonly skipped item on the shared responsibility side of a cloud setup.
Once those are in place, pull the generator into your API security scope. Like any component that accepts outside content and can make network requests, it belongs in your testing coverage.
Who can reach the file?
Once generated, the document sits somewhere and is usually shared through a link. Two mistakes dominate here.
The first is treating an unguessable URL as authorisation. A sequential address like /invoices/1042.pdf is all it takes for one customer to read another company's invoice. The download request has to check record ownership too, so your authorisation model does not end at the UI layer.
The second is parking files in a public object storage bucket. The right pattern is a signed, expiring link: the bucket stays private, and the application mints a short-lived download URL after it has verified permission. Keep expiry short for links sent by email, because that link travels inside forwarded messages for months. Recording who downloaded what in your audit log is often the only evidence you have when a document is later disputed.
Archive format, signatures, and structured invoices
For documents kept long term, PDF is not enough and PDF/A is the target. The difference is that PDF/A requires embedded fonts and forbids external dependencies, so the file still looks the same in ten years. Part three of the standard permits embedded files, which is what hybrid e-invoice formats are built on: Factur-X and ZUGFeRD carry a human-readable PDF and machine-readable XML in one file. Do not assume your output conforms, verify it. veraPDF is an open source validator that covers every PDF/A part and conformance level plus PDF/UA parts 1 and 2 (veraPDF).
Accessibility runs through the same place. A document generated without tagging collapses into unordered text in a screen reader. If you produce documents for public sector or enterprise customers, this can appear in the tender requirements, since WCAG conformance is not only about web pages.
Signing is its own topic. The standard for electronic signatures in PDF is PAdES, defined in the ETSI EN 319 142 series, whose second part covers the PAdES-E-LTV level for long-term validation (ETSI EN 319 142-2). The point is that certificates, revocation data and a timestamp are embedded in the file so the signature can still be verified years later. Pasting an image of a signature is not that.
One distinction worth making early in markets with mandatory e-invoicing: the legal record is the structured XML, and the PDF is its human-readable rendering. In Türkiye, e-Fatura and e-Arşiv documents are issued in the UBL-TR format, so a PDF your own system produces does not stand in for the document that goes through the integrator. ERP and e-commerce integrations that confuse the two get stuck at reconciliation.
You cannot test this by comparing bytes
Generate a PDF twice from identical input and the two files differ. Creation timestamps and object ids change inside. So a test that asserts "output file equals expected file" fails from day one, and the team switches it off.
What works instead: first increase determinism by fixing generation time and ids in the test environment. Then compare rendered pages rather than bytes, by converting pages to images and diffing them against references with a small tolerance. As a cheap extra check, assert the page count and verify that key fields survive text extraction, such as invoice number, total and tax line.
Choose the reference set deliberately. Six scenarios is a reasonable minimum: a very long company name, a sixty-line order, a zero-value line, a refund or negative amount, text heavy with non-ASCII characters, and a table that lands exactly on a page boundary. Run these in the same container image you use in production, because a different font set breaks the layout differently. The gap between staging and production reaches all the way down to typefaces in document generation.
A two-week first step
Four pieces of work are enough. List the documents you need to produce and answer three questions for each: can it change, how many pages can it reach, does it contain text from outside. Choose the engine from that table rather than the other way round. For immutable documents, build a storage pattern that keeps the file, the input snapshot and the template version together. Move rendering into its own container with restricted outbound traffic, and pin down with a test that user input is not treated as HTML. Then build the six-scenario reference set and wire the visual comparison into CI.
If you would like a second pair of eyes on your current document flow, to work out which documents should freeze and which can be regenerated on demand, an hour is usually enough to settle the engine choice and the storage pattern.
Need help with this topic?