Making a two-page invoice print cleanly
HTML that looks right on screen often prints badly: a table row cut in half at the bottom of a page, a total alone on the last page, a grey background that vanishes. Print CSS fixes each of these with one rule. Here is an invoice with 40 line items, taken from a messy first print to a clean PDF.
Start with the page itself. The tool writes an @page rule for you, such as @page { size: A4 portrait; margin: 15mm; }. A4 is 210 by 297 millimetres, so 15 mm margins leave a printable area 180 mm wide. At the CSS ratio of 96 pixels to the inch, 180 mm is about 680 pixels. That is the width your layout really has on paper, which is why a design that needs 900 pixels on screen gets squeezed or cut off in print. Give the invoice a max-width in mm or a width of 100% and it fits.
Next, the table. With 40 rows it runs onto a second page. Put the heading row inside a thead element, and most browsers repeat it at the top of page 2, so the reader still knows which column is the amount. Add tr { break-inside: avoid; } so a row with a long description is not split across the page break. Browsers treat break-inside on table rows as a request rather than a promise, so check the preview of the PDF in the print dialog.
Then the totals. A short totals block often lands alone at the top of the last page. Wrap the last few rows and the totals in one element with break-inside: avoid, and the browser moves them together. If you want the terms and conditions on a page of their own, give that section break-before: page. The sample in the tool uses exactly that rule to start its last paragraph on page 2.
Last, colour. By default, browsers drop background colours when printing to save ink, so a shaded heading row prints white. This tool adds print-color-adjust: exact to the page, which asks the browser to keep them. In Chrome, also turn off Headers and footers in the print dialog, or each page gets a date and a title in its margin.
Be clear about what this tool is. It is your browser’s print to PDF, with the page set up for you. It is not a pixel-perfect renderer: the PDF is laid out for paper, not for the preview’s width, and Chrome, Firefox and Safari can each break pages a little differently. Nothing is loaded from the network, so external images, stylesheets and web fonts must be inlined first. It cannot add a table of contents, bookmarks, page numbers or a password. For those you need a dedicated PDF engine.