Print Page as PDF

Selenium 4 will allow users to print a page as a PDF through Chrome, Firefox, and Edge.

The following Java example will show how a url is loaded and then printed as a PDF. For additional examples in multiple languages, check our our Selenium 4 Documentation.

Firefox

Something important to note is that GeckoDriver 0.30.0 or higher is needed to use Firefox with Selenium 4. At the moment, Firefox 93 (beta) is needed.

@Test
public void printPageWithFirefox() throws IOException {
	String userName = System.getenv("SAUCE_USERNAME");
	String accessKey = System.getenv("SAUCE_ACCESS_KEY");
	URL gridUrl = new URL("https://ondemand.us-west-1.saucelabs.com:443/wd/hub");
	FirefoxOptions firefoxOptions = new FirefoxOptions();
	firefoxOptions.setCapability("platformName", "Windows 10");
	firefoxOptions.setCapability("browserVersion", "beta");

        Map<String, Object> sauceOptions = new HashMap<>();
	sauceOptions.put("name", "printPageWithFirefox");
	sauceOptions.put("username", userName);
	sauceOptions.put("accessKey", accessKey);
	sauceOptions.put("geckodriverVersion", "0.30.0");
	firefoxOptions.setCapability("sauce:options", sauceOptions);

        RemoteWebDriver driver = new RemoteWebDriver(gridUrl, firefoxOptions);
	Path printPage = Paths.get("src/test/screenshots/PrintPageFirefox.pdf");

        driver.get("https://www.saucedemo.com/v1/inventory.html");
	Pdf print = driver.print(new PrintOptions());
	Files.write(printPage, OutputType.BYTES.convertFromBase64Png(print.getContent()));
	driver.quit();
}

Chrome

@Test
public void printPageWithChrome() throws IOException {
	String userName = System.getenv("SAUCE_USERNAME");
	String accessKey = System.getenv("SAUCE_ACCESS_KEY");
	URL gridUrl = new URL("https://ondemand.us-west-1.saucelabs.com:443/wd/hub");
	ChromeOptions chromeOptions = new ChromeOptions();
	// PrintToPDF is only supported in headless mode
	chromeOptions.setHeadless(true);
	chromeOptions.setCapability("platformName", "Windows 10");
	chromeOptions.setCapability("browserVersion", "latest");

        Map<String, Object> sauceOptions = new HashMap<>();
	sauceOptions.put("name", "printPageWithChrome");
	sauceOptions.put("username", userName);
	sauceOptions.put("accessKey", accessKey);
	chromeOptions.setCapability("sauce:options", sauceOptions);

        RemoteWebDriver driver = new RemoteWebDriver(gridUrl, chromeOptions);
	Path printPage = Paths.get("src/test/screenshots/PrintPageChrome.pdf");

        driver.get("https://www.saucedemo.com/v1/inventory.html");
	Pdf print = driver.print(new PrintOptions());
	Files.write(printPage, OutputType.BYTES.convertFromBase64Png(print.getContent()));
	driver.quit();
}

Check out our comprehensive guide to Selenium 4 for more details.





Written by

Diego Molina and Titus Fortner