Skip to content

Guide · Java

Async PDF rendering with a verified webhook in Java

A long report should not hold an HTTP request open. In async mode the API answers at once with a queued render and calls your endpoint when the PDF is ready. This guide has both halves in Java: the request, and a receiver that accepts only deliveries Formfeed really signed.

Free plan with 100 units a month, no credit card

Report with a chart
What comes out: Report with a chart

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 11 or newer, Maven, and the dev.formfeed:formfeed package from Maven Central, which brings Jackson.
  • The template. revenue-report from the report example, and its data.json next to the program.
  • A secret. 16 to 200 random characters in FORMFEED_WEBHOOK_SECRET, known to both programs. It signs the deliveries of this render, retries included.
  • A public URL. Replace https://example.com/hooks/formfeed with your endpoint. While developing, formfeed listen forwards deliveries to localhost without a tunnel.
InstallShell
# a pom.xml with the one dependency, and the class path Maven resolves for it
cat > pom.xml <<'EOF'
<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>example</groupId>
  <artifactId>formfeed-guide</artifactId>
  <version>1</version>
  <dependencies>
    <dependency>
      <groupId>dev.formfeed</groupId>
      <artifactId>formfeed</artifactId>
      <version>0.3.35</version>
    </dependency>
  </dependencies>
</project>
EOF
mvn -q dependency:build-classpath -Dmdep.outputFile=classpath.txt

The program

The request names the template, switches to mode: "async" and says where to report. The answer comes back immediately with the status queued.

Render.javaJava
import com.fasterxml.jackson.databind.ObjectMapper;
import dev.formfeed.Formfeed;
import dev.formfeed.RenderRequest;
import java.io.File;

public class Render {
  public static void main(String[] args) throws Exception {
    var formfeed = Formfeed.builder().apiKey(System.getenv("FORMFEED_API_KEY")).build();
    var data = new ObjectMapper().readTree(new File("data.json"));

    var request = RenderRequest.template("revenue-report")
        .data(data)
        .mode("async")
        .webhookUrl("https://example.com/hooks/formfeed")
        .webhookSecret(System.getenv("FORMFEED_WEBHOOK_SECRET"));
    // a problem answer (4xx, 5xx) throws a FormfeedException with the API's code and detail
    var render = formfeed.renders().create(request);
    System.out.println(render.getId() + " " + render.getStatus()); // queued: the webhook reports the rest
  }
}

Run it

It prints the render’s id and queued. A few seconds later your endpoint receives render.completed with the full render, its download_url included, or render.failed with the reason.

Shell
export FORMFEED_API_KEY=ff_test_...
export FORMFEED_WEBHOOK_SECRET=$(openssl rand -hex 24)
java -cp "$(cat classpath.txt)" Render.java

What is particular about Java

  • A builder in, getters out. The request is a RenderRequest (RenderRequest.template("…") with setters such as .data(…) and .filename(…), and .set(…) for any other field) or a map with the fields the API documents (renders().batch, pdf().protect); the answer is an immutable object with getters: getDownloadUrl(), getPageCount() and getUnits(), and getRaw() holds the whole answer.
  • Retries are built in. The client sends an Idempotency-Key with every render and retries 429, 503 and network errors up to three times with backoff, with the same key: a retry of a request that was answered already gets that answer back instead of a second render.
  • Jackson for the JSON. The SDK writes requests and reads answers with Jackson databind 2.x, which a Spring application has already: data can be a map, a Jackson tree or an object of your own that Jackson writes as a JSON object, and objectMapper(…) on the builder hands the SDK your application’s mapper.
  • One source file. The java launcher compiles and runs a single source file in one step, with the SDK and Jackson on the class path from classpath.txt. In your project the dependency goes into pom.xml, or with Gradle implementation("dev.formfeed:formfeed:0.3.35").

The receiver

It listens on port 8080, reads the raw body, checks the signature and the age of the timestamp, and only then looks at the JSON. A delivery that fails the check gets 401.

Hook.javaJava
import com.sun.net.httpserver.HttpServer;
import dev.formfeed.Render;
import dev.formfeed.Webhook;
import dev.formfeed.WebhookEvent;
import java.net.InetSocketAddress;

public class Hook {
  static final String SECRET = System.getenv("FORMFEED_WEBHOOK_SECRET");

  public static void main(String[] args) throws Exception {
    HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
    server.createContext("/hooks/formfeed", exchange -> {
      // the signature covers the bytes on the wire: read the raw body, never re-serialised JSON
      byte[] body = exchange.getRequestBody().readAllBytes();
      WebhookEvent event;
      try {
        // checks the HMAC and the five-minute tolerance, throws when either fails
        event = Webhook.parse(SECRET, exchange.getRequestHeaders().getFirst("Webhook-Signature"), body);
      } catch (IllegalArgumentException e) {
        exchange.sendResponseHeaders(401, -1);
        exchange.close();
        return;
      }

      Render render = Render.fromMap(event.getData());
      if (event.getType().equals("render.completed")) System.out.println("done " + render.getId() + " " + render.getDownloadUrl());
      if (event.getType().equals("render.failed")) System.out.println("failed " + render.getId());
      exchange.sendResponseHeaders(204, -1);
      exchange.close();
    });
    server.start();
  }
}

Start the receiver

Shell
FORMFEED_WEBHOOK_SECRET=… java -cp "$(cat classpath.txt)" Hook.java

Verifying in Java

  • One call verifies. Webhook.parse checks the HMAC, compared in constant time with MessageDigest.isEqual, and the five-minute tolerance, and throws IllegalArgumentException when either fails; Webhook.verify answers true or false instead.
  • In Spring. Take the body as @RequestBody byte[] (or String) and the header with @RequestHeader("Webhook-Signature"), and verify before your ObjectMapper maps anything: a body read into an object has lost the bytes the signature covers.

What arrives

A POST with Webhook-Signature: t=<unix seconds>,v1=<hex>, where the hex is HMAC-SHA256 over t, a dot and the raw body, keyed with your secret exactly as you have it, as UTF-8 bytes: the webhook_secret you sent, or a registered endpoint’s whole whsec_… string, prefix included. Every attempt is signed anew with its own t. Webhook-Id stays the same across retries, so it is your deduplication key. data is the render as GET /renders/{id} returns it:

POST /hooks/formfeedJSON
{
  "id": "evt_5b0c8e6f2d4a4c3e9b1a7f6e5d4c3b2a",
  "type": "render.completed",
  "created_at": "2026-09-18T10:42:00Z",
  "workspace_id": "3a6f…",
  "data": {
    "id": "rnd_7da09ab6cd9946b798c187c2a9350852",
    "status": "succeeded",
    "download_url": "https://cdn.formfeed.dev/o/eu/…/document.pdf?exp=…&sig=…",
    "page_count": 2,
    "units": 1,
    …
  }
}

Retries, and what your endpoint owes

  • Answer fast. A delivery succeeds with a 2xx within 10 seconds. Store the event and do the work afterwards.
  • Retries. Anything else, a redirect included, is retried after 1 minute, 5 minutes, 30 minutes, 2 hours and 12 hours: six attempts in all, over about 14 hours and 40 minutes. The same event can therefore arrive twice: deduplicate by Webhook-Id.
  • Without a secret. A webhook_url without webhook_secret is delivered unsigned. For signed deliveries of every render, register an endpoint once in the app or through POST /webhooks; it gets its own secret.
  • Try it locally. formfeed listen --forward-to http://localhost:8080/hooks/formfeed relays the events of your test renders to your machine, signed with the session’s own secret rather than webhook_secret: start the receiver with that one, which formfeed listen --print-secret prints (run it before the session, since it ends a running one). formfeed trigger render.completed --template revenue-report makes a real test render whose event you watch arrive. The key needs the webhook:listen scope. See developing webhooks locally.

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 Report PDF generation.

More Java guides

FAQ

Can I poll instead of receiving a webhook?
Yes: GET /renders/{id} until the status is succeeded or failed; the SDKs have waitFor, wait_for, WaitFor and WaitForAsync for it. A webhook saves the requests and reports sooner. See async and batch.
Why must the raw body be used?
The signature covers the bytes on the wire. Parsing and re-serialising JSON may reorder keys, change number formats or escape characters differently, and the HMAC of that text no longer matches.
What is the five-minute tolerance for?
It stops a captured delivery from being replayed later. It also means the clock of your server must be roughly right.

Async render with a webhook in other languages

Start rendering today

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