Skip to content

Guide · Developer

Headers, Footers and Page Numbers in HTML to PDF

Add repeating headers, footers and Page X of Y numbers to HTML-to-PDF output with header templates or CSS @page margin boxes, with tested fixes.

Updated 11 min readSublimePDF Team

Invoices need "Page 2 of 4". Statements need the account number on every page. Reports need a running title that skips the cover. A Chromium-based renderer gives you two separate ways to print this page furniture:

  1. Header and footer templates. These are small HTML snippets passed to the renderer, options.headerTemplate and options.footerTemplate in the SublimePDF API, and Chromium prints them in the page margins.
  2. CSS @page margin boxes. These are rules such as @bottom-right { content: counter(page) } written in the document itself. Chrome added support in version 131.

This guide shows how to use each one and when to choose it. It also covers the failure modes we reproduced. We printed 17 fixtures with local headless Chrome 158 through the DevTools Protocol Page.printToPDF command, so the parameter names match Chromium's own, and checked the text, positions and colours in each PDF with pdfjs-dist. These are local Chrome results, not SublimePDF production output. Page breaks, table layout and fonts are covered in the print CSS guide.

Which approach to use

NeedHeader/footer templates@page margin boxes
Page X of YYes (pageNumber, totalPages)Yes (counter(page), counter(pages))
Different header on page 1No, same on every pageYes, with @page :first
Different header per sectionNoYes, with named pages
Rich HTML (logo, two columns)Yes, inline styles and data: imagesText and simple generated content only
Stored with the layoutNo, sent in options with each requestYes, part of the document's CSS, whether you send HTML or a saved template ID
Uses the document's CSSNo, styles are isolatedYes

For documents you generate repeatedly, margin boxes are usually the better default. The page furniture lives in the same CSS as the layout, whether your code sends that HTML on each call or you saved it as a template in the app, it can differ on the first page, and every request renders it the same way. Use header templates when you need a logo or a multi-column header, or when the same body HTML needs different furniture for different callers.

