PDF headers, footers and page numbers with CSS
Add headers, footers and "Page X of Y" numbers to generated PDFs with CSS @page margin boxes.
Last updated
Headers, footers and page numbers are CSS: you put them in the margin
boxes of an @page rule. counter(page) is the current page and
counter(pages) the total.
<style>
@page {
size: A4;
margin: 25mm 20mm;
@top-center { content: "ACME Ltd, monthly report"; font-size: 9pt; color: #666; }
@bottom-right { content: "Page " counter(page) " of " counter(pages); font-size: 9pt; color: #666; }
}
</style>
<h1>Report</h1>
<p>The margin boxes repeat on every page.</p>
Send this HTML to /v1/render as in the curl guide.
No header on the first page
@page :first {
@top-center { content: none; }
}
Chapter title in the header
string-set copies a heading's text, and string() prints it in a
margin box:
h2 { string-set: chapter content(); }
@page { @top-left { content: string(chapter); } }
Restart page numbers per chapter
Give each chapter a named page, then reset the counter on the first page
of each chapter. A counter-reset on the chapter element itself has no
effect on the page counter.
section.chapter { page: chapter; break-before: page; }
@page :nth(1 of chapter) { counter-reset: page 1; }
@page chapter { @bottom-center { content: "Page " counter(page); } }
counter(pages) still counts the whole document, so "Page X of Y" per
chapter is not possible.
FAQ
- How do I add page numbers to a PDF made from HTML?
- Put the page counters in an @page margin box: content: "Page " counter(page) " of " counter(pages). The renderer fills in both numbers.
- Why is my header cut off?
- Margin boxes draw inside the page margin. With a top margin of 0, the header is clipped at the page edge. Give @page a margin large enough for the text.