Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
Command Line

How to Use the `–replace` Option in wkhtmltopdf

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use --replace <name> <value> to substitute a custom token in wkhtmltopdf header or footer text. Put the token in brackets—for example, [customer]—then provide its value with --replace customer "Acme Corp". The option is repeatable, so one command can fill several custom fields.

The basic pattern

wkhtmltopdf applies --replace to text configured through header and footer options. The name in the command has no brackets; the matching token in the header or footer does.

wkhtmltopdf 
  --header-left "Customer: [customer]" 
  --header-right "Ticket: [ticket]" 
  --replace customer "Acme Corp" 
  --replace ticket "A-1042" 
  input.html output.pdf

The generated PDF header contains Customer: Acme Corp on the left and Ticket: A-1042 on the right. Values containing spaces should be quoted. Quote values containing shell metacharacters as well, and use the quoting rules of your shell.

One custom value

wkhtmltopdf 
  --header-center "Prepared for [customer]" 
  --replace customer "Acme Corp" 
  input.html output.pdf

Several custom values

Add one complete --replace name value pair for each token. Do not combine mappings into a single argument.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
wkhtmltopdf 
  --footer-left "Account: [account]" 
  --footer-center "Owner: [owner]" 
  --footer-right "Case: [case]" 
  --replace account "C-2048" 
  --replace owner "Jordan Lee" 
  --replace case "A-1042" 
  input.html output.pdf

Which header and footer options support it?

The same substitution pattern works with the text positions exposed by wkhtmltopdf:

  • --header-left
  • --header-center
  • --header-right
  • --footer-left
  • --footer-center
  • --footer-right

For example:

wkhtmltopdf 
  --footer-center "Invoice [invoice] · [customer]" 
  --replace invoice "INV-9007" 
  --replace customer "Acme Corp" 
  invoice.html invoice.pdf

Keep the spelling consistent. [customer] matches --replace customer "..."; [Customer] and [customer_name] are different names.

What `–replace` does—and does not do

The option is documented as replacing bracketed names in header and footer text. It is not a general find-and-replace operation for the HTML document body.

Location How to insert a value Does `–replace` rewrite it?
Text header or footer Put [name] in the option value Yes
HTML body Put the desired text in the source HTML or generate it before conversion No, not as a documented body substitution feature
HTML header or footer file Read page variables from the query string and insert them with JavaScript Use the HTML header/footer mechanism, not body replacement

If a customer name appears inside <main> in your source file, replace it in your application, template engine, or preprocessing step before invoking wkhtmltopdf. Adding --replace customer ... will not search that markup.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Built-in variables you already get

wkhtmltopdf supplies standard header and footer variables. Place these names in brackets without defining them yourself:

Variable Typical use
[page] Current page number
[frompage] First page in the current range
[topage] Last page number
[webpage] Web page address or source identifier
[section], [subsection] Document section labels
[date], [isodate], [time] Date and time values
[title], [doctitle] Page or document title
[sitepage], [sitepages] Site-level page numbering

A page counter needs no custom mapping:

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

Custom names and built-in variables serve different purposes. Use --replace for values supplied by your application, and use the documented variables for pagination and document metadata. Avoid reusing built-in names unless you have a specific reason to test the behavior.

Using HTML headers and footers

Text options are convenient for short labels. For logos, multiple lines, CSS layout, or richer typography, use --header-html header.html or --footer-html footer.html.

wkhtmltopdf 
  --margin-top 25mm 
  --header-html header.html 
  --footer-html footer.html 
  input.html output.pdf

For an HTML header or footer, wkhtmltopdf passes page information to that document in the URL query string. The documented approach is to parse that query string in JavaScript and copy values into elements whose classes identify the variables.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <script>
    function subst() {
      const vars = {};
      const query = window.location.search.substring(1).split('&');
      for (const part of query) {
        if (!part) continue;
        const pair = part.split('=');
        vars[pair[0]] = decodeURIComponent(pair[1] || '');
      }
      for (const name in vars) {
        const nodes = document.getElementsByClassName(name);
        for (const node of nodes) node.textContent = vars[name];
      }
    }
  </script>
</head>
<body onload="subst()">
  <span class="page"></span> / <span class="topage"></span>
  <span class="title"></span>
</body>
</html>

