Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To create a PDF using the Selenium Chrome driver, you can follow the below steps:

  1. First, you need to set the Chrome options to enable the printing of PDF files. You can do this by adding the following options to your Chrome driver:
ChromeOptions options = new ChromeOptions(); 
Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("plugins.always_open_pdf_externally", true);
options.setExperimentalOption("prefs", prefs);
  1. Once you have set the Chrome options, you can create a new Chrome driver using these options:
WebDriver driver = new ChromeDriver(options);
  1. Navigate to the webpage that you want to create the PDF of using the driver instance:
driver.navigate().to("https://example.com");
  1. To create the PDF, you can use the ChromeDevTools API through the driver instance. You can use the 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);
  1. This will create a PDF of the webpage and store it in the browser's memory. You can retrieve the PDF content using the printToPDF() method, as shown below:
byte[] pdfContent = driver.executeCdpCommand("Page.printToPDF", params).get("data").toString().getBytes();
  1. You can now save the PDF file to your desired location as follows:
try (FileOutputStream fos = new FileOutputStream("sample.pdf")) {
    fos.write(pdfContent);
}