rustedf.cloud
Menu

Page numbers, headers and footers in a PDF with HTML and CSS

Published 2 min read

On screen, a page has no bottom. A PDF does: every sheet needs a page number, and long documents usually want a running title or a “Confidential” note on each page. In CSS this is done with the @page rule and its margin boxes, and the rustedf.cloud renderer supports them.

Page X of Y

@page {
size: A4;
margin: 20mm;
@bottom-center { content: "Page " counter(page) " of " counter(pages); }
}
  • size sets the paper (A4, A4 landscape, or a size in lengths) and margin the space around the content.
  • @bottom-center is a margin box: a slot in the margin of every page. Its content is text, joined with counter(page) for the current page and counter(pages) for the total.

You do not count pages yourself. The total is known once the whole document has been laid out, and the counters are filled in for you.

Margin boxes exist on the top and the bottom edge, each with a left, a center and a right slot.

@page {
size: A4;
margin: 24mm 20mm;
@top-left { content: "Acme Corp"; }
@top-center { content: "Quarterly report"; }
@top-right { content: counter(page) " / " counter(pages); }
@bottom-left { content: "Confidential"; }
@bottom-right { content: "Printed " counter(page); }
}

Leave the margin large enough for what you put in it. A margin of a few millimetres has no room for a header.

What a margin box can hold

The margin boxes take text and the two page counters. That covers the common cases: page numbers, a document title, a company name, a legal note.

For something richer on every page, use what else repeats:

  • the header row of a table, which the renderer repeats on every page the table spans, so a column header or a short label travels with the data;
  • content in the body, for what only needs to appear once, such as a logo on the first page.

Rules inside @media print apply to the PDF. Put the page furniture there if the same stylesheet is also used on screen, so the browser view stays clean.

Check it

Render a document long enough to span two pages and look at the result. The X-Pages header of a render, and the pages value of POST /v1/validate, tell you the page count without opening the file. If a margin box has no effect, validate the document: anything the renderer did not support is listed.

Read more in Supported HTML and CSS and Validating a document.

← All posts