The classes in this example correspond to the variables passed by wkhtmltopdf. Extend the markup and CSS for your layout, but retain the query-string substitution step when you need page metadata. The --replace option itself remains the documented mechanism for bracketed names in text header/footer options; it does not turn arbitrary body HTML into a replacement template.

Margins, spacing, and layout

A header or footer can be correctly substituted yet still be clipped or overlap the page content. Reserve physical space for it.

  1. Choose a top margin large enough for the header, or a bottom margin large enough for the footer.
  2. Adjust header or footer spacing when the text sits too close to the document.
  3. Convert a multi-page sample and inspect the first, middle, and last pages.
  4. If using an HTML header/footer, size its content deliberately; a taller HTML document needs more margin.
wkhtmltopdf 
  --margin-top 24mm 
  --margin-bottom 20mm 
  --header-spacing 4 
  --footer-spacing 4 
  --header-left "Customer: [customer]" 
  --footer-right "Page [page] of [topage]" 
  --replace customer "Acme Corp" 
  input.html output.pdf

Troubleshooting

The token appears literally as `[customer]`

  • Check that the option name is exactly customer, without brackets.
  • Check that the header or footer contains exactly [customer].
  • Ensure the --replace pair is part of the same wkhtmltopdf command.
  • Confirm that the token is in a supported header/footer text option, not in the body HTML.

The footer changes, but body text does not

This is expected. --replace is documented for header and footer text, not global HTML substitution. Change the source template before conversion, or generate an HTML header/footer and insert values there.

One value contains spaces or punctuation

Quote it:

--replace customer "Acme Corp (West)"

Without quoting, the shell can split the value into separate arguments. For values assembled from untrusted input, use your language’s process-spawning API with an argument array rather than concatenating a shell command.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Page numbers are blank in an HTML footer

Make sure the footer runs the query-string substitution script after loading and that its elements use the expected classes, such as page and topage. A literal <span class="page"></span> without the script will remain empty.

The header overlaps the document

Increase the relevant margin and adjust header/footer spacing. Check the rendered height of an HTML header, not just its font size.

A custom name conflicts with a built-in variable

Choose a distinct name such as customer_name or ticket_id. Reserve names such as page and topage for wkhtmltopdf’s documented pagination values.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Practical templates

Report with customer and pagination

wkhtmltopdf 
  --header-left "Customer: [customer]" 
  --header-right "Report: [report]" 
  --footer-right "Page [page] of [topage]" 
  --replace customer "Acme Corp" 
  --replace report "Monthly usage" 
  --margin-top 18mm 
  --margin-bottom 15mm 
  report.html report.pdf

Batch conversion from a script

For each document, construct the argument list independently so values cannot accidentally leak from one job to the next. Keep the token names stable across templates, and log the input identifier and output path for failed conversions.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Or skip the browser setup

If your actual goal is a clean screenshot or PDF of a web page rather than a locally rendered wkhtmltopdf document, ScreenshotNeo provides a website screenshot API and MCP server. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; bot checks, blank pages, timeouts, failed loads, and cache hits are not billed. Each response identifies the page verdict and billing status in headers.

One GET request returns an image or PDF. See the ScreenshotNeo documentation for all options.

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}`);

It also offers an MCP server with take_screenshot, get_page_info, and capture_pdf for AI clients, plus controls for full-page capture, selectors, device and viewport settings, dark mode, JavaScript, cookies, headers, waiting conditions, blocking, caching, signed links, webhooks, bulk capture, and more. The Free plan includes 1,000 screenshots per month without a card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

When to choose each method

Need Best fit
Inject a few values into a PDF header or footer Text options with repeatable --replace
Use page counters or document metadata Built-in bracketed variables such as [page] and [topage]
Design a branded, multi-line header/footer --header-html or --footer-html with query-string JavaScript
Replace text throughout the document body Preprocess the HTML or use a template engine
Capture a live public website without managing a browser ScreenshotNeo API or MCP server

Frequently Asked Questions

Can I use multiple `–replace` options in one command?

Yes. Repeat the complete option for every custom token, for example `–replace customer “Acme Corp” –replace ticket “A-1042″`.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Does `–replace` work inside the HTML body?

No. Its documented scope is header and footer text. Replace body values before running wkhtmltopdf.

How do I show page numbers in an HTML footer?

Use an HTML footer that reads the query-string variables with JavaScript and inserts them into elements such as `` and ``.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read next

Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.