Examples

HTML to PDF with Java and Selenium

Add Selenium to your Maven project

<dependency>
  <groupId>org.seleniumhq.selenium</groupId>
  <artifactId>selenium-java</artifactId>
  <version>4.34.0</version>
</dependency>

selenium-java 4.11+ includes Selenium Manager, which downloads the right chromedriver automatically. Check Maven Central for the latest version.

Convert HTML to PDF and save to file

import org.openqa.selenium.Pdf;
import org.openqa.selenium.PrintsPage;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.print.PrintOptions;

import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Base64;

public class Screenshot {
  public static void main(String[] args) throws Exception {
    ChromeOptions options = new ChromeOptions();
    options.addArguments("--headless=new");

    ChromeDriver driver = new ChromeDriver(options);

    String html = "<html><body><h1>Hello World</h1></body></html>";
    driver.get("data:text/html;charset=utf-8," + html);

    Pdf pdf = ((PrintsPage) driver).print(new PrintOptions());
    Files.write(Path.of("html.pdf"), Base64.getDecoder().decode(pdf.getContent()));

    driver.quit();
  }
}

Find out how to change the size of the viewport with Java and Selenium.

That was 26 lines of code — plus a browser to run in production

Keeping headless browsers fed, patched and scaled is a job in itself. We built Urlbox so the same screenshot is one API call:

curl "https://api.urlbox.com/v1/YOUR_API_KEY/png?url=https://example.com"

Try the Urlbox screenshot API — free trial, no browser babysitting.