Skip to content

Guide · Java

Convert HTML to PDF in Java

Chromium makes the best HTML-to-PDF converter, and the worst dependency: hundreds of megabytes, fonts to install, zombie processes to reap. This Java program sends an HTML file to the Formfeed API instead and saves what Chromium prints.

Free plan with 100 units a month, no credit card

What you need

  • An API key. Create one in the app under API keys and export it as FORMFEED_API_KEY. A test key (ff_test_…) is right for trying things out. See the quick start.
  • Java. You need Java 17 or newer; java.net.http.HttpClient and text blocks are part of the JDK.
  • An HTML file. invoice.html next to the program: a complete document with its CSS inline or linked. A sample is further down.

The program

The program reads invoice.html, posts it with the paper size and the margins, waits for the result when the API answers 202, stops with the API’s message when something is wrong, and saves the PDF.

Render.javaJava
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;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Render {
  static final String ENDPOINT = "https://api-eu.formfeed.dev/v1/renders";
  static final HttpClient CLIENT = HttpClient.newHttpClient();

  public static void main(String[] args) throws Exception {
    String html = Files.readString(Path.of("invoice.html"));

    // the JDK has no JSON library: the body is a text block, and a project would use Jackson or Gson
    String body = """
        {
          "html": %s,
          "settings": {"paper":{"format":"A4"},"margin":{"top":"20mm","right":"18mm","bottom":"20mm","left":"18mm"}}
        }
        """.formatted(quote(html));

    HttpResponse<String> response = send(HttpRequest.newBuilder(URI.create(ENDPOINT)).POST(HttpRequest.BodyPublishers.ofString(body)));

    // not done within 60 seconds: the answer is 202 and the render goes on in the background;
    // its result answers the same way until the render has finished
    while (response.statusCode() == 202) {
      Thread.sleep(2000);
      response = send(HttpRequest.newBuilder(URI.create(ENDPOINT + "/" + field(response.body(), "id") + "/result")));
    }

    // every error is a problem document (RFC 9457) with a title and a detail
    if (response.statusCode() >= 400) {
      System.err.println(response.body());
      System.exit(1);
    }

    String render = response.body();
    CLIENT.send(HttpRequest.newBuilder(URI.create(field(render, "download_url"))).build(),
        HttpResponse.BodyHandlers.ofFile(Path.of("invoice.pdf")));
    System.out.println(field(render, "id") + " " + field(render, "page_count") + " page(s), " + field(render, "units") + " unit(s)");
  }

  /** One call to the API with the key; the download goes to a signed URL without it. */
  static HttpResponse<String> send(HttpRequest.Builder request) throws Exception {
    return CLIENT.send(request
        .header("Authorization", "Bearer " + System.getenv("FORMFEED_API_KEY"))
        .header("Content-Type", "application/json")
        .build(), HttpResponse.BodyHandlers.ofString());
  }

  /** The first value of a field anywhere in a JSON text; a project would use Jackson or Gson instead. */
  static String field(String json, String name) {
    Matcher m = Pattern.compile("\"" + name + "\"\\s*:\\s*(?:\"([^\"]*)\"|([^,}\\s]+))").matcher(json);
    return m.find() ? (m.group(1) != null ? m.group(1) : m.group(2)) : "";
  }

  /** A JSON string literal. */
  static String quote(String text) {
    StringBuilder out = new StringBuilder("\"");
    for (char c : text.toCharArray()) {
      if (c == '"' || c == '\\') out.append('\\').append(c);
      else if (c < 0x20) out.append(String.format("\\u%04x", (int) c));
      else out.append(c);
    }
    return out.append('"').toString();
  }
}

Run it

It prints the render’s id, the page count and the units it cost, and invoice.pdf lies next to the program.

Shell
export FORMFEED_API_KEY=ff_test_...
java Render.java

What is particular about Java

  • No JSON library in the JDK. To stay free of dependencies the body is a text block, and the values the program needs from JSON (the render’s id and download_url, an invoice number) are read with a regular expression. In a project, build the body and read the answer with Jackson or Gson.
  • Single-file launch. java Render.java compiles and runs in one step, so trying it needs no build tool.
  • Straight to disk. BodyHandlers.ofFile streams the PDF into the file without holding it in memory.

An HTML file that prints well

The HTML is printed as it is, with the print rules Chromium supports. Web fonts load from a <link>, and two CSS rules keep a long table readable across pages:

invoice.htmlHTML
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap">
    <style>
      body { font-family: 'Inter', sans-serif; font-size: 10pt; color: #1e293b; }
      h1 { font-size: 20pt; color: #312e81; }
      table { width: 100%; border-collapse: collapse; }
      td, th { padding: 2mm; border-bottom: 1px solid #e2e8f0; text-align: left; }
      thead { display: table-header-group; } /* repeats the head row on every page */
      tr { break-inside: avoid; }
    </style>
  </head>
  <body>
    <h1>Invoice 2026-0042</h1>
    <table>
      <thead><tr><th>Item</th><th>Amount</th></tr></thead>
      <tbody><tr><td>Consulting</td><td>960.00 €</td></tr></tbody>
    </table>
  </body>
</html>

What the settings control

  • Paper. paper.format takes A4, Letter and the other common names, landscape: true turns it, and width with height sets a custom size such as a 100 × 150 mm label.
  • Margins. Per side, as CSS lengths such as 20mm. A background that should reach the edge needs margins of 0.
  • Header and footer. header.html and footer.html repeat on every page inside the top and bottom margin; elements with the classes pageNumber and totalPages show the page numbers.
  • Placeholders. Add "engine": "jinja2" (or liquid, handlebars) and a data object, and {{ … }} in the HTML is filled before printing, with all helpers for money, dates, barcodes and charts.

When a template is the better tool

Sending HTML is right for pages your application already renders. When the document is yours to design (invoices, certificates, reports), a stored template gives you an editor with a page-accurate preview, versions, and a request that carries only data. The PDF invoice guide of this language shows that variant.

When the API says no

  • One shape for every error. Errors are problem documents (RFC 9457) with type, title, status, detail, a stable code and the request_id to quote to support; the type URL leads to a page about that error. The list is in the error reference.
  • The usual ones. 401 unauthorized for a missing or revoked key, 404 template_not_found for a wrong template name, 422 template_runtime_error when the template fails on the data, 429 rate_limited above the plan’s requests per second, 402 quota_exceeded when the Free plan’s units are used up (a paid plan bills extra units up to its hard cap).
  • Retry safely. Send an Idempotency-Key header with the POST, and repeat the request with the same key when you do not know whether the first attempt arrived: for 24 hours the key returns the first answer instead of rendering and billing again. The answer is stored once the first attempt has been answered, so do not retry while it may still run; and problems below 500 are stored too, so a corrected request needs a new key.

The job around this program

This guide is one program. What the job needs around it, from the template to the limits and the price, is on the page HTML to PDF API.

More Java guides

FAQ

Can it render a URL instead of an HTML string?
Yes: send url instead of html. It must be a public https page, which is loaded without your cookies or headers; addresses in private networks are refused, and a page that does not load within 30 seconds fails with navigation_failed.
How large may the HTML be?
Up to 5 MB per request. Images and fonts are fetched by URL and do not count towards that. Limits per plan are in the docs.
Does JavaScript in the page run?
Yes, Chromium runs it before printing, which is how charts render. It waits until the network has been idle, for at most 30 seconds, so a page that keeps loading fails with render_timeout rather than hanging.

HTML to PDF in other languages

Start rendering today

The free plan includes 100 units a month and free test renders. Change plans when you need more.