How to Convert Plain Text to PDF with Java

Convert plain text reports into styled, tagged PDFs with Java and control whether lines are preserved or reflowed.
Share this page

This Java tutorial submits a plain text file to the pdfRest Convert to PDF API Tool and creates a tagged PDF with controlled page setup and typography. The sample selects preserved line handling so the source layout remains visible.

Why Convert Plain Text to PDF with Java?

Java batch applications and transaction systems still produce text summaries, spool-style reports, and reconciliation output. These files are efficient for systems to create, yet they can be awkward to distribute to reviewers who expect a paginated document with reliable rendering.

A settlement service provides a useful example: after processing a nightly batch, it may write account totals, warnings, and control values to a text report. The Java application can convert that report to PDF and place it alongside the batch record for finance review. Preserved lines maintain the report’s sequence, and a monospaced body font can be selected when aligned text columns are significant.

When the source contains prose instead of layout-sensitive rows, reflow mode produces more natural paragraphs. The conversion API lets the same Java service choose that behavior per request while setting document language, title, margins, fonts, and tags centrally.

Java Code Example for Converting Plain Text 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 PdfFromText {
  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.txt");
    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}}},\"plain_text\":{\"line_handling\":\"preserve\"}}");
    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 Plain Text 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 Plain Text conversion:

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

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

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

{
  "plain_text": {
    "line_handling": "preserve"
  }
}

preserve keeps every normalized source line and its spacing in a preformatted block. Windows and legacy carriage-return line endings are normalized consistently. The alternative reflow joins consecutive nonblank lines into paragraphs, using blank lines as paragraph boundaries; reflow is the default when the field is omitted. Only those two values are accepted. When horizontal alignment matters, select a monospaced body font because preserve mode retains characters and spacing but does not force a particular font.

The sample also carries style.table because the repository uses one broad structured-text profile. Plain Text does not create a table, so those table colors, borders, widths, and padding have no effect and may be omitted from a text-only integration.

For the Plain Text 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 Plain Text 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 services can apply this approach to audit logs, generated notices, and text-based batch reports while choosing whether source line breaks remain fixed or reflow into paragraphs. The requested tags contribute document structure without certifying accessibility compliance.

Production profiles only need the settings relevant to their text workflow. Use API Lab to compare line-handling modes, then review the Convert to PDF documentation before finalizing request validation.

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