How to Convert JSON to PDF with Java
This Java example sends JSON to the pdfRest Convert to PDF API Tool and receives a styled, tagged PDF. It demonstrates hierarchy presentation, document metadata, page setup, typography, multipart construction, and resource-response handling.
Why Convert JSON to PDF with Java?
Enterprise Java services exchange JSON for orders, decisions, events, and integration results. Those payloads are efficient application contracts, but they are poor review documents when someone must understand nested properties or retain the information with a business case.
Consider an order platform that receives a JSON decision from a fraud-screening service. Java can convert the response into a hierarchy-formatted PDF where decision fields, reason arrays, and nested account details remain visibly related. Operations staff can add the PDF to the order record while developers preserve the original payload for programmatic analysis.
Using the API keeps the Java application from maintaining a second reporting model for arbitrary JSON shapes. It can choose a readable hierarchy for operational review or normalized source for engineers, while applying the same metadata, page design, and tagging rules to both.
Java Code Example for Converting JSON to PDF
import io.github.cdimascio.dotenv.Dotenv;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.*;
import org.json.JSONObject;
public class PdfFromJson {
private static final String API_URL = "https://api.pdfrest.com";
private static final String DEFAULT_API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
public static void main(String[] args) throws IOException {
File inputFile = new File(args.length > 0 ? args[0] : "/path/to/sample.json");
Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load();
String apiKey = dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY);
JSONObject options =
new JSONObject(
"{\"title\":\"Structured Content Sample\",\"language\":\"en-US\",\"enable_tagging\":true,\"page_setup\":{\"size\":\"Letter\",\"orientation\":\"portrait\",\"margin\":{\"top\":36,\"right\":42,\"bottom\":36,\"left\":42}},\"style\":{\"font\":\"Arial\",\"heading_font\":\"Arial\",\"code_font\":\"Courier\",\"text_size\":11,\"text_color_rgb\":[34,34,34],\"heading_scale\":1.35,\"table\":{\"column_width_weights\":[2,3,2],\"keep_header_with_first_row\":true,\"repeat_headers_on_overflow\":true,\"show_borders\":true,\"border_width\":0.75,\"border_color_rgb\":[180,188,200],\"header_fill_color_rgb\":[33,64,98],\"header_text_color_rgb\":[255,255,255],\"row_fill_color_rgb\":[250,250,252],\"alternate_row_fill_color_rgb\":[235,240,246],\"cell_padding\":{\"top\":6,\"right\":8,\"bottom\":6,\"left\":8}}},\"data_presentation\":\"hierarchy\"}");
MultipartBody.Builder form =
new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart(
"file",
inputFile.getName(),
RequestBody.create(inputFile, MediaType.parse("application/octet-stream")))
.addFormDataPart("structured_text_options", options.toString());
Request request =
new Request.Builder()
.url(API_URL + "/pdf")
.header("Api-Key", apiKey)
.post(form.build())
.build();
send(request);
}
private static void send(Request request) throws IOException {
OkHttpClient client = new OkHttpClient.Builder().readTimeout(60, TimeUnit.SECONDS).build();
try (Response response = client.newCall(request).execute()) {
System.out.println("Result code " + response.code());
if (response.body() != null) System.out.println(response.body().string());
if (!response.isSuccessful()) System.exit(1);
}
}
}
Source: View the sample on GitHub
Breaking Down the Code
This Java JSON example combines OkHttp for transport, org.json for conversion settings, and dotenv support for repository configuration. Those project dependencies must remain available when the class is moved into another application.
import io.github.cdimascio.dotenv.Dotenv; import java.io.File; import java.io.IOException; import java.util.concurrent.TimeUnit; import okhttp3.*; import org.json.JSONObject;
The Java endpoint excerpt exposes the regional service selection used for this JSON conversion:
public class PdfFromJson {
private static final String API_URL = "https://api.pdfrest.com";
private static final String DEFAULT_API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
public static void main(String[] args) throws IOException {
File inputFile = new File(args.length > 0 ? args[0] : "/path/to/sample.json");
Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load();
String apiKey = dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY);
Java wraps the .json path in an OkHttp request body and retains the filename in the multipart upload. The shared /pdf endpoint uses that extension to select JSON conversion.
public static void main(String[] args) throws IOException {
File inputFile = new File(args.length > 0 ? args[0] : "/path/to/sample.json");
Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load();
The JSONObject is the pdfRest conversion profile. Its title and language describe the PDF, enable_tagging explicitly requests logical tags, and page_setup establishes Letter portrait pages with 36-point margins. The style member controls the fonts, text size, color, and any JSON-specific rendering choices.
{
"data_presentation": "hierarchy"
}
source is the default. It validates and parses the input, then pretty-prints normalized JSON syntax in a code-style block; original indentation and insignificant whitespace are not preserved. hierarchy removes the syntax and creates a nested list in which property names are bold and primitive values appear as key-value items.
Scalar arrays become ordinary nested values. Arrays containing objects or other arrays label their members Item 1, Item 2, and so on. The converter preserves JSON structure but intentionally does not infer application-specific report meaning. Malformed JSON is rejected in either presentation mode.
The sample’s shared style.table object does not affect JSON source or hierarchy output. It can be omitted when the profile is used only for JSON conversion.
For the JSON upload, MultipartBody.Builder combines the source file, serialized structured_text_options, and ordinary output text field in one request body.
"file",
inputFile.getName(),
RequestBody.create(inputFile, MediaType.parse("application/octet-stream")))
.addFormDataPart("structured_text_options", options.toString());
Request request =
new Request.Builder()
.url(API_URL + "/pdf")
.header("Api-Key", apiKey)
.post(form.build())
.build();
send(request);
OkHttp submits the JSON conversion with the API key and checks the HTTP result. The printed body contains generated-resource JSON after success or API error details when processing fails.
}
private static void send(Request request) throws IOException {
OkHttpClient client = new OkHttpClient.Builder().readTimeout(60, TimeUnit.SECONDS).build();
try (Response response = client.newCall(request).execute()) {
System.out.println("Result code " + response.code());
if (response.body() != null) System.out.println(response.body().string());
if (!response.isSuccessful()) System.exit(1);
}
}
}
Beyond the Tutorial
Java teams can adapt this workflow to transaction records, service responses, policy snapshots, and integration diagnostics. Complex arrays are labeled by item number, which helps reviewers navigate repeated objects without requiring domain-specific templates.
The generated tags expose document structure but are not a PDF/UA or WCAG certification. Explore payload and styling variations with API Lab, then consult the Convert to PDF API guide for supported parameters and constraints.