ScreenshotNeo

BlogHow-to

How to Add Chapter and Section Page Numbers With wkhtmltopdf

Add document-wide page numbers and chapter labels with wkhtmltopdf, then learn the reliable multi-render workflow for numbering that restarts at each chapter.

By the ScreenshotNeo team30 September 20268 min read

How to Add Chapter and Section Page Numbers With wkhtmltopdf

wkhtmltopdf can put the current page, total pages, section name, and subsection name in a PDF header or footer. For a document-wide footer, use [page] and [topage]; for heading context, use [section] and [subsection]. It does not automatically restart numbering at each chapter. To get chapter-local page 1s, render each chapter separately and merge the PDFs. This guide shows both approaches, styled HTML headers and footers, offsets, outlines, a table of contents, and common fixes.

1. Add document-wide page numbers

Install wkhtmltopdf using the package or build appropriate for your operating system, then run this command from the directory containing input.html:

wkhtmltopdf \
  --margin-bottom 18mm \
  --footer-center "Page [page] of [topage]" \
  input.html output.pdf

[page] is the current page and [topage] is the last page number, which serves as the document total. The margin reserves space for the footer. Without adequate space, body content and the footer can overlap or be clipped. Increase the bottom margin if the footer is tall, and use --footer-spacing to adjust the gap.

For a header instead, use --header-right and reserve space with --margin-top:

wkhtmltopdf \
  --margin-top 16mm \
  --header-right "Page [page] of [topage]" \
  input.html output.pdf

The manual documents these substitutions for header and footer strings. They are placeholders interpreted during PDF generation; they are not JavaScript variables in the source HTML.

2. Show chapter and section names

Use [section] and [subsection] in the header or footer to include the current section and subsection labels. A typical book-style header places the chapter on the left and the section on the right:

wkhtmltopdf \
  --margin-top 16mm \
  --margin-bottom 18mm \
  --header-left "[section]" \
  --header-right "[subsection]" \
  --footer-center "Page [page] of [topage]" \
  book.html book.pdf

Use semantic headings in the HTML so section context and document structure are meaningful. For example:

<h1>Chapter 1: Installation</h1>
<h2>Linux packages</h2>
<p>...</p>
<h2>Building from source</h2>
<p>...</p>
<h1>Chapter 2: Configuration</h1>
<h2>Page layout</h2>
<p>...</p>

The substitutions expose heading labels and counters, but they do not define a numbering scheme that resets whenever an <h1> or <h2> appears. A single continuous render has document-wide page numbering.

Plain command-line strings are sufficient for a short label. For custom CSS, aligned elements, borders, or more involved layout, supply a separate file with --header-html or --footer-html. wkhtmltopdf passes values to that file as query parameters. The documented approach reads those parameters and fills elements with classes such as page, topage, section, and subsection.

Save the following as header.html:

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <style>
    body { margin: 0; font: 9pt Arial, sans-serif; }
    .row {
      display: flex;
      justify-content: space-between;
      border-bottom: 1px solid #999;
      padding-bottom: 3px;
    }
  </style>
  <script>
    function subst() {
      const params = new URLSearchParams(location.search);
      for (const name of ["page", "topage", "section", "subsection"]) {
        document.querySelectorAll("." + name).forEach(el => {
          el.textContent = params.get(name) || "";
        });
      }
    }
  </script>
</head>
<body onload="subst()">
  <div class="row">
    <span class="section"></span>
    <span class="subsection"></span>
    <span>Page <span class="page"></span>
      of <span class="topage"></span></span>
  </div>
</body>
</html>

Then render with enough top margin and optional spacing:

wkhtmltopdf \
  --margin-top 20mm \
  --header-spacing 4 \
  --header-html header.html \
  --footer-center "Page [page] of [topage]" \
  --margin-bottom 18mm \
  book.html book.pdf

The template can also use documented values including title, doctitle, sitepage, and sitepages. Header and footer HTML runs in the PDF renderer, so keep the file available to the process and ensure scripts execute before its contents are laid out. Do not rely on externally hosted stylesheets or scripts unless the renderer can reach them.

4. Restart page numbering at each chapter

There is no documented automatic per-heading counter reset in wkhtmltopdf. If each chapter must say “Page 1 of N,” render each chapter as its own PDF and merge the results. Since [page] and [topage] are calculated for each render, they become chapter-local.

Render each chapter separately so its page count starts at one, then merge the PDFs.
Render each chapter separately so its page count starts at one, then merge the PDFs.
  1. Split the source into chapter HTML files. Include the styles and assets each file needs, and keep the chapter heading in its markup.
  2. Render each chapter independently. Pass a chapter-specific label in the header or footer.
  3. Merge the generated PDFs with a PDF merging tool available in your environment.
  4. Check page totals and transitions in the merged output, especially where a chapter starts or ends.
wkhtmltopdf \
  --margin-bottom 18mm \
  --footer-center "Chapter 2 — Page [page] of [topage]" \
  chapter-2.html chapter-2.pdf

wkhtmltopdf \
  --margin-bottom 18mm \
  --footer-center "Chapter 3 — Page [page] of [topage]" \
  chapter-3.html chapter-3.pdf

# Merge chapter-2.pdf and chapter-3.pdf with your chosen PDF-merging tool.

The merge command depends on the PDF tool you choose; wkhtmltopdf itself is responsible here for rendering each chapter. This workflow is an inference from the documented counter scope, not a built-in automatic reset feature. If you need “Chapter 2 — Section 3 — Page 1 of 7,” include the chapter and section labels in the chapter render’s header and let that render’s local counters supply page and total.

