I want to get a pdf of a webpage using selenium WebDriver. I'm using FirefoxDriver because ChromeDriver has trouble calculating exact A4 size which leaves a white line at the bottom. Printing works fine with FirefoxDriver except it does not include background images.
public boolean fromHTML(String url) {
System.setProperty("webdriver.gecko.driver", "src/main/resources/geckodriver");
FirefoxOptions options = new FirefoxOptions();
options.addArguments("--headless", "--disable-gpu");
FirefoxDriver driver = new FirefoxDriver(options);
driver.manage().window().maximize();
driver.get(url);
PrintOptions printOptions = new PrintOptions();
printOptions.setBackground(true);
Pdf pdf = driver.print(printOptions);
try {
Files.write(Paths.get("./cert.pdf"), OutputType.BYTES.convertFromBase64Png(pdf.getContent()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
FirefoxDriver gets print(PrintOptions options) from https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/class-use/PrintsPage.html