May 11, 2026

wkhtmltopdf @page CSS Guide: size, margin, and Layout

wkhtmltopdfCSSPDF generationtutorial

With wkhtmltopdf, @page { size: A4; margin: 0; } does not always produce the margins you expect. This guide shows how to set paper size, margins, and page numbers with documented CLI flags instead of relying on CSS alone.

If you've already decided to migrate, skip to the migration section — the workarounds here will buy time, but the underlying limitations are architectural.

Why wkhtmltopdf Handles @page Differently

wkhtmltopdf uses Qt WebKit. Rather than guessing how each @page declaration is supported, use the officially documented CLI flags for page size, margins, headers, and footers.

The practical consequence: do not rely on @page alone for page layout. Split declarations between the stylesheet and CLI flags.

@page Properties: Choosing CSS or CLI

Setting Recommended approach in this guide Notes
A4 --page-size A4 Do not depend on CSS size alone
Landscape --orientation Landscape Combine with --page-size
Margins --margin-top/right/bottom/left Left and right default to 10mm
Headers --header-html, --header-left, etc. Check local-file access for HTML files
Page numbers --footer-right "[page] / [topage]" Use CLI substitutions instead of CSS counters
Print media --print-media-type Screen media is the default

Summary: Use CLI flags for margins and dedicated options for headers and footers. Set --page-size explicitly instead of relying on differences in @page size support.

Setting Page Size

A4 (the common case)

/* Do not rely on CSS alone; also set the CLI flag below */
@page {
  size: A4;
}

CLI flag (reliable):

wkhtmltopdf --page-size A4 input.html output.pdf

When combining CSS and CLI settings, set the intended paper size explicitly with the CLI and verify the output.

Custom size

# 210mm x 297mm (A4 exact)
wkhtmltopdf --page-width 210mm --page-height 297mm input.html output.pdf

# Letter (US)
wkhtmltopdf --page-size Letter input.html output.pdf

Landscape

/* Do not rely on CSS alone; use the CLI flags below */
@page { size: A4 landscape; }
# Reliable
wkhtmltopdf --orientation Landscape --page-size A4 input.html output.pdf

Setting Margins

Do not rely on @page alone for margins; set all four CLI flags. The official documentation specifies 10mm defaults for the left and right margins.

Zero margins

wkhtmltopdf \
  --margin-top 0 \
  --margin-right 0 \
  --margin-bottom 0 \
  --margin-left 0 \
  input.html output.pdf

Standard document margins

wkhtmltopdf \
  --margin-top 20mm \
  --margin-right 15mm \
  --margin-bottom 20mm \
  --margin-left 15mm \
  input.html output.pdf

Extra bottom margin for footer

If you're using a footer, add extra bottom margin so content doesn't overlap:

wkhtmltopdf \
  --margin-bottom 25mm \
  --footer-html footer.html \
  --enable-local-file-access \
  --footer-spacing 5 \
  input.html output.pdf

Page Numbers

wkhtmltopdf provides page numbers through CLI substitution variables, not CSS counters.

Simple page number in footer

wkhtmltopdf \
  --footer-right "Page [page] of [topage]" \
  --footer-font-size 9 \
  input.html output.pdf

Available variables: [page], [topage], [date], [time], [title], [doctitle], [sitepage], [sitepages].

HTML footer with page numbers

For styled footers, use a separate HTML file with JavaScript:

<!-- footer.html -->
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <style>
    body {
      margin: 0;
      padding: 4mm 15mm;
      font-family: 'Helvetica Neue', sans-serif;
      font-size: 8pt;
      color: #6b7280;
    }
    .footer-inner {
      display: flex;
      justify-content: space-between;
      border-top: 1px solid #e5e7eb;
      padding-top: 3mm;
    }
  </style>
</head>
<body>
  <div class="footer-inner">
    <span>Confidential</span>
    <span id="page-num"></span>
  </div>
  <script>
    // wkhtmltopdf injects these variables into the footer URL
    var vars = {};
    var parts = window.location.search.substr(1).split('&');
    for (var i = 0; i < parts.length; i++) {
      var p = parts[i].split('=', 2);
      if (p.length == 2) vars[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
    }
    document.getElementById('page-num').textContent =
      'Page ' + (vars['page'] || '') + ' of ' + (vars['topage'] || '');
  </script>
</body>
</html>
wkhtmltopdf \
  --footer-html footer.html \
  --enable-local-file-access \
  --margin-bottom 20mm \
  --footer-spacing 3 \
  input.html output.pdf

JavaScript is enabled by default. Use --javascript-delay to adjust the wait before rendering. These local-footer examples also include --enable-local-file-access:

wkhtmltopdf \
  --enable-javascript \
  --javascript-delay 200 \
  --footer-html footer.html \
  --enable-local-file-access \
  input.html output.pdf

Headers

Headers work the same way as footers:

wkhtmltopdf \
  --header-html header.html \
  --enable-local-file-access \
  --margin-top 25mm \
  --header-spacing 3 \
  input.html output.pdf

Or use the simple text options:

wkhtmltopdf \
  --header-left "[title]" \
  --header-right "[date]" \
  --header-line \
  --header-font-size 9 \
  input.html output.pdf

@page and Element Page-Break CSS

Set paper properties explicitly with CLI flags. For element page breaks, you can include both legacy and modern declarations, then verify output from your version.

@page {
  size: A4; /* Also set --page-size A4 */
}

/* Page break on an element (outside @page) */
.page-break {
  page-break-before: always;
  break-before: page;
}

/* Prevent breaks inside an element */
.keep-together {
  page-break-inside: avoid;
  break-inside: avoid;
}

With wkhtmltopdf, separate concerns: use CLI settings for paper and margins, and CSS declarations for element page breaks.

Complete Working Example

A production wkhtmltopdf command with margins, footer, and page size:

wkhtmltopdf \
  --page-size A4 \
  --margin-top 20mm \
  --margin-right 15mm \
  --margin-bottom 25mm \
  --margin-left 15mm \
  --footer-html footer.html \
  --enable-local-file-access \
  --footer-spacing 5 \
  --enable-javascript \
  --javascript-delay 100 \
  --print-media-type \
  --encoding utf-8 \
  --disable-smart-shrinking \
  input.html \
  output.pdf

Key flags explained:

Flag Purpose
--print-media-type Apply @media print CSS rules
--disable-smart-shrinking Prevent content from being scaled down to fit
--encoding utf-8 Set the input HTML's default text encoding to UTF-8
--javascript-delay 100 Wait for JS to execute before rendering

Generating from HTML Strings (Subprocess)

When generating from application code, wkhtmltopdf is typically invoked as a subprocess with stdin:

# Pipe HTML via stdin
echo "<html>...</html>" | wkhtmltopdf \
  --page-size A4 \
  --margin-top 20mm \
  --footer-right "Page [page] of [topage]" \
  - output.pdf
import subprocess

html = "<html><body><h1>Invoice</h1></body></html>"

result = subprocess.run(
    [
        "wkhtmltopdf",
        "--page-size", "A4",
        "--margin-top", "20mm",
        "--margin-right", "15mm",
        "--margin-bottom", "20mm",
        "--margin-left", "15mm",
        "--footer-right", "Page [page] of [topage]",
        "--quiet",
        "-",        # stdin
        "-",        # stdout
    ],
    input=html.encode("utf-8"),
    capture_output=True,
)

if result.returncode != 0:
    raise RuntimeError(result.stderr.decode("utf-8", errors="replace"))

pdf_bytes = result.stdout
const { spawn } = require("node:child_process");

function htmlToPdf(html) {
  return new Promise((resolve, reject) => {
    const child = spawn("wkhtmltopdf", [
      "--page-size", "A4",
      "--margin-top", "20mm",
      "--footer-right", "Page [page] of [topage]",
      "--quiet",
      "-",  // stdin
      "-",  // stdout
    ]);
    const chunks = [];
    const errors = [];

    child.stdout.on("data", (chunk) => chunks.push(chunk));
    child.stderr.on("data", (chunk) => errors.push(chunk));
    child.on("error", reject);
    child.on("close", (code) => {
      if (code === 0) {
        resolve(Buffer.concat(chunks)); // PDF bytes
      } else {
        reject(new Error(Buffer.concat(errors).toString("utf8")));
      }
    });

    child.stdin.end(html);
  });
}

Known Limitations

Beyond @page, Qt WebKit and Chromium differ in their support for modern CSS, JavaScript, and font loading. Test complex layouts, external fonts, and multi-page tables in both the source and destination environments.

The official wkhtmltopdf GitHub repository is archived and read-only. Consider this maintenance status before adopting it for a new project.

For a full feature comparison, see wkhtmltopdf vs Chromium PDF engine.

Migrating to a Modern PDF API

If wkhtmltopdf's limitations are causing production problems, consider migrating to a Chromium-based API.

FUNBREW PDF's quality engine uses Chromium. It supports size, margin, page pseudo-classes, and named pages; Chrome 131 and later also support margin boxes and page counters. Quality falls back to fast when Gotenberg is not configured, so verify actual output instead of assuming complete compatibility.

Before (wkhtmltopdf subprocess)

result = subprocess.run(
    ["wkhtmltopdf", "--margin-top", "20mm", "--margin-bottom", "20mm",
     "--footer-right", "Page [page]", "-", "-"],
    input=html.encode("utf-8"),
    capture_output=True,
)
if result.returncode != 0:
    raise RuntimeError(result.stderr.decode("utf-8", errors="replace"))

pdf_bytes = result.stdout

After (FUNBREW PDF API)

import requests

headers = {"Authorization": "Bearer sk-your-api-key"}
response = requests.post(
    "https://pdf.funbrew.cloud/api/pdf/generate-from-html",
    headers=headers,
    json={
        "html": html,  # Define page numbers with CSS @page margin boxes
        "options": {
            "engine": "quality",
            "page-size": "A4",
            "margin-top": 20,
            "margin-right": 15,
            "margin-bottom": 20,
            "margin-left": 15,
        },
    },
    timeout=60,
)
response.raise_for_status()

download_url = response.json()["data"]["download_url"]
pdf_response = requests.get(download_url, headers=headers, timeout=60)
pdf_response.raise_for_status()
pdf_bytes = pdf_response.content

Key differences: no subprocess or CLI flags, and margins are numeric millimeter values such as margin-top. Define page numbers with CSS margin boxes in the HTML and verify them with the quality engine on Chrome 131 or later.

For a step-by-step walkthrough of the migration, see the wkhtmltopdf migration guide.

Quick Reference: wkhtmltopdf CLI Flags

Goal CSS CLI flag
A4 page size Do not rely on @page { size: A4 } alone --page-size A4
Zero margins Reset the body margin too --margin-top 0 --margin-right 0 --margin-bottom 0 --margin-left 0
20mm top margin — --margin-top 20mm
Landscape — --orientation Landscape
Page numbers Use CLI substitutions instead of CSS counters --footer-right "Page [page] of [topage]"
Page break page-break-before: always and break-before: page —
Avoid row split page-break-inside: avoid and break-inside: avoid —
Print media CSS — --print-media-type

Debugging Tips

  1. Add --debug-javascript to see JS errors in the footer/header HTML
  2. Test with --dump-outline outline.xml to inspect the PDF outline
  3. Use --quiet in production to suppress non-error output to stderr
  4. Try Playground for instant HTML-to-PDF feedback without CLI setup — paste your HTML and see the output immediately in your browser

Summary

For wkhtmltopdf @page CSS:

  • Margins: Always use --margin-* CLI flags instead of relying on @page alone
  • Page size: Set --page-size explicitly
  • Landscape: Use --orientation Landscape
  • Page numbers / headers / footers: Use --footer-right, --header-html, and --footer-html; check --enable-local-file-access for local HTML
  • Page breaks: Include legacy and modern declarations and verify output from your version
  • Background colors: wkhtmltopdf enables --background by default. Use --print-media-type when switching from screen to print styles

If these workarounds are limiting you, a Chromium-based API like FUNBREW PDF removes the CLI. Verify margin boxes on Chrome 131 or later. In test mode, you can generate a watermarked PDF in the Playground without signing up.

Related Links

Powered by FUNBREW PDF