User Agents

Web browsers and everyday web tech, explained

Generate PDFs from HTML with Headless Chrome

· 4 min read · Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Generate PDFs from HTML with headless Chrome by using Chrome's built-in printing capabilities in a browser environment without a graphical interface. This method converts web pages or HTML content into high-fidelity PDF documents, preserving layout, fonts, and styling exactly as they appear in Chrome. It’s widely used for generating reports, invoices, or documentation programmatically. The process relies on Chrome or Chromium installed on a server or local machine and can be automated via command line or scripting tools like Node.js.

What You'll Need

  • Chrome or Chromium browser installed (version 59 or later)
  • Access to a command line or terminal
  • Basic knowledge of HTML and file paths
  • Optional: Node.js and Puppeteer for automation

Step-by-Step

  1. Ensure Chrome or Chromium is installed on your system. Verify the version by opening Chrome, navigating to chrome://settings/help, and confirming it's version 59 or higher. Headless mode for PDF generation has been supported since Chrome 59.
  2. Prepare your HTML file. Save the HTML content you want to convert as a local file (e.g., report.html) on your machine. Make sure all assets (CSS, images, fonts) are either embedded or accessible via relative or absolute paths.
  3. Open a terminal or command prompt. Navigate to the directory containing your HTML file using cd /path/to/your/file.
  4. Run the Chrome command to generate the PDF. Use the following template, adjusting file names and paths as needed:
    chrome --headless --disable-gpu --print-to-pdf=report.pdf report.html
    This command launches Chrome without a UI, disables GPU rendering (required in headless mode), and outputs a PDF named report.pdf from report.html.
  5. Wait for the command to complete. Chrome will close automatically once the PDF is generated. Check the current directory for the output file.
  6. To customize the PDF output, add optional flags. For example:
    chrome --headless --disable-gpu --print-to-pdf=report.pdf --no-margins --paper-size=a4 report.html
    Common flags include --no-margins, --landscape, --page-ranges=1-3, and --scale=0.8. Refer to Chrome's command-line switches documentation for full options.
  7. For automation or dynamic content, use Puppeteer (a Node.js library). Install it via npm:
    npm install puppeteer
    Then create a script (generate.js) with:
    const puppeteer = require('puppeteer');
    
    (async () => {
      const browser = await puppeteer.launch();
      const page = await browser.newPage();
      await page.goto('file:///path/to/report.html', {waitUntil: 'networkidle0'});
      await page.pdf({path: 'report.pdf', format: 'A4'});
      await browser.close();
    })();
    Run the script with node generate.js to generate the PDF.
  8. Verify the output PDF. Open it in a viewer to confirm layout, fonts, and content match expectations. Pay attention to image rendering, font embedding, and page breaks.

Common Mistakes

  • Forgetting to include --disable-gpu, which is required in headless mode on some systems and can cause the command to fail silently.
  • Using incorrect file paths, especially when running Chrome from a different directory. Always use absolute paths if relative ones fail.
  • Not waiting for dynamic content to load. When using JavaScript-heavy pages, Chrome may generate the PDF before content renders. Use --virtual-time-budget=5000 or Puppeteer’s waitUntil option.
  • Ignoring CSS media types. If styles are only defined for screen, they may not apply in print. Use @media print or screen styles to ensure correct styling.
  • Overlooking file permissions. Chrome may fail to write the PDF if the output directory is not writable.

Tips

  • Use Puppeteer for complex workflows. It offers fine-grained control over page loading, authentication, and PDF settings.
  • Test HTML locally first. Open the HTML file in Chrome to ensure it renders correctly before conversion.
  • Set explicit page size and margins in CSS using @page rules to avoid layout shifts.
  • Embed fonts using @font-face and base64 encoding if external fonts fail to load in headless mode.
  • Add a small delay or network idle check when loading pages with AJAX content to ensure completeness.

Troubleshooting

If the PDF does not generate, first check that Chrome is in your system PATH or provide the full executable path (e.g., /usr/bin/google-chrome on Linux or "C:\Program Files\Google\Chrome\Application\chrome.exe" on Windows). If Chrome opens a window, you’re not in headless mode—double-check the --headless flag. If fonts or images are missing, verify that resources are accessible and not blocked by CORS or file:// restrictions. On some systems, use --allow-file-access-from-files to enable local file loading. If Puppeteer fails to launch Chrome, try launching it with headless: 'new' or args: ['--no-sandbox', '--disable-setuid-sandbox'] in environments like Docker. Always check terminal output for error messages, which often indicate missing files, permission issues, or syntax errors in flags.

Frequently Asked Questions

Can I generate PDFs from HTML strings without saving a file?

Yes. With Puppeteer, use page.setContent() to load HTML directly, then call page.pdf().

Does headless Chrome support CSS print features?

Yes. It supports @page, page margins, page breaks, and @media print rules.

Why are images not showing in the PDF?

Images may fail to load from file:// paths. Use absolute paths, embed as base64, or serve HTML via a local server.

Can I add headers and footers?

Yes. Use the --header-html and --footer-html flags or Puppeteer’s displayHeaderFooter option with headerTemplate.

Is this method suitable for server-side automation?

Yes. Headless Chrome runs on Linux servers and integrates well with Node.js, Python, or CI/CD pipelines.

How do I set custom paper sizes?

Use --paper-width and --paper-height in inches or millimeters, or set format: 'A4' in Puppeteer with custom dimensions.