Chromium fills five classes in a template: date, title (the document's title element), url, pageNumber and totalPages. A footer with Page X of Y looks like this:

<div style="width:100%; padding:0 15mm; font:9px Arial, sans-serif; color:#555;
            display:flex; justify-content:space-between;">
  <span>Acme Ltd · Statement ACC-1042</span>
  <span>Page <span class="pageNumber"></span> of <span class="totalPages"></span></span>
</div>

Through the API, send it as a string in options.footerTemplate, with a bottom margin big enough to hold it. This complete Node.js 18+ script (save it as statement.mjs) renders a 90-row statement with a running header, a Page X of Y footer and a column header that repeats on every page. The rows are filled from data by the HTML's {{#each}} loop:

import { writeFile } from "node:fs/promises";
 
const apiBase = process.env.SUBLIMEPDF_API_BASE_URL ?? "https://api.sublimepdf.com/v1";
const apiKey = process.env.SUBLIMEPDF_API_KEY;
if (!apiKey) throw new Error("Set SUBLIMEPDF_API_KEY");
 
const html = `<!doctype html>
<html><head><meta charset="utf-8"><title>Statement {{account}}</title>
<style>
  body  { font: 10pt Arial, sans-serif; }
  table { width: 100%; border-collapse: collapse; }
  thead { display: table-header-group; }  /* repeat column headings */
  tr    { break-inside: avoid; }          /* never split a row */
  th, td { padding: 4px 6px; border-bottom: 1px solid #ddd; text-align: left; }
</style></head>
<body>
  <h1>Statement {{account}}</h1>
  <table>
    <thead><tr><th>Date</th><th>Description</th><th>Amount</th></tr></thead>
    <tbody>
      {{#each transactions}}<tr><td>{{date}}</td><td>{{description}}</td><td>{{amount}}</td></tr>{{/each}}
    </tbody>
  </table>
</body></html>`;
 
// Fictional data: 90 display-ready rows.
const transactions = Array.from({ length: 90 }, (_, i) => ({
  date: `2026-11-${String((i % 28) + 1).padStart(2, "0")}`,
  description: `Render batch ${i + 1}`,
  amount: `£${(12.5 + i).toFixed(2)}`,
}));
 
const headerTemplate = `<div style="width:100%;padding:0 15mm;font:9px Arial,sans-serif;color:#555">
  Acme Ltd (fictional) · Statement ACC-1042</div>`;
const footerTemplate = `<div style="width:100%;padding:0 15mm;font:9px Arial,sans-serif;color:#555;text-align:right">
  Page <span class="pageNumber"></span> of <span class="totalPages"></span></div>`;
 
const res = await fetch(`${apiBase}/html-to-pdf`, {
  method: "POST",
  headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
  body: JSON.stringify({
    html,
    data: { account: "ACC-1042", transactions },
    options: {
      format: "A4",
      margin: { top: "20mm", bottom: "20mm", left: "15mm", right: "15mm" },
      headerTemplate,
      footerTemplate,
    },
  }),
});
if (!res.ok) throw new Error(`SublimePDF ${res.status}: ${await res.text()}`);
await writeFile("statement.pdf", Buffer.from(await res.arrayBuffer()));
console.log("Saved statement.pdf");

If the statement is a template you saved in the app, send the same data and options to POST /templates/{id}/generate instead; the header and footer templates still travel in options.

In our fixture this printed "PG 1 OF 5" through "PG 5 OF 5" on a five-page document. The rules below come from what went wrong in the other fixtures.

Always set a font size

Chromium does not give template text a readable default size. A footer with no font-size came out at 0.75 pt (1 CSS pixel), which is invisible in print, while the body text was 12 pt. With font-size: 9px the same footer measured 6.75 pt. Set a size on the outer element of every template.

Reserve room with margins

Templates are drawn inside the page margin, and Chromium neither clips them nor moves the body out of the way:

  • With a 0 mm bottom margin, the footer still printed, but on top of the body text. The footer baseline sat 291.3 mm from the top of the page, and the last body line was at 292.4 mm.
  • A header six lines tall with a 10 mm top margin ran 15 mm down into the body area, overlapping the first three paragraphs.

Measure your header and set options.margin.top (or the @page margin) to its height plus a few millimetres. Chromium's own default margin is 1 cm, which is too small for most branded headers.

Templates do not see the document's CSS

A .brand rule in the document had no effect on <span class="brand"> inside the header. Playwright's documentation says the same thing: page styles are not visible inside templates, and script tags in templates are not run. Put styles inline, or in a style element inside the template string. That worked in our fixture, where a .own rule defined inside the footer template coloured its text.

Images: use data URIs

A remote image in a header (<img src="http://..."> pointing at our local test server) was not drawn, and Chrome never requested the file. The same image as a data:image/png;base64,... URI printed normally. Keep logos small, because the template is sent with every request.

Backgrounds need print-color-adjust

A footer with background: #12ab34 printed without its background, even with printBackground on. Adding -webkit-print-color-adjust: exact; print-color-adjust: exact; to the element brought it back.

Send both templates

When header and footer display is on and only a footer template is supplied, Chromium falls back to its default header. In our run that header was the print date and the document title ("22/11/2026, 22:49 HF-TITLE-MARK"). That is Chromium's behaviour when it is driven directly. The SublimePDF API avoids it: when you send only one of options.headerTemplate and options.footerTemplate, it sends an empty "<span></span>" for the other, so no default header or footer appears. Each template can be up to 64 KB. If you drive Chromium yourself, send "<span></span>" for the template you do not want.

Same on every page, including page 1

A header template printed on all five pages of the fixture, including page 1. There is no first-page option. If the cover must be clean, use margin boxes or render the cover separately and join the files with the API's POST /merge.

The date class uses the renderer's own locale and clock. If the date matters, such as an invoice date or a "generated at" stamp, put your own value into the HTML from your data.

CSS @page margin boxes

The Paged Media spec divides each page's margin into 16 margin boxes, such as @top-left, @top-center, @bottom-right and so on. Chrome supports them from version 131, together with the page counter and the pages counter, which holds the total page count.

@page {
  size: A4;
  margin: 20mm 18mm 22mm;
  @top-left     { content: "Weekly operations report"; font: 8pt Georgia, serif; color: #777; }
  @bottom-right { content: "Page " counter(page) " of " counter(pages); font: 8pt Georgia, serif; color: #777; }
}
@page :first {
  @top-left { content: none; }   /* clean cover */
}

In the fixtures:

  • @bottom-center with counter(page) and counter(pages) printed the correct "PG n OF 5" on all five pages, with no header template involved.
  • @page :first { @top-center { content: none; } } removed the running header from page 1 only. It printed on pages 2 to 5.
  • Named pages give each section its own header. With @page appendix { @top-left { content: "Appendix"; } } and page: appendix on the appendix wrapper, the body pages and appendix pages each carried their own label.

The sample report template uses this approach. Its page numbers are @bottom-right margin boxes, and an @page :first rule hides the organisation and period footer on page 1. We checked the published PDF: page 1's footer area contains only "1 / 2", and page 2's contains "2 / 2" plus "Fernhill Logistics (fictional) · 17–23 November 2026".

Report sample files

Rendered from this template and data with headless Chromium for documentation.

Numbering that skips the cover

@page :first { counter-reset: page 0; } made page 2 print as page 1. But counter(pages) still counted the cover, so a five-page document read "PG 1 OF 5" through "PG 4 OF 5". A counter-reset: page on an ordinary element had no effect on page numbers. If the cover must not be counted, you have two options. You can print only "Page X" without a total, or you can render the cover and body as separate PDFs and merge them, so each part numbers itself.

What margin boxes cannot do in Chromium

The Generated Content for Paged Media spec defines string-set, which copies a heading into a running header, and position: running(), which moves an element into a margin box. Neither worked in Chrome 158. In our string-set fixture the chapter title printed on 1 of 3 pages, only where the heading itself was. For per-chapter headers, use named pages with fixed text, as described above.

Do not mix both mechanisms

With margin boxes in the CSS and a footer template in the request, Chrome printed both on every page. Both sat in the bottom margin, so they collided. Pick one per template.

Long tables with headers, footers and page numbers

Statements and long invoices combine all of this, as in the statement.mjs script above. Three rules do the work: thead { display: table-header-group; } repeats the column headings, tr { break-inside: avoid; } keeps each row whole, and top and bottom margins of 20 mm leave room for the header and footer templates.

In our long-table fixture, a 90-row table over four pages printed the column header, the running header and correct page numbers on all four pages. The {{#each}} loop uses the template syntax described in the template variables guide. The table rules themselves are explained in the print CSS guide.

Troubleshooting

SymptomCause we reproducedFix
Footer missing or a tiny smudgeNo font-size in the template (0.75 pt)Set font-size on the outer element
Footer overlaps the last linesBottom margin 0 or too smallSet margin.bottom larger than the footer
Header covers the first paragraphHeader taller than margin.topIncrease margin.top
Date and title appear at the topOnly a footer template was sentSend headerTemplate: "<span></span>"
Brand colours ignored in the headerDocument CSS does not reach templatesInline styles or a style element in the template
Logo missingRemote image in the templateUse a data: URI
Header background missingPrint colour adjustmentprint-color-adjust: exact
Two footers on top of each otherMargin boxes plus footer templateUse only one mechanism
"Page 1 of 5" on a 4-page bodyCover counted in counter(pages)Drop the total or merge a separate cover

Run the fixtures

Every fixture's HTML and PDF is in /samples/fixtures/headers-footers/. Examples include the Page X of Y footer (PDF), the first-page-suppressed margin box and the long table. To repeat the suite with Chrome installed:

node scripts/research/headers-footers/run.mjs

Header and footer template HTML is sent in options with each request, as described in the API reference. Margin boxes belong in the document's own CSS, so every render prints the same page furniture, whether you send the HTML each time or save it as a template like the report template.

Sources

  1. Chrome DevTools Protocol: Page.printToPDF (parameter definitions as bundled in playwright-core types/protocol.d.ts) · accessed 23 November 2026
  2. Playwright: page.pdf() options (header and footer template notes) · accessed 23 November 2026
  3. Chrome for Developers: Add content to the margins of web pages when printed using CSS (30 October 2024) · accessed 23 November 2026
  4. CSS Paged Media Module Level 3 (W3C Working Draft, 14 September 2023) · accessed 23 November 2026
  5. CSS Generated Content for Paged Media Module (W3C Working Draft, 25 January 2024) · accessed 23 November 2026

Generate your first PDF with one API call.

Create an account, copy an API key and send HTML, or a template ID with JSON data, from your code or your agent.