Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate PDF with selenium chrome driver

To generate PDF from a HTML file, I want to use selenium Chrome driver.

I tried it with command line :

chrome.exe --headless --disable-gpu --print-to-pdf   file:///C:invoiceTemplate2.html

and it works perfectly, So I wanted to do that with JAVA and here's my code :

System.setProperty("webdriver.chrome.driver", "C:/work/chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless", "--disable-gpu", "--print-to-pdf",
            "file:///C:/invoiceTemplate2.html");
WebDriver driver = new ChromeDriver(options);
driver.quit();

The server is started with no problem, but chrome is opened with multiple tabs with the arguments I specified in Options.

Any solution to this ? thx.

like image 353
Moatez Bouhdid Avatar asked Nov 19 '22 01:11

Moatez Bouhdid


1 Answers

This can indeed be done with Selenium and ChromeDriver (tested with Chrome version 85), but using the "print-to-pdf" option when starting Chrome from the webdriver is not the solution.

The thing to do is to use the command execution functionality of ChromeDriver:

https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/remote/RemoteWebDriver.html#execute-java.lang.String-java.util.Map-

There is a command called Page.printToPDF that provides PDF output functionality. A dictionary containing the item "data", with the resulting PDF in base-64-encoded format, is returned.

Unfortunately, I do not have a full Java example, but in this answer, there is a C# example (Selenium methods are named differently in C# compared to Java, but the principle should be the same):

https://stackoverflow.com/a/63970792/2416627

The Page.printToPDF command in Chrome is documented here:

https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF

like image 103
Otto G Avatar answered Dec 10 '22 23:12

Otto G