How to Convert XML to PDF with Java

Convert XML data into a styled and tagged PDF with Java while choosing a readable hierarchy or source-code presentation.
Share this page

This Java tutorial demonstrates how to upload XML to the pdfRest Convert to PDF API Tool and receive a styled, tagged PDF. The example uses hierarchy presentation for readability and includes the page, language, and font controls needed for predictable document output.

Why Convert XML to PDF with Java?

Java applications often sit at the center of enterprise systems where XML represents transactions, policy data, service messages, or archival metadata. Those payloads are useful to software, but business reviewers usually need a stable document that communicates the same information without exposing them to raw markup.

For example, an insurance platform may receive a nested XML response from an underwriting service and need to preserve the decision details with a case file. The application can convert that response into a PDF whose hierarchy keeps sections, fields, and values visually related. Claims staff can review the result in ordinary document software, and the generated resource can continue through the organization’s existing PDF workflow.

Centralizing this work in an API also keeps the Java service from maintaining its own XML-to-layout engine. Teams can select hierarchy mode for operational review or source mode for developers and auditors who need to see the original element syntax, while using the same conversion path for both audiences.

Java Code Example for Converting XML 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 PdfFromXml {
  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.xml");
    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 XML 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 XML conversion:

public class PdfFromXml {
  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.xml");
    Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load();
    String apiKey = dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY);

Java wraps the .xml path in an OkHttp request body and retains the filename in the multipart upload. The shared /pdf endpoint uses that extension to select XML conversion.

  public static void main(String[] args) throws IOException {
    File inputFile = new File(args.length > 0 ? args[0] : "/path/to/sample.xml");
    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 XML-specific rendering choices.

{
  "data_presentation": "hierarchy"
}

source is the default. It first validates the XML and then displays the user’s original source text, including its markup, whitespace, and declared encoding text. hierarchy instead creates a nested list: local element names become bold labels, attributes appear with an @ prefix, and leaf values follow their element names. Namespace prefixes are not displayed in hierarchy labels. Invalid XML and documents without a root element are rejected in either mode.

The shared style.table member does not affect XML hierarchy or source output. It can be removed from an XML-only profile without changing the resulting document.

For the XML 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 XML 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

A hierarchy-based PDF can make deeply nested service responses, product catalogs, and interchange documents approachable to reviewers outside the development team. Source presentation remains available when engineers need the exact markup visible in the document.

The requested tags describe the document’s logical organization but are not a declaration of PDF/UA or WCAG conformance. Try variations interactively in API Lab and use the Convert to PDF API reference when selecting additional conversion controls.

Generate a self-service API Key now!
Create your FREE API Key to start processing PDFs in seconds, only possible with pdfRest.