1 | initial version |
To create a PDF using the Selenium Chrome driver, you can follow the below steps:
ChromeOptions options = new ChromeOptions();
Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("plugins.always_open_pdf_externally", true);
options.setExperimentalOption("prefs", prefs);
WebDriver driver = new ChromeDriver(options);
driver
instance:driver.navigate().to("https://example.com");
executeCdpCommand()
method to send a command to Chrome. To create a PDF, send the following command:HashMap<String, Object> params = new HashMap<>();
params.put("landscape", false);
params.put("displayHeaderFooter", false);
params.put("printBackground", true);
params.put("preferCSSPageSize", true);
params.put("marginTop", 0);
params.put("marginBottom", 0);
params.put("marginLeft", 0);
params.put("marginRight", 0);
params.put("scale", 1);
driver.executeCdpCommand("Page.printToPDF", params);
printToPDF()
method, as shown below:byte[] pdfContent = driver.executeCdpCommand("Page.printToPDF", params).get("data").toString().getBytes();
try (FileOutputStream fos = new FileOutputStream("sample.pdf")) {
fos.write(pdfContent);
}