Examples
HTML to PNG 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 PNG and save to file
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
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);
File image = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
Files.copy(image.toPath(), Path.of("html.png"));
driver.quit();
}
} Find out how to change the size of the viewport with Java and Selenium.
That was 25 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.