When numbering should stay continuous

If a chapter is rendered separately but the page number should continue from earlier pages, use the library’s pageOffset setting. It adds a fixed number to page numbers in headers, footers, and the table of contents. It does not reset a counter at a heading, and it does not replace chapter-local rendering when every chapter must begin at page 1.

5. Configure margins, spacing, outlines, and the table of contents

Need Option or input What it does
Room above body --margin-top Reserves space for a header.
Room below body --margin-bottom Reserves space for a footer.
Header gap --header-spacing Sets spacing between header and page content.
Footer gap --footer-spacing Sets spacing between footer and page content.
Bookmarks --outline Enables a PDF outline.
Outline nesting --outline-depth Limits how many heading levels appear in the outline.
TOC toc object Builds a table of contents from heading tags.
Inspect outline --dump-outline Writes the generated outline XML.
Customize TOC --xsl-style-sheet Applies an XSL stylesheet to the TOC transformation.

Use <h1> for chapters and <h2> for sections to express hierarchy. Then enable the outline and choose an appropriate depth:

Margins and spacing keep page headers and footers clear of the document content.
Margins and spacing keep page headers and footers clear of the document content.
wkhtmltopdf \
  --outline \
  --outline-depth 2 \
  --margin-top 16mm \
  --header-left "[section]" \
  --footer-center "Page [page] of [topage]" \
  book.html book.pdf

For a generated TOC, add a toc object in the invocation as described in the project documentation, and use --xsl-style-sheet if its default presentation needs customization. A TOC and outline are separate PDF features: the outline supplies bookmarks, while the TOC is a rendered page or set of pages in the document.

6. Troubleshoot common pagination problems

Symptom Likely cause Fix
Footer is clipped or overlaps text Bottom margin is too small, or footer spacing pushes it beyond the page. Increase --margin-bottom; adjust --footer-spacing conservatively.
Header content is missing Insufficient top margin, inaccessible template/assets, or template JavaScript did not populate elements. Increase --margin-top, confirm the file path is readable, and inspect the template’s query parameter names and load handler.
[section] is blank or unexpected The source heading structure does not provide the expected section context. Use semantic heading tags and confirm the heading labels; test a minimal input with one chapter and section.
Every chapter continues the same count The entire book was rendered as one document. Render separate chapter inputs and merge, or use a fixed pageOffset only when continuous numbering is desired.
Total count looks wrong in a header template The template reads a different key, or the displayed value is not the document-level counter expected. Use the documented topage query parameter and compare with the plain-string footer output.
Outline or TOC is empty Headings may not use semantic heading elements, or outline/TOC options were omitted. Use h1/h2 hierarchy and enable the relevant outline or TOC configuration.
Long chapter starts unexpectedly on a new page Page breaks may be present in HTML or CSS. Inspect print styles and chapter markup; keep intentional chapter breaks, but remove unintended forced breaks.

7. Reliability, performance, and cost considerations

A one-pass render is simpler and avoids an additional merge stage. Chapter-by-chapter rendering adds process launches, intermediate files, and a merge operation, but it gives each chapter an independent page count. For repeatable output, keep chapter source, styles, fonts, and image assets available to the rendering process, use consistent page dimensions and margins for every chapter, and inspect the merged PDF at chapter boundaries.

Page totals are known only once a render has laid out its content, which is why wkhtmltopdf supplies substitutions during generation. Changes in text, fonts, images, or layout can shift pagination and change totals. If a template uses JavaScript, make sure it reads the documented query parameters and fills its elements reliably.

Cost depends on how wkhtmltopdf is installed and operated in your environment; the pagination options themselves do not define a service price. Factor in compute, storage for intermediate PDFs, and the operational work of merging when choosing chapter-local numbering. No performance benchmark is implied here: measure your own book size, assets, and rendering environment if throughput matters.

8. Or skip the browser setup

If your task also needs website screenshots or PDF captures, ScreenshotNeo is a website screenshot API and MCP server from Yorker Media. For a PDF capture, see the ScreenshotNeo API documentation and use its PDF options. A one-call image capture looks like this:

curl -G "https://api.screenshotneo.com/v1/shot" \
  -d access_key=YOUR_API_KEY \
  --data-urlencode url=https://stripe.com \
  -o shot.webp
import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({
  access_key: 'YOUR_API_KEY',
  url: 'https://stripe.com'
});
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo removes cookie banners, newsletter popups, and chat widgets before capture. Bot checks, blank pages, and failed loads are never billed, and response headers say what happened. Its MCP server lets AI agents take screenshots. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 shots. It is a website capture service, so use wkhtmltopdf for the chapter pagination workflow described above.

Sign up free for 1,000 screenshots a month, with no card.

9. FAQ

Can I use site-level page counters?

Yes. Header/footer substitutions include [sitepage] and [sitepages] for site-level counters. Use them when the multi-object rendering model fits your document.

Does pageOffset restart each chapter?

No. It adds a fixed offset to displayed page numbers. It is useful for a known continuous starting number, not an automatic reset at each heading.

Can the header show the document title too?

HTML header/footer templates can populate documented values including title and doctitle, in addition to page and section fields.

Should chapter-local page totals include the cover or TOC?

That is a document-design choice. Render those pages as their own object or include them with a chapter, depending on which pages should count toward that chapter’s [topage].

Primary documentation