Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Your first PDF

Assuming you have finished installing, this page walks from a single page through to page breaks.

1. Convert

Start with a hello.html.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <style>
      body { font-family: sans-serif; }
      h1 { border-bottom: 2px solid #333; padding-bottom: 8px; }
      .total { text-align: right; font-size: 1.2em; font-weight: bold; }
    </style>
  </head>
  <body>
    <h1>Invoice</h1>
    <p>Thank you for your continued business. Please find the charges below.</p>
    <p class="total">Total 12,000 JPY</p>
  </body>
</html>

Then convert it.

sghtmltopdf hello.html -o hello.pdf

Without -o, the output file is the input name with the extension changed to .pdf. Use - to read from standard input and write to standard output.

cat hello.html | sghtmltopdf - -o - > hello.pdf

2. Choose the paper and margins

sghtmltopdf hello.html -o hello.pdf \
  --page-size A4 --margin-top 20mm --margin-bottom 20mm

The units mm, cm, in, pt, and px are accepted, and a bare number means mm.

The same thing can be written in CSS with @page. If you write both, the CSS wins; the CLI options are treated as initial values. This is the opposite of wkhtmltopdf, so check Migrating from wkhtmltopdf when you move over.

@page {
  size: A4;
  margin: 20mm;
}

3. Break pages

“Start a new page here” is expressed with the CSS property break-before.

<style>
  .page-break { break-before: page; }
</style>

<h1>Invoice</h1>
<p>This is page 1.</p>

<div class="page-break">
  <h1>Line items</h1>
  <p>This is page 2.</p>
</div>

break-after, which breaks after the element, and break-inside: avoid, which keeps the element in one piece, are available too. So are orphans and widows, which stop a single line from being stranded at a page boundary. See Page breaks for details.

4. Add headers and footers

sghtmltopdf hello.html -o hello.pdf \
  --header-center "Invoice" \
  --footer-right "[page] / [topage]" \
  --header-line

[page] is replaced with the current page number and [topage] with the total page count. JavaScript is never executed, so these placeholders take its place. If you would rather build the header in HTML, use --header-html.

5. Pin the fonts

The examples so far use whatever fonts the system has. On a server or in CI, where you do not want the output to depend on the environment, name the font files explicitly.

sghtmltopdf hello.html -o hello.pdf \
  --font NotoSansJP-Regular.ttf \
  --gothic-font NotoSansJP-Regular.ttf