Fix Selenium WebDriver C# Timeouts Printing PDFs in Headless Chrome
In this article
This guide shows you how to stop Selenium WebDriver (C#) from timing out when you use headless Chrome to print a page as a PDF. The fix involves telling Chrome to wait longer for the print job to finish and adjusting how the PDF is generated. You'll need Visual Studio (or any C# IDE), a Selenium WebDriver project, and ChromeDriver installed.
What You'll Need
- A C# project with Selenium.WebDriver NuGet package installed.
- ChromeDriver (matching your Chrome version) available in your PATH or referenced in code.
- Basic understanding of C# and Selenium WebDriver.
Step-by-Step
- Set Chrome options for headless printing. Create a
ChromeOptionsinstance and add the argument--headless(or--headless=newfor newer Chrome versions). Also add--disable-gpuand--no-sandboxif you're on Linux or in a container. These are common for headless mode. - Enable the print-to-PDF feature. Add the argument
--print-to-pdfand, optionally,--print-to-pdf-no-headerto remove headers/footers. This tells Chrome to generate a PDF when the page loads. - Set a longer page load timeout. In your Selenium code, after creating the driver, set the page load timeout to a higher value (e.g., 60 or 120 seconds) using
driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(120);. This is the most common fix for timeouts because printing can take longer than a normal page load. - Increase the script timeout. Also set the script timeout (for async scripts) to a similar value:
driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(120);. - Use explicit waits for the PDF file. If you're waiting for the PDF to appear on disk, don't use a fixed sleep. Instead, use a WebDriverWait (or a simple loop) that checks for the file's existence with a timeout of, say, 30 seconds. This avoids unnecessary delays and handles slow printing.
- Consider using the Chrome DevTools Protocol (CDP) for print. Instead of relying on the
--print-to-pdfflag, you can use CDP'sPage.printToPDFmethod. This gives you more control and avoids the timeout issue because it returns the PDF as a base64 string directly. Here's a minimal example:var cdp = new ChromeDevToolsProtocol(driver); var printResult = cdp.Page.PrintToPDF(); File.WriteAllBytes("output.pdf", Convert.FromBase64String(printResult.Data));You'll need theDevTools.Sessionor a library likeWebDriverManagerthat supports CDP. - Run the print command after the page is fully loaded. Use a WebDriverWait for a specific element that indicates the page is ready (e.g., a footer or a specific div). Then trigger the print via JavaScript:
((IJavaScriptExecutor)driver).ExecuteScript("window.print();");– but this only works if you've set up the browser to handle the print dialog (usually with the--kiosk-printingflag). - Clean up and close the driver. Always call
driver.Quit()in afinallyblock to release resources, especially when using headless mode.
Common Mistakes
- Not setting the page load timeout – the default is 300 seconds in some drivers, but if you have a slow page, it might still time out. Always set it explicitly.
- Using
--print-to-pdfwithout specifying an output path – Chrome will save the PDF to a default location, which might not be where you expect. Use--print-to-pdf=C:\path\output.pdfto set it explicitly. - Forgetting to add
--disable-gpu– on some systems, headless Chrome requires this to avoid rendering issues that can cause hangs. - Using
Thread.Sleepinstead of explicit waits – fixed sleeps are brittle and can either cause timeouts or slow down your test unnecessarily. - Not handling the print dialog – if you call
window.print()without the--kiosk-printingflag, Chrome will show a dialog that Selenium cannot interact with, causing a hang.
Tips
- Use the CDP approach if you need the PDF content in memory (e.g., to attach to an email) rather than saving to disk.
- If you're printing multiple pages, consider reusing the same driver instance to avoid the overhead of launching a new browser each time.
- Set the browser window size to a standard paper size (e.g., 8.5x11 inches) using
driver.Manage().Window.Sizeto get consistent PDF layouts. - Test with a simple page first to verify your setup works before tackling complex pages with dynamic content.
- Keep your ChromeDriver and Chrome versions in sync – mismatches can cause unexpected behavior.
Troubleshooting
- If you still get a timeout after setting timeouts: Check if the page itself is hanging (e.g., due to endless JavaScript). Try loading the page in normal (non-headless) mode to see if it loads fine.
- If the PDF is not generated: Verify that the
--print-to-pdfargument is correctly spelled and that you have write permissions to the output directory. - If the CDP call fails: Ensure you're using the correct version of the DevTools protocol. You can check the Chrome version and match it with the CDP version.
- If the driver hangs on
Quit(): This can happen if there are pending print jobs. Try callingdriver.Close()first, thenQuit(). - If the page takes too long to render: Use
driver.Manage().Timeouts().ImplicitWaitfor element searches, but note that implicit waits don't affect page load timeouts.
Frequently Asked Questions
Why does printing cause a timeout in headless Chrome?
Headless Chrome still needs to render the page and generate the PDF, which can take longer than a simple page load. The default page load timeout may be too short for this operation.
Can I use the same code for non-headless Chrome?
Yes, but you'll need to handle the print dialog manually (e.g., with a keyboard shortcut) or use the CDP approach, which works in both modes.
How do I set the PDF output path?
Use the --print-to-pdf argument with a full path: --print-to-pdf=C:\temp\output.pdf. If you omit the path, Chrome saves to the default download folder.
Is there a way to print without waiting for the page to fully load?
You can use driver.Navigate().GoToUrl() and then immediately call the print command, but this may result in an incomplete PDF. It's better to wait for a specific element to be present.
What if I need to print a page that requires authentication?
Handle authentication before navigating to the page, or use cookies to maintain the session. The print command itself doesn't handle login.
Can I print to PDF without saving to disk?
Yes, using the CDP Page.printToPDF method returns the PDF as a base64-encoded string, which you can process in memory.