How to Import Data to PDF Forms with Java

Populate PDF form fields from structured data with Java.
Share this page

This step-by-step tutorial explains how a Java application can import data to PDF forms through the Import Form Data API Tool. The multipart request pairs the destination PDF with a structured data file whose field names map to the form. After reviewing the example, you'll be ready to import data to PDF forms with your own input.

Why Import Data to PDF Forms with Java?

An onboarding system may already hold customer details that also belong in a standardized PDF form. Importing those values avoids asking users or staff to enter the same information twice.

The multipart request sends the PDF as file and the field-value file as data_file to /pdf-with-imported-form-data. Field names in the data must match the form.

Java Code Example

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 PDFWithImportedFormData {

  // By default, we use the US-based API service. This is the primary endpoint for global use.
  private static final String API_URL = "https://api.pdfrest.com";

  // For GDPR compliance and enhanced performance for European users, you can switch to the EU-based
  // service by commenting out the URL above and uncommenting the URL below.
  // For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work
  // private static final String API_URL = "https://eu-api.pdfrest.com";

  // Specify the path to your file here, or as the first argument when running the program.
  private static final String DEFAULT_FILE_PATH = "/path/to/file.pdf";

  // Specify the path to your data file here, or as the second argument when running the
  // program.
  private static final String DEFAULT_DATA_PATH = "/path/to/file.xml";

  // Specify your API key here, or in the environment variable PDFREST_API_KEY.
  // You can also put the environment variable in a .env file.
  private static final String DEFAULT_API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";

  public static void main(String[] args) {
    File inputFile, dataFile;
    if (args.length > 1) {
      inputFile = new File(args[0]);
      dataFile = new File(args[1]);
    } else {
      inputFile = new File(DEFAULT_FILE_PATH);
      dataFile = new File(DEFAULT_DATA_PATH);
    }

    final Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load();

    final RequestBody inputFileRequestBody =
        RequestBody.create(inputFile, MediaType.parse("application/pdf"));
    final RequestBody dataFileRequestBody =
        RequestBody.create(dataFile, MediaType.parse("application/xml"));
    RequestBody requestBody =
        new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("file", inputFile.getName(), inputFileRequestBody)
            .addFormDataPart("data_file", dataFile.getName(), dataFileRequestBody)
            .build();
    Request request =
        new Request.Builder()
            .header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
            .url(API_URL + "/pdf-with-imported-form-data")
            .post(requestBody)
            .build();
    try {
      OkHttpClient client =
          new OkHttpClient().newBuilder().readTimeout(60, TimeUnit.SECONDS).build();
      Response response = client.newCall(request).execute();
      System.out.println("Result code " + response.code());
      if (response.body() != null) {
        System.out.println(prettyJson(response.body().string()));
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  private static String prettyJson(String json) {
    // https://stackoverflow.com/a/9583835/11996393
    return new JSONObject(json).toString(4);
  }
}

Source: Java sample on GitHub.

Breaking Down the Code

Load the Java HTTP and JSON dependencies

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 sample assigns a clear role to each library: HTTP communication, credential lookup, or JSON handling.

Choose the input and load credentials

// service by commenting out the URL above and uncommenting the URL below.
  // For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work
  // private static final String API_URL = "https://eu-api.pdfrest.com";

  // Specify the path to your file here, or as the first argument when running the program.
  private static final String DEFAULT_FILE_PATH = "/path/to/file.pdf";

  // Specify the path to your data file here, or as the second argument when running the
  // program.
  private static final String DEFAULT_DATA_PATH = "/path/to/file.xml";

  // Specify your API key here, or in the environment variable PDFREST_API_KEY.
  // You can also put the environment variable in a .env file.
  private static final String DEFAULT_API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";

  public static void main(String[] args) {
    File inputFile, dataFile;
    if (args.length > 1) {
      inputFile = new File(args[0]);
      dataFile = new File(args[1]);
    } else {
      inputFile = new File(DEFAULT_FILE_PATH);

The form and its data file have separate defaults and command-line arguments, making their relationship explicit before dotenv loads the API key.

Build the multipart request body

final RequestBody dataFileRequestBody =
        RequestBody.create(dataFile, MediaType.parse("application/xml"));
    RequestBody requestBody =
        new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("file", inputFile.getName(), inputFileRequestBody)
            .addFormDataPart("data_file", dataFile.getName(), dataFileRequestBody)
            .build();
    Request request =
        new Request.Builder()
            .header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
            .url(API_URL + "/pdf-with-imported-form-data")
            .post(requestBody)
            .build();
    try {
      OkHttpClient client =
          new OkHttpClient().newBuilder().readTimeout(60, TimeUnit.SECONDS).build();

The multipart request sends the PDF as file and the field-value file as data_file to /pdf-with-imported-form-data. Field names in the data must match the form. The form-data setup leaves boundary construction to OkHttp so the header remains synchronized with the serialized content.

Send the request to pdfRest

.build();
    Request request =
        new Request.Builder()
            .header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
            .url(API_URL + "/pdf-with-imported-form-data")
            .post(requestBody)
            .build();
    try {
      OkHttpClient client =
          new OkHttpClient().newBuilder().readTimeout(60, TimeUnit.SECONDS).build();
      Response response = client.newCall(request).execute();

The client request posts the multipart content to pdfRest and keeps deployment-region changes independent of the rest of the Java code.

Read the API response

try {
      OkHttpClient client =
          new OkHttpClient().newBuilder().readTimeout(60, TimeUnit.SECONDS).build();
      Response response = client.newCall(request).execute();
      System.out.println("Result code " + response.code());
      if (response.body() != null) {
        System.out.println(prettyJson(response.body().string()));
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  private static String prettyJson(String json) {
    // https://stackoverflow.com/a/9583835/11996393
    return new JSONObject(json).toString(4);

The response check prints the HTTP status and JSON body so generated resource IDs or API error details are visible.

Beyond the Tutorial

The completed example gives you a practical Java starting point for learning how to import data to PDF forms. With that foundation, you can use form import for prefilled applications, generated forms, batch correspondence, and system-of-record synchronization.

As you apply the pattern to real documents, keep in mind that data keys must match the PDF field names exactly, so export a known form first when the contract is unclear. Validate dates, checkboxes, choice fields, and multiline values with realistic records before generating forms in bulk.

Before integrating this workflow, test representative documents with the Import Data to PDF Forms operation in API Lab. Then use the Import Form Data API Tool documentation to review every available parameter and response field.

Note: The Import Data to PDF Forms example above uses multipart form data; to reuse a resource ID, use the JSON payload example as a guide.

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