Skip to content

Guide · Java

Create a ZUGFeRD / Factur-X e-invoice in Java

Between businesses in Germany, every company has had to be able to receive e-invoices since 2025; issuing them becomes mandatory in 2027 for businesses with more than €800,000 turnover in the year before, and in 2028 for all, with exceptions such as invoices up to €250. This Java program sends an invoice as JSON and gets back a ZUGFeRD / Factur-X file: the PDF people read, with the XML inside it that accounting software reads, both made from the same data and checked before you get the file.

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.
  • The template. e-rechnung from the e-invoice example: copy it into your workspace from the example’s page, or push the folder with the CLI (formfeed templates push --publish). Any invoice template works the same way once its data has an _invoice block.
  • The data. The example’s data.json next to the program: one _invoice block with seller, buyer, lines, the VAT breakdown and the totals, in the terms of the European standard EN 16931.
  • A plan with e-invoices. Live e-invoices need the Starter plan or above. With a test key (ff_test_…) every plan makes test e-invoices with a test mark on the page, the Free plan up to 20 a day.

The program

The program reads data.json, posts it with the template’s name and post.einvoice, waits for the result when the API answers 202, stops with the API’s message when something is wrong, and saves the e-invoice.

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 data = Files.readString(Path.of("data.json"));

    // the JDK has no JSON library: the body is a text block, and a project would use Jackson or Gson
    String body = """
        {
          "template": "e-rechnung",
          "data": %s,
          "post": {"einvoice":{"profile":"en16931"}}
        }
        """.formatted(data);

    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("e-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)) : "";
  }
}

Run it

It prints the render’s id, the page count and the units it cost (on a live key one more than the same PDF without the XML), and e-invoice.pdf lies next to the program. A PDF viewer shows the invoice, and its attachments show the factur-x.xml inside. With a test key the render is not metered, and every test e-invoice carries a test mark, on every plan.

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.

What makes the PDF an e-invoice

  • post.einvoice. turns the PDF into a PDF/A-3 that carries the invoice as factur-x.xml. The example template declares the same in its settings.json, so for this template the line is optional; for your own invoice template it is the one switch.
  • The _invoice block. Seller, buyer, lines, VAT breakdown and totals, named as in the standard; units and VAT categories are codes (HUR, S). The template prints the page from the same block, so the page and the XML cannot say different things.
  • The check. Before the file is delivered, the XML is held to the rules of EN 16931 and the PDF to PDF/A-3b. The report is in the render’s einvoice.validation, and a value the page does not show is listed in einvoice.display.missing.
  • ZUGFeRD or Factur-X. One specification under two names, and the same file. flavour decides only which name and release the render reports: ZUGFeRD 2.5 or Factur-X 1.09.

When the data is wrong

A block that breaks a rule fails the request with 422 einvoice_data_invalid before anything is rendered or counted. The problem lists every finding with its place in the data and the rule it breaks (BR-CO-15, …), and the program prints its title and detail. A file that fails the check is never delivered, and never replaced by a plain PDF.

What stays with you

Formfeed creates and checks the file. Sending it to your customer, archiving it and the VAT treatment of the invoice stay with you. When an e-invoice is required, with the official sources, is on the e-invoicing page; the fields and the rules are in the e-invoice docs.

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 Invoice PDF API.

More Java guides

FAQ

Which profile should I choose?
en16931, the default, carries every field of the European standard; basic is the smallest profile that is an invoice on its own. Any other profile is answered with einvoice_profile_unsupported.
Does Formfeed create XRechnung?
No. Formfeed writes ZUGFeRD / Factur-X: the XML inside a PDF/A-3. XRechnung and UBL are not available.
What does an e-invoice cost?
One unit on top of its render, so a one-page e-invoice costs two units. Live e-invoices need the Starter plan or above; on the Free plan, test renders make up to 20 a day. See pricing.
Can I have the XML as a file of its own?
xml: "both" in post.einvoice stores the XML beside the PDF as well, and the render links it as einvoice.xml_url. Inside the PDF it is there either way.

ZUGFeRD e-invoice in other languages

Start rendering today

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