User Agents

Web browsers and everyday web tech, explained

Print PDFs with Headless Chrome and DevTools

· 5 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

Printing PDFs with headless Chrome and Chrome DevTools Protocol (CDP) allows you to automate PDF generation from web pages without launching a visible browser. This is ideal for server-side rendering, report generation, or batch conversion of HTML to PDF. By using Chrome in headless mode and connecting via the DevTools Protocol, you can control page rendering, set margins, adjust scaling, and export high-quality PDFs programmatically. This guide walks through the process using command-line tools and simple scripting, assuming basic familiarity with terminal commands and web development tools.

What You'll Need

  • Google Chrome or Chromium installed (version 59 or later)
  • Access to a command line or terminal (macOS, Linux, or Windows)
  • A local or remote HTML file to convert
  • Basic knowledge of JSON and command-line arguments
  • Optional: Node.js and Puppeteer for scripting (not required for basic use)

Step-by-Step

  1. Verify Chrome or Chromium is installed by opening a terminal and typing chrome --version or chromium --version. If not installed, download Chrome from the official site or use your system’s package manager.
  2. Launch Chrome in headless mode with remote debugging enabled. Run this command in the terminal:
    chrome --headless --disable-gpu --remote-debugging-port=9222 --no-sandbox
    This starts Chrome without a UI and listens for DevTools connections on port 9222. The --no-sandbox flag may be needed on some systems but use cautiously in production.
  3. Open a new terminal window. Use curl to request the list of available debugging targets. Run:
    curl http://localhost:9222/json
    You should see a JSON response listing active pages. Note the webSocketDebuggerUrl for the target you want to print.
  4. Use a tool like Puppeteer or a WebSocket client to connect to the debugging URL. For simplicity, we’ll use Puppeteer with a small script. Install it via npm if not already present:
    npm install puppeteer
  5. Create a JavaScript file named print-pdf.js. Add the following code to connect to the running Chrome instance and generate a PDF:
const puppeteer = require('puppeteer');

(async () => {
  // Connect to existing Chrome instance
  const browser = await puppeteer.connect({
    browserWSEndpoint: 'ws://localhost:9222/devtools/browser/[browser-id]',
    defaultViewport: null
  });

  const page = await browser.newPage();
  await page.goto('file:///path/to/your/page.html', { waitUntil: 'networkidle0' });

  await page.pdf({
    path: 'output.pdf',
    format: 'A4',
    printBackground: true,
    margin: {
      top: '20px',
      bottom: '40px',
      left: '20px',
      right: '20px'
    }
  });

  await browser.close();
})();
  1. Replace [browser-id] in the WebSocket URL with the actual ID from the /json response. Also update the page.goto() URL to point to your HTML file or web page.
  2. Run the script with Node.js:
    node print-pdf.js
    If successful, a file named output.pdf will be created in the current directory.
  3. For direct command-line PDF printing without scripting, use Chrome’s built-in print-to-PDF via command line. Run:
    chrome --headless --disable-gpu --print-to-pdf=output.pdf /path/to/page.html
    This skips DevTools entirely and directly exports the page. Add --no-margins or --landscape as needed.
  4. Verify the output PDF opens correctly and displays all content, especially CSS styles, fonts, and images. Adjust the waitUntil condition if elements are missing (e.g., use 'domcontentloaded' for faster loads or 'networkidle2' for dynamic content).
  5. Automate batch conversions by looping through HTML files in a script, adjusting the input and output paths dynamically.

Common Mistakes

  • Forgetting to start Chrome with --remote-debugging-port, making it impossible to connect via DevTools.
  • Using an incorrect or expired webSocketDebuggerUrl — always fetch it fresh from /json after launching Chrome.
  • Not waiting for page resources to load before generating the PDF, leading to missing images or incomplete styles.
  • Running headless Chrome in restricted environments without --no-sandbox, which may cause startup failures (but avoid this flag in untrusted environments).
  • Hardcoding file paths without escaping spaces or special characters, causing navigation failures.

Tips

  • Use networkidle0 or networkidle2 in page.goto() to ensure all network requests finish before printing.
  • Set printBackground: true to include CSS background colors and images in the PDF.
  • Adjust scale (0.1 to 2.0) in the page.pdf() options to control zoom level.
  • Use absolute file paths (e.g., file:///Users/name/doc.html) to avoid routing issues.
  • For large-scale automation, consider running Chrome in Docker with predefined settings.

Troubleshooting

If the PDF is blank, confirm the page loaded correctly by adding a screenshot step: await page.screenshot({ path: 'debug.png' }); before page.pdf(). If Chrome fails to start, check port 9222 is not already in use — change the debugging port if needed. If Puppeteer throws a connection error, ensure the browser is running and the WebSocket URL is correct. For missing fonts or styles, verify the HTML page loads all assets over file:// or ensure CORS is not blocking resources. If using Linux servers, install required dependencies like libx11-dev or libgbm-dev if Chrome crashes on launch. On Windows, use forward slashes or properly escaped backslashes in file paths.

Frequently Asked Questions

Can I print multiple pages into one PDF?

Yes, but each page.pdf() call generates one file. To combine, use external tools like pdfunite or PyPDF2 to merge outputs after generation.

Does this work with password-protected pages?

Only if you can authenticate programmatically. Use page.authenticate() with credentials, or log in via page.type() and form submission before printing.

Can I add headers and footers?

Yes. In the page.pdf() options, use displayHeaderFooter: true and set headerTemplate and footerTemplate with HTML.

Is Puppeteer required?

No. You can use raw WebSocket connections or tools like chrome-remote-interface, but Puppeteer simplifies the process significantly.

Why is my PDF missing images?

Images may fail to load if the page doesn’t wait long enough. Use waitUntil: 'networkidle0' or check if the image paths are correct in the headless context.

Can I run this on a server without a GUI?

Yes. Headless Chrome is designed for server environments. Ensure all dependencies are installed and avoid flags that require display servers.