iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
Use Puppeteer’s page.pdf() with displayHeaderFooter: true, then provide HTML strings through headerTemplate and footerTemplate. Reserve vertical space with top and bottom margins, and use Puppeteer’s supported placeholder classes for dates, titles, URLs, and page numbers.
Minimal working example
This Node.js example loads a page and creates a PDF with a branded header and a page-number footer. Install Puppeteer first with npm install puppeteer.
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://example.com', { waitUntil: 'networkidle2' });
await page.pdf({
path: 'output.pdf',
format: 'A4',
displayHeaderFooter: true,
headerTemplate: `
<div style="width:100%; font-size:9px; padding:0 20px; color:#555;">
<span>Example report</span>
<span style="float:right"><span class="date"></span></span>
</div>`,
footerTemplate: `
<div style="width:100%; font-size:9px; padding:0 20px; color:#555; text-align:center;">
Page <span class="pageNumber"></span> of <span class="totalPages"></span>
</div>`,
margin: {
top: '60px',
bottom: '60px',
left: '24px',
right: '24px'
}
});
await browser.close();
})();
The displayHeaderFooter option is false by default, so templates are ignored unless you enable it. The margin values above are starting points; adjust them after inspecting your paper size, template height, and content. Puppeteer documents these options in its PDFOptions interface.
Recommended Free Tools
How header and footer templates work
Templates are separate HTML strings
headerTemplate and footerTemplate are independent fragments. Supply only the one you need, or supply both. They repeat on each PDF page generated by page.pdf(). Keep the markup self-contained and simple; do not assume that every normal page style, script, or layout behavior will work inside the print furniture.
#1 Best Overall
- EDIT text, images & designs in PDF documents. ORGANIZE PDFs. Convert PDFs to Word, Excel & ePub.
- READ and Comment PDFs – Intuitive reading modes & document commenting and mark up.
- CREATE, COMBINE, SCAN and COMPRESS PDFs
- FILL forms & Digitally Sign PDFs. PROTECT and Encrypt PDFs
- LIFETIME License for 1 Windows PC or Laptop. 5GB MobiDrive Cloud Storage Included.
Supported dynamic values
Puppeteer replaces these classes with document values:
| Class | Inserted value | Typical use |
|---|---|---|
date |
Formatted print date | Report generation date |
title |
Document title | Page header |
url |
Document location | Source URL or audit trail |
pageNumber |
Current page number | “Page 2” |
totalPages |
Total page count | “of 8” |
For example, a footer can contain <span class="pageNumber"></span> / <span class="totalPages"></span>. The same placeholder support and constraints apply to both templates.
Reserve space so content does not collide with the furniture
Puppeteer’s PDF margins default to undefined, which means no margin is set for you. Set at least the top margin needed by the header and the bottom margin needed by the footer. If a template is taller than the reserved area, it can overlap the document body or appear clipped.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallOutdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchawait page.pdf({
path: 'report.pdf',
displayHeaderFooter: true,
headerTemplate: '<div style="font-size:10px; padding:8px 16px;">Confidential</div>',
footerTemplate: '<div style="font-size:10px; padding:8px 16px; text-align:right;">Page <span class="pageNumber"></span></div>',
margin: {
top: '55px',
bottom: '45px',
left: '18mm',
right: '18mm'
}
});
Measure the rendered result for your own template, font, and paper choice rather than treating these values as universal measurements.
Style the templates safely
Use inline styles for predictable output
Inline CSS is the most dependable way to style a header or footer. Define width, font size, padding, alignment, and color directly in the fragment. External stylesheets and page-level selectors are not guaranteed to affect template content as they would affect the document body.
Rank #2
- Edit PDFs with Ease. Modify text, images, and layouts directly within your PDF documents.
- Convert & Organize. Export PDFs to Word, Excel, or ePub, and organize files with ease.
- Read & Annotate. Enjoy intuitive reading modes and powerful tools to comment, highlight, and mark up PDFs.
- Create & Manage PDFs. Create new PDFs, combine multiple files, scan documents, and compress for easy sharing.
- Fill & Sign Forms. Complete forms and digitally sign documents with secure e-signature tools.
const headerTemplate = `
<div style="width:100%; border-bottom:1px solid #d0d7de; padding:0 18px 6px; font:10px Arial, sans-serif; color:#334155;">
<span class="title"></span>
<span style="float:right">Internal use</span>
</div>`;
Images and logos
If you include a logo, use a reliably available asset and verify the PDF in the same runtime that will run in production. A data URI can avoid a separate network request, while a remote image may fail if the browser cannot reach it before rendering. Keep the image dimensions explicit so it does not change the header height unexpectedly.
Keep scripts out of the templates
Treat templates as print markup, not an interactive page. Put data preparation and conditional logic in Node.js before calling page.pdf(), then interpolate the resulting, escaped values into the HTML. Do not insert untrusted user text directly into HTML without escaping it.
Control print media, paper size, and colors
Print CSS is the default
page.pdf() generates output using the print CSS media type. Add print-specific rules in your page stylesheet when the PDF should differ from the screen view:
@media print {
.screen-only { display: none !important; }
.invoice { break-inside: avoid; }
}
If the PDF must use screen styles instead, call page.emulateMediaType('screen') before page.pdf():
await page.emulateMediaType('screen');
await page.pdf({
path: 'screen-styled.pdf',
displayHeaderFooter: true,
headerTemplate,
footerTemplate,
margin: { top: '60px', bottom: '60px' }
});
Puppeteer documents this behavior in the Page class API and the Page.pdf() method.
Rank #3
- Create and edit PDFs. Collaborate with ease. E-sign documents and collect signatures. Get everything done in one app, wherever you go.
- Edit text and images without jumping to another app.
- E-sign documents or request e-signatures on any device. Recipients don’t need to log in to e-sign.
- Convert PDFs to editable Microsoft Word, Excel, or PowerPoint documents.
- Share PDFs for collaboration. Commenting features make it easy for reviewers to comment, mark up, and annotate.
Preserve exact colors when required
PDF generation modifies colors for printing by default. To request closer color fidelity, add this rule to the document’s print CSS:
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Clear out junk files and repair common Windows errors3Scan for outdated or missing drivers - takes under a minute* {
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}
Use it selectively when possible: forcing every color can increase ink usage and may make a document less readable in print.
Choose a paper model
format selects a named paper size such as A4 or Letter. You can instead provide width and height, plus landscape: true for orientation. When format is set, it takes priority over width and height.
await page.pdf({
path: 'landscape-report.pdf',
format: 'A4',
landscape: true,
displayHeaderFooter: true,
headerTemplate,
footerTemplate,
margin: { top: '52px', bottom: '52px' }
});
preferCSSPageSize defaults to false. Set it to true when the document’s CSS @page size should take priority over PDF option dimensions:
await page.pdf({
path: 'css-sized.pdf',
displayHeaderFooter: true,
preferCSSPageSize: true,
headerTemplate,
footerTemplate,
margin: { top: '60px', bottom: '60px' }
});
Fonts, loading, and repeatable output
Puppeteer’s PDF generation waits for fonts to load by default. Retain that behavior when your header, footer, or body uses web fonts. If you deliberately change font-loading behavior, inspect the resulting PDF in the actual deployment environment; a fallback font can alter line wrapping, header height, and page breaks. The official PDF generation guide covers the default font wait and related guidance.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Rank #4
- Perfect Adobe Acrobat Pro alternative – lifetime license for Windows 10 and 11.
- EDIT text, images, pages, hyperlinks, designs in PDF documents. ORGANIZE PDFs.
- READ and Comment on PDFs – Intuitive reading modes & document commenting and mark up tools!
- CREATE, COMBINE, SCAN and COMPRESS PDFs.
- FILL forms & Digitally Sign PDFs. Work with Digital certificates
For stable captures, wait for the page state your application actually needs before calling page.pdf(). A network-idle wait can be useful for static pages, while an explicit selector wait is safer when an application continues polling:
await page.goto(url, { waitUntil: 'domcontentloaded' });
await page.waitForSelector('#report-ready');
await page.evaluate(() => document.fonts.ready);
await page.pdf({
path: 'ready.pdf',
displayHeaderFooter: true,
headerTemplate,
footerTemplate,
margin: { top: '60px', bottom: '60px' }
});
Common failures and fixes
The header or footer is missing
- Cause:
displayHeaderFooterwas omitted or set tofalse. - Fix: Set
displayHeaderFooter: truein the samepage.pdf()call that supplies the templates.
Body text runs into the header
- Cause: The top margin is smaller than the header’s rendered height.
- Fix: Increase
margin.top, reduce template padding or font size, and regenerate the PDF.
Footer is clipped or overlaps the last line
- Cause: Insufficient bottom margin.
- Fix: Reserve more bottom space and check the final page at the selected paper size.
Page numbers show literally as text
- Cause: The placeholder class is misspelled or placed on an element without the documented class.
- Fix: Use exactly
class="pageNumber"andclass="totalPages"; do not put the words in curly-brace syntax.
Colors look washed out
- Cause: Print color adjustment changed the source colors.
- Fix: Add
-webkit-print-color-adjust: exact(and the standard property) where exact color reproduction matters.
Layout differs between local and production
- Cause: Different Chromium versions, missing fonts, unavailable image URLs, or a different media type.
- Fix: Pin and deploy the same Puppeteer/Chromium environment, wait for fonts and required selectors, and verify all assets are reachable in production.
CSS page size is ignored
- Cause: PDF dimensions are taking precedence.
- Fix: Set
preferCSSPageSize: truewhen your@pagerule should control size.
Testing checklist before shipping
- Render a one-page and a multi-page document.
- Check that the first, middle, and final pages have the expected header and footer.
- Verify page numbers and total pages after content changes.
- Test both your target paper size and orientation.
- Confirm long titles, non-Latin text, and missing optional fields do not break the template.
- Open the PDF in more than one viewer and print a sample if physical output matters.
- Keep margins, template HTML, and browser versions under version control so visual changes are reviewable.
Or skip the browser setup
For a hosted screenshot or PDF workflow, ScreenshotNeo provides a single HTTP endpoint and an MCP server for AI agents. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers report the page verdict and billing status. Its PDF options include paper size, margins, landscape mode, and page ranges.
See the ScreenshotNeo documentation for the complete parameter list. A direct request 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
Python
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)
Node.js
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 includes an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
FAQ
Can I add only a footer?
Yes. Enable displayHeaderFooter, provide footerTemplate, and omit headerTemplate. Reserve bottom margin for the footer.
Can a template contain page-specific data?
Puppeteer supplies the documented date, title, URL, current-page, and total-page placeholders. For other values, prepare the HTML in your application before calling page.pdf().
Best Value
- ALL-IN-ONE SOLUTION – read, edit, convert, merge and protect your PDF files
- MAXIMUM FUNCIONALITY – create interactive forms, compare PDFs, bates numbering, find and replace text or colors, convert documents, OCR engine, comment, highlight, fill out and print forms, document protection and others
- EASY TO INSTALL AND USE – well-structured user-interface, in-program instructions, free tech support whenever you need it
- GREAT VALUE FOR MONEY - why spend a fortune if you can have maximum functionality at a reasonable price - this also fits the requirements of companies very well
Should I use CSS @page or PDF options for size?
Use PDF options for straightforward format, dimensions, and orientation control. Set preferCSSPageSize: true when the document’s CSS page rule must take priority.
Frequently Asked Questions
Can I add only a footer?
Yes. Enable displayHeaderFooter, provide footerTemplate, and omit headerTemplate. Reserve bottom margin for the footer.
Can a template contain page-specific data?
Puppeteer supplies the documented date, title, URL, current-page, and total-page placeholders. For other values, prepare the HTML in your application before calling page.pdf().
Should I use CSS @page or PDF options for size?
Use PDF options for straightforward format, dimensions, and orientation control. Set preferCSSPageSize: true when the document’s CSS page rule must take priority.
Quick Recap
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.

