2

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

SanLW
  • 91
  • 7
  • I was having the same problem, and the problem went away when I upgraded to a newer version of Firefox. – Steve Jorgensen Sep 30 '22 at 09:58
  • @SteveJorgensen Then I should give it a try again. I gave up the idea of using headless browser and went for a 3rd party service instead. But this can cut some cost. Thanks! – SanLW Oct 05 '22 at 05:26

0 Answers0