Skip to content
shotsmith
Features Docs Guides Pricing Changelog Sign inStart free

How to take website screenshots in Java

Capture website screenshots and PDFs from Java with the built-in HttpClient, plus a Spring Boot controller that streams the image.

4 min read

Java’s screenshot options usually involve Selenium or Playwright for Java, both of which need a browser installed and maintained wherever your code runs. With shotsmith you use the java.net.http.HttpClient that ships with Java 11 and later, and Chrome runs on our side.

1. Get an API key

Create a free account (100 renders a month, no card) and set your access key as the environment variable SHOTSMITH_ACCESS_KEY.

2. Save a screenshot

BodyHandlers.ofFile streams the image straight to disk. Check the status code: on errors, the file holds a JSON error instead of an image.

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Path;

public class Capture {
    public static void main(String[] args) throws Exception {
        var client = HttpClient.newHttpClient();
        var request = HttpRequest.newBuilder(URI.create(
            "https://shotsmith.dev/v1/take?access_key=YOUR_ACCESS_KEY&url=https%3A%2F%2Fshotsmith.dev%2Fsample&full_page=true&block_cookie_banners=true&format=png"
        )).build();

        var res = client.send(request, HttpResponse.BodyHandlers.ofFile(Path.of("capture.png")));
        if (res.statusCode() != 200) {
            throw new RuntimeException("HTTP " + res.statusCode());
        }
    }
}

3. A Spring Boot endpoint

This controller returns a WebP thumbnail of any URL. It URL-encodes every parameter, caches successful images in the browser for an hour, and passes errors through with their original status. cache=true makes repeat requests within four hours instant and free.

import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;

import org.springframework.http.CacheControl;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SpringScreenshotController {

    private final HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
    private final String accessKey = System.getenv("SHOTSMITH_ACCESS_KEY");

    // GET /thumbnail?url=https://shotsmith.dev/sample
    @GetMapping("/thumbnail")
    public ResponseEntity<byte[]> thumbnail(@RequestParam String url) throws Exception {
        String query = "access_key=" + encode(accessKey)
            + "&url=" + encode(url)
            + "&format=webp&image_width=640&block_cookie_banners=true&cache=true";

        HttpRequest request = HttpRequest.newBuilder(URI.create("https://shotsmith.dev/v1/take?" + query))
            .timeout(Duration.ofSeconds(30))
            .build();
        HttpResponse<byte[]> res = http.send(request, HttpResponse.BodyHandlers.ofByteArray());

        // On errors the body is JSON with error_code and error_message: pass it on with the same status.
        String contentType = res.headers().firstValue("Content-Type").orElse("application/octet-stream");
        return ResponseEntity.status(res.statusCode())
            .contentType(MediaType.parseMediaType(contentType))
            .cacheControl(res.statusCode() == 200 ? CacheControl.maxAge(Duration.ofHours(1)).cachePublic() : CacheControl.noStore())
            .body(res.body());
    }

    private static String encode(String value) {
        return URLEncoder.encode(value, StandardCharsets.UTF_8);
    }
}

Anyone who can call this endpoint spends your renders. Restrict the url parameter to hosts you expect, or put it behind authentication.

4. PDFs from your own HTML

For invoices and reports, POST your HTML as JSON and write the PDF to a file:

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Path;

public class Request {
    public static void main(String[] args) throws Exception {
        var body = """
            {
              "html": "<h1>Invoice #1042</h1>",
              "format": "pdf",
              "pdf_paper_format": "a4",
              "pdf_print_background": true
            }
            """;

        var request = HttpRequest.newBuilder(URI.create("https://shotsmith.dev/v1/take"))
            .header("X-Access-Key", "YOUR_ACCESS_KEY")
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(body))
            .build();

        var res = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofFile(Path.of("invoice.pdf")));
        if (res.statusCode() != 200) {
            throw new RuntimeException("HTTP " + res.statusCode());
        }
    }
}

Real templates are long: build the JSON with your JSON library of choice (Jackson, Gson) rather than a text block, so quotes and newlines are escaped for you.

5. Errors and long renders

Errors are JSON with a stable error_code (see the error reference), and failed renders aren’t billed. Synchronous requests must finish within 18 seconds. For slow pages, videos and batches, use async rendering with webhooks.