Examples
Screenshot the viewport 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.
Take a screenshot of the viewport 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);
driver.get("https://www.htmltoimage.com/demo");
File image = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
Files.copy(image.toPath(), Path.of("viewport.png"));
driver.quit();
}
} Find out how to change the size of the viewport with Java and Selenium.
That was 23 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.