Guides / Java

Convert HTML to PDF in Java

Invoices, contracts, reports, certificates: every product eventually needs PDFs, and Java PDF libraries make you hand-position every box. RasterKit prints through real Chromium instead — write ordinary HTML and CSS, POST it, get a finished PDF back.

Because it's a print pipeline rather than a drawing API, you keep your existing templates and stylesheets: flexbox, grid, web fonts, page-break CSS, repeating headers and footers with page numbers all just work.

1. Get an API key

Sign up free (magic link, no card) — your key is shown right after sign-in. You get 100 renders/month free across screenshots, PDFs, and images.

2. Make the request

import java.net.URI;
import java.net.http.*;
import java.nio.file.*;
import java.time.Duration;

public class Render {
    public static void main(String[] args) throws Exception {
        String body = """
            {"url": "https://example.com/invoice/42", "format": "A4", "print_background": true}""";
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://rasterkit.com/v1/pdf"))
            .timeout(Duration.ofSeconds(60))
            .header("x-api-key", System.getenv("RASTERKIT_API_KEY"))
            .header("content-type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(body))
            .build();

        HttpResponse<byte[]> res = HttpClient.newHttpClient()
            .send(request, HttpResponse.BodyHandlers.ofByteArray());
        if (res.statusCode() != 200) {
            throw new RuntimeException("Render failed: " + res.statusCode() + " " + new String(res.body()));
        }
        Files.write(Path.of("document.pdf"), res.body());
        System.out.println("Saved document.pdf");
    }
}

The response body is the file itself — no JSON envelope to unwrap, no second download request. Errors come back as JSON with a stable error code.

3. Tune the output

The PDF API reference documents every parameter. The ones people reach for first:

Use cases

FAQ

How do I add page numbers?

Pass footer_template with Chromium's built-in classes, e.g. <span class="pageNumber"></span> / <span class="totalPages"></span>.

Why are my background colors missing?

Browsers skip backgrounds when printing by default. RasterKit sets print_background: true by default — if you turned it off, turn it back on.

Can I control page breaks?

Yes — standard CSS (break-inside: avoid, break-after: page) is respected, and prefer_css_page_size lets your @page rules define the paper size.

Related guides

Get your free API key →