Ask Anvil

Answers to questions about automating PDFs, e-signatures, Webforms, and other paperwork problems.
PDFs
Categories

How do I hide the nav and buttons when converting a web page to PDF with Puppeteer?

Add a print stylesheet to the page. Puppeteer's page.pdf() generates the PDF with the print CSS media type, so rules inside @media print apply automatically:

@media print {
  header.site-nav,
  .cta-button,
  #cookie-banner {
    display: none !important;
  }
}

@page {
  size: A4;
}

Then generate the PDF. Setting preferCSSPageSize to true lets the @page size in your CSS win over the format, width, and height options, and printBackground keeps background colors and images:

const fs = require('fs');
const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('https://example.com/report/123', { waitUntil: 'networkidle0' });
  const pdf = await page.pdf({ preferCSSPageSize: true, printBackground: true });
  await fs.promises.writeFile('report.pdf', pdf);
  await browser.close();
})();

Caveats

According to the Puppeteer docs, printBackground defaults to false, so backgrounds vanish unless you set it. preferCSSPageSize also defaults to false, which scales the content to fit the paper size, and the default paper format is letter.

If you want the PDF to look like the on-screen page instead, call await page.emulateMediaType('screen') before page.pdf(). Your @media print rules then stop applying, so the nav and buttons come back. The only accepted values are screen, print, and null.

MDN notes that specificity and precedence rules still apply inside @media print, which is why the example uses !important when overriding display rules defined elsewhere in your stylesheet.

Back to All Questions

The fastest way to build software for documents

Anvil Document SDK is a comprehensive toolbox for product teams launching document flows where PDF filling, signing, and complex conditional scenarios are necessary.
Explore Anvil
Anvil Webforms
Marketing Mode