Java HTML to PDF API guide

Use the Java HttpClient API to generate PDFs from Spring Boot services, jobs, or CLI tools.

EndpointPOST https://api.html2pdf.app/v1/generate
AuthenticationX-API-Key: <your-api-key>

Overview

Send the API request with Java standard library classes and write the returned byte array to a PDF file.

The API accepts a JSON request body. Send either a public URL or inline HTML in the required html parameter. For normal synchronous conversions, the response body is the generated PDF and should be saved as binary data.

Requirements

  • Java 11 or newer
  • An html2pdf.app API key available to the JVM
  • A backend service, worker, or command line entry point

Quick start

Replace <your-api-key> or the environment variable with your html2pdf.app API key, then run the example from a trusted backend environment.

Read the successful response as bytes and write them to document.pdf.

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

public class GeneratePdf {
    public static void main(String[] args) throws IOException, InterruptedException {
        String payload = "{\"html\":\"https://www.example.com\"}";

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.html2pdf.app/v1/generate"))
                .header("Content-Type", "application/json")
                .header("X-API-Key", System.getenv("HTML2PDF_API_KEY"))
                .POST(HttpRequest.BodyPublishers.ofString(payload))
                .build();

        HttpClient client = HttpClient.newHttpClient();
        HttpResponse<byte[]> response = client.send(
                request,
                HttpResponse.BodyHandlers.ofByteArray()
        );

        if (response.statusCode() < 200 || response.statusCode() >= 300) {
            throw new IOException("PDF generation failed: " + response.statusCode());
        }

        Files.write(Path.of("document.pdf"), response.body());
    }
}

Java examples

These examples cover the next common production flows: generating from inline HTML with options and queuing a callback job.

1. Generate with layout options

Add format, margins, and media options to control the generated PDF layout.

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

public class GenerateInvoicePdf {
    public static void main(String[] args) throws IOException, InterruptedException {
        String payload = "{"
                + "\"html\":\"<h1>Invoice</h1><p>Total: $240.00</p>\","
                + "\"format\":\"A4\","
                + "\"media\":\"print\","
                + "\"marginTop\":40,"
                + "\"marginRight\":32,"
                + "\"marginBottom\":40,"
                + "\"marginLeft\":32,"
                + "\"filename\":\"invoice.pdf\""
                + "}";

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.html2pdf.app/v1/generate"))
                .header("Content-Type", "application/json")
                .header("X-API-Key", System.getenv("HTML2PDF_API_KEY"))
                .POST(HttpRequest.BodyPublishers.ofString(payload))
                .build();

        HttpResponse<byte[]> response = HttpClient.newHttpClient().send(
                request,
                HttpResponse.BodyHandlers.ofByteArray()
        );

        if (response.statusCode() < 200 || response.statusCode() >= 300) {
            throw new IOException("PDF generation failed: " + response.statusCode());
        }

        Files.write(Path.of("invoice.pdf"), response.body());
    }
}

2. Submit an asynchronous job

Send callBackUrl and state when a separate webhook should receive the generated PDF.

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class QueuePdf {
    public static void main(String[] args) throws IOException, InterruptedException {
        String payload = "{"
                + "\"html\":\"https://www.example.com/report\","
                + "\"callBackUrl\":\"https://your-app.com/webhooks/html2pdf\","
                + "\"state\":\"report-1042\""
                + "}";

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.html2pdf.app/v1/generate"))
                .header("Content-Type", "application/json")
                .header("X-API-Key", System.getenv("HTML2PDF_API_KEY"))
                .POST(HttpRequest.BodyPublishers.ofString(payload))
                .build();

        HttpResponse<String> response = HttpClient.newHttpClient().send(
                request,
                HttpResponse.BodyHandlers.ofString()
        );

        if (response.statusCode() < 200 || response.statusCode() >= 300) {
            throw new IOException("Unable to queue PDF job: " + response.body());
        }
    }
}

Request options

Most integrations start with html and then add options as the document design becomes more specific.

  • html is required and accepts a public URL or raw HTML.
  • format, landscape, width, and height control page size.
  • marginTop, marginRight, marginBottom, and marginLeft control whitespace around the rendered page.
  • media selects screen or print CSS rendering.
  • callBackUrl switches the request to asynchronous generation and sends the completed PDF to your webhook.

See the full API parameter reference for every supported field.

Troubleshooting

  • Use BodyHandlers.ofByteArray for synchronous PDF responses.
  • Store the API key in environment configuration or your secret manager.
  • Use a JSON library such as Jackson in production when payloads become dynamic.

If the generated document is blank or missing styles, first confirm that the source URL is public and that required CSS, fonts, and images are reachable by the rendering service.