Guide · Java
Generate a PDF invoice from JSON in Java
Your Java code sends the facts of an invoice (customer, lines, VAT rate) and gets back a finished PDF. Sums, number formats, the due date and the payment QR code are the template’s job, so none of that logic ends up in your application.
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.HttpClientand text blocks are part of the JDK. - The template.
invoice-defrom the invoice example: copy it into your workspace from the example’s page, which keeps the nameinvoice-deand publishes the copy, or push the folder with the CLI (formfeed templates push --publish). A render uses the published version. - The data. The example’s
data.jsonnext to the program. It holds the company, the customer and two invoice lines, and no totals.
The program
The program reads data.json, posts it with the template’s name and a file name built from the invoice number, waits for the result when the API answers 202, stops with the API’s message when something is wrong, and saves the PDF.
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 data = Files.readString(Path.of("data.json"));
// the JDK has no JSON library: field() takes the first "number" of the data, which is invoice.number
String filename = "invoice-" + field(data, "number") + ".pdf";
// the body is a text block, and a project would use Jackson or Gson
String body = """
{
"template": "invoice-de",
"data": %s,
"filename": %s
}
""".formatted(data, quote(filename));
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. With a key that starts with ff_test_ the render is not metered; on the Free plan it carries a small watermark.
export FORMFEED_API_KEY=ff_test_...
java Render.javaWhat 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
idanddownload_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.javacompiles and runs in one step, so trying it needs no build tool. - Straight to disk.
BodyHandlers.ofFilestreams the PDF into the file without holding it in memory.
What the template does with the JSON
The request carries no derived numbers, which is the point of rendering from a template:
- Totals.
invoice.lines | sum('total')adds the lines, and VAT and gross follow frominvoice.vat_rate. - Formats. With the template’s locale
de-DE,moneyprints3.760,40 €anddate('dd.MM.yyyy')prints10.09.2026;dateAdd(14, 'days')sets the due date. - GiroCode.
epcQrdraws the SEPA payment code from name, IBAN, BIC, amount and reference. - File name. is not the template’s job. The API takes
filenameas written and fills in no template expressions, so the program buildsinvoice-2026-0042.pdffrom the invoice number, and the download carries that name. Characters outside A–Z, a–z, 0–9,.,-,_,(,)and the space become_.
From one invoice to many
An invoice run is a batch: one request with up to 1,000 documents, one zip at the end, and a webhook when it is done. See batches. For documents that take longer than a few seconds, render asynchronously and let a webhook report back.
When the API says no
- One shape for every error. Errors are problem documents (RFC 9457) with
type,title,status,detail, a stablecodeand therequest_idto quote to support; thetypeURL leads to a page about that error. The list is in the error reference. - The usual ones.
401 unauthorizedfor a missing or revoked key,404 template_not_foundfor a wrong template name,422 template_runtime_errorwhen the template fails on the data,429 rate_limitedabove the plan’s requests per second,402 quota_exceededwhen the Free plan’s units are used up (a paid plan bills extra units up to its hard cap). - Retry safely. Send an
Idempotency-Keyheader 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 Invoice PDF API.
More Java guides
FAQ
- Can I send the invoice HTML instead of using a stored template?
- Yes, put it in
htmland leavetemplateout; the HTML-to-PDF guide of this language shows it. A stored template adds versions, a preview with your sample data and release channels. - How long is the download URL valid?
- A signed link is valid for at most seven days and never longer than the file is kept, which your plan’s retention decides (a workspace setting or
expires_incan only shorten it).GET /renders/{id}issues a fresh link at any time, so store the render’s id, not the URL. Withaccess: "public"the link lasts as long as the file. Details in the rendering docs. - What does a render cost?
- One unit for every started five pages of a PDF, so one to five pages cost one unit and six to ten cost two. Test renders are free. See pricing.