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.
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.
1@Test2public void printPageWithFirefox() throws IOException {3String userName = System.getenv("SAUCE_USERNAME");4String accessKey = System.getenv("SAUCE_ACCESS_KEY");5URL gridUrl = new URL("https://ondemand.us-west-1.saucelabs.com:443/wd/hub");6FirefoxOptions firefoxOptions = new FirefoxOptions();7firefoxOptions.setCapability("platformName", "Windows 10");8firefoxOptions.setCapability("browserVersion", "beta");910Map<String, Object> sauceOptions = new HashMap<>();11sauceOptions.put("name", "printPageWithFirefox");12sauceOptions.put("username", userName);13sauceOptions.put("accessKey", accessKey);14sauceOptions.put("geckodriverVersion", "0.30.0");15firefoxOptions.setCapability("sauce:options", sauceOptions);1617RemoteWebDriver driver = new RemoteWebDriver(gridUrl, firefoxOptions);18Path printPage = Paths.get("src/test/screenshots/PrintPageFirefox.pdf");1920driver.get("https://www.saucedemo.com/v1/inventory.html");21Pdf print = driver.print(new PrintOptions());22Files.write(printPage, OutputType.BYTES.convertFromBase64Png(print.getContent()));23driver.quit();24}
1@Test2public void printPageWithChrome() throws IOException {3String userName = System.getenv("SAUCE_USERNAME");4String accessKey = System.getenv("SAUCE_ACCESS_KEY");5URL gridUrl = new URL("https://ondemand.us-west-1.saucelabs.com:443/wd/hub");6ChromeOptions chromeOptions = new ChromeOptions();7// PrintToPDF is only supported in headless mode8chromeOptions.setHeadless(true);9chromeOptions.setCapability("platformName", "Windows 10");10chromeOptions.setCapability("browserVersion", "latest");1112Map<String, Object> sauceOptions = new HashMap<>();13sauceOptions.put("name", "printPageWithChrome");14sauceOptions.put("username", userName);15sauceOptions.put("accessKey", accessKey);16chromeOptions.setCapability("sauce:options", sauceOptions);1718RemoteWebDriver driver = new RemoteWebDriver(gridUrl, chromeOptions);19Path printPage = Paths.get("src/test/screenshots/PrintPageChrome.pdf");2021driver.get("https://www.saucedemo.com/v1/inventory.html");22Pdf print = driver.print(new PrintOptions());23Files.write(printPage, OutputType.BYTES.convertFromBase64Png(print.getContent()));24driver.quit();25}