Guide · Java
Convert Markdown to PDF in Java
A report your code writes, release notes or an answer from a model are Markdown already. This Java program sends a Markdown file to the Formfeed API as it is and saves the PDF, styled by the `document` theme and with raw HTML in the text shown as text, so it never runs.
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. - A Markdown file.
report.mdnext to the program, up to 1 MB. A sample is further down.
The program
The program reads report.md, posts it as markdown with bookmarks from its headings, 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 markdown = Files.readString(Path.of("report.md"));
// the JDK has no JSON library: the body is a text block, and a project would use Jackson or Gson
String body = """
{
"markdown": %s,
"settings": {"pdf":{"outline":true}}
}
""".formatted(quote(markdown));
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("report.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 report.pdf lies next to the program.
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.
A Markdown file with a title
The front matter gives the PDF its title and author; without one the first heading is the title. A line \newpage starts a new page, and a link to a heading works inside the PDF:
---
title: Release notes 2.4
author: Fennlor Studio GmbH
---
# Release notes 2.4
## What is new
- Faster previews, see [the numbers](#numbers)
- Footnotes in the export[^1]
- [x] Tested on every plan
## Numbers
| Step | Before | After |
| :------ | -----: | -----: |
| Preview | 840 ms | 310 ms |
| Export | 2.1 s | 1.4 s |
\newpage
## Thanks
To everyone who reported a problem.
[^1]: From version 2.4 on.What the settings control
- Look.
settings.markdown.themeisdocument, which styles the text, in the brand kit’s fonts and colour where the workspace has one, ornone;settings.markdown.csscomes after it. - Raw HTML. Shown as text by default.
settings.markdown.html: "allow"writes it as it stands, for Markdown you wrote yourself, never for text from your users or a model. - Line breaks.
settings.markdown.breaks: truemakes a single line break a line break, for text from a chat. - Paper, header and footer.
paper,margin,header.htmlandfooter.htmlwork as for HTML; elements with the classespageNumberandtotalPagesshow the page numbers.
Placeholders in the Markdown
Add "engine": "jinja2" (or liquid, handlebars) and a data object, and {{ … }} in the text is filled before it is read as Markdown, with all helpers. The Markdown guide has the rest.
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 Markdown to PDF API.
More Java guides
FAQ
- Which Markdown does it read?
- GitHub Flavored Markdown: tables, task lists, strikethrough and autolinks, plus footnotes and a front matter block. Heading ids follow GitHub’s rule, so links between headings work inside the PDF.
- How large may the Markdown be?
- Up to 1 MB of UTF-8 per request, and a stylesheet in
settings.markdown.cssup to 256 kB. Limits per plan are in the docs. - Where do pictures come from?
- A picture named by a bare file name, such as
logo.png, is a file of the workspace’s file library; a publichttpsaddress or adata:image/address works as well.formfeed pdf convert report.mdsends the pictures beside the file along by itself.