User Agents

Web browsers and everyday web tech, explained

Serve PDFs to Users 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

This guide explains how to use headless Chrome to generate and serve PDF files to users on demand. Instead of pre-generating static PDFs or relying on third-party services, you can render HTML templates into PDFs directly from your server using the same rendering engine as the Chrome browser. This is useful for invoices, reports, tickets, or any document that needs to reflect current data. You'll need a server with Node.js (or another language that can spawn child processes) and Chrome or Chromium installed.

What You'll Need

  • A server with Node.js (v14 or later) or another runtime that can execute shell commands.
  • Chrome or Chromium installed (version 60+ for headless mode). On Linux, you may need to install dependencies like libnss3 and libatk.
  • Basic knowledge of HTML/CSS for your PDF template.
  • Access to a command line on your server.

Step-by-Step

  1. Install Chrome/Chromium – On Ubuntu/Debian: sudo apt-get install chromium-browser. On CentOS: sudo yum install chromium. Verify with chromium --version or google-chrome --version.
  2. Create a simple HTML template – Write a file like invoice.html with your content, including inline CSS for print (e.g., @page { margin: 2cm; } ). Use placeholders like if you plan to substitute data.
  3. Set up a Node.js server – Initialize a project with npm init -y and install Express: npm install express. Create an app.js file.
  4. Write the endpoint – In app.js, create a route like app.get('/pdf', (req, res) => { ... }). Inside, read your HTML template, replace placeholders with data from a database or request query.
  5. Generate the PDF – Use child_process.execFile to run Chrome in headless mode. Example command: chromium --headless --disable-gpu --print-to-pdf=/tmp/output.pdf --no-margins file:///path/to/template.html. Use the --no-sandbox flag if running as root or in a container.
  6. Serve the PDF – After Chrome completes, read the generated file and send it to the client: res.sendFile('/tmp/output.pdf'). Set the Content-Type header to application/pdf.
  7. Clean up – Delete the temporary PDF after sending, or use a unique filename per request to avoid collisions.
  8. Test – Run node app.js and visit http://localhost:3000/pdf. You should see the PDF in your browser.

Common Mistakes

  • Not using absolute file paths – Chrome needs absolute paths to the HTML file and the output PDF. Use path.resolve() in Node.
  • Forgetting the --no-sandbox flag – On many Linux servers, Chrome fails without it due to sandboxing restrictions.
  • Ignoring Chrome's exit code – If Chrome fails (e.g., due to missing fonts), it may produce an empty PDF. Check stderr and exit code.
  • Using --print-to-pdf with a URL that has query strings – Chrome may not handle query strings well in headless mode. Write the HTML to a temporary file instead.

Tips

  • Use a template engine like Handlebars or EJS to inject data cleanly.
  • Set a @page rule in CSS to control margins and page size.
  • For large PDFs, consider streaming or generating asynchronously with a job queue.
  • Cache the generated PDF if the data doesn't change often, to reduce load.
  • Use --print-to-pdf-no-header to remove the default header/footer.

Troubleshooting

  • PDF is blank or missing content – Check that your HTML file is accessible by Chrome (permissions, path). Open the HTML in a regular browser to see if it renders. Also check Chrome's stderr for errors.
  • Chrome not found – Ensure the binary is in your PATH or specify the full path in your code.
  • PDF is truncated or cut off – Adjust your CSS margins and page size. Use --no-margins only if you handle margins in CSS.
  • Server hangs – Chrome might not exit if there are pending timers or network requests. Use --timeout or kill the process after a few seconds.
  • Permission errors – Run the server with a non-root user, or use --no-sandbox and --disable-setuid-sandbox.

Frequently Asked Questions

Can I use Puppeteer instead of raw Chrome commands?

Yes, Puppeteer is a Node library that simplifies controlling headless Chrome. It provides a page.pdf() method. However, it adds a dependency and may be heavier than calling Chrome directly.

How do I add headers and footers to the PDF?

Chrome's --print-to-pdf does not support custom headers/footers directly. You can use Puppeteer's displayHeaderFooter option, or embed headers/footers in your HTML using fixed positioning.

Is headless Chrome faster than other PDF generators?

It's comparable. Chrome is slower than lightweight libraries like pdfkit, but it gives you pixel-perfect rendering of HTML/CSS, which is often worth the speed trade-off.

Can I serve PDFs on a Windows server?

Yes, install Chrome for Windows and use the same approach. The command is similar, but the path to the executable may differ (e.g., C:\Program Files\Google\Chrome\Application\chrome.exe).

How do I handle concurrent requests?

Chrome can only handle one PDF at a time per process. Use a queue or spawn multiple Chrome instances with unique output filenames. Alternatively, use Puppeteer's cluster module.

What about memory usage?

Each Chrome instance uses ~100-200 MB. If you have many requests, consider using a pool of Chrome processes or a dedicated PDF microservice.