How to Convert CSV to PDF with Java
This Java example converts CSV records into a styled PDF table through the pdfRest Convert to PDF API Tool. It demonstrates tagged output, per-column width and alignment choices, repeated headers, alternating row fills, and multipart upload from a server application.
Why Convert CSV to PDF with Java?
Enterprise Java systems commonly export inventory, transactions, and reconciliation data as CSV because the format is lightweight and widely supported. That portability does not solve the presentation problem when managers or customers need a document with clear columns, page breaks, and labels.
Consider a warehouse platform that produces a daily CSV of item numbers, descriptions, and quantities requiring review. The Java service can turn the export into a PDF where the description receives more width, quantities align to the right, and header rows repeat across pages. Supervisors receive a report they can print or annotate without first opening and styling a spreadsheet.
Generating the table through a service also keeps recurring reports consistent. Page geometry, border rules, colors, padding, typography, and structural tags live in the conversion profile rather than in desktop templates maintained by individual users.
Java Code Example for Converting CSV 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 PdfFromCsv {
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.csv");
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}}},\"csv\":{\"first_row_is_header\":true,\"delimiter\":\",\",\"columns\":[{\"index\":0,\"width_weight\":2,\"text_align\":\"left\"},{\"index\":1,\"width_weight\":3,\"text_align\":\"left\"},{\"index\":2,\"width_weight\":1,\"text_align\":\"right\"}]}}");
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 CSV 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 CSV conversion:
public class PdfFromCsv {
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.csv");
Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load();
String apiKey = dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY);
Java wraps the .csv path in an OkHttp request body and retains the filename in the multipart upload. The shared /pdf endpoint uses that extension to select CSV conversion.
public static void main(String[] args) throws IOException {
File inputFile = new File(args.length > 0 ? args[0] : "/path/to/sample.csv");
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 CSV-specific rendering choices.
{
"csv": {
"first_row_is_header": true,
"delimiter": ",",
"columns": [
{
"index": 0,
"width_weight": 2,
"text_align": "left"
},
{
"index": 1,
"width_weight": 3,
"text_align": "left"
},
{
"index": 2,
"width_weight": 1,
"text_align": "right"
}
]
}
}
first_row_is_header defaults to true; setting it to false renders every record as a body row. delimiter defaults to a comma and must contain exactly one character, so a tab or semicolon can be selected but a multi-character separator cannot.
Column indexes are zero-based. Unspecified columns default to weight 1 and left alignment. Width weights are positive relative proportions, not points or pixels, and text_align accepts only left, center, or right. An index outside the parsed CSV, a nonpositive weight, or another alignment value produces a validation error.
The per-column CSV weights take precedence over style.table.column_width_weights; the broader table list is only a fallback when CSV-specific widths are absent. The remaining table style controls borders, colors, row striping, and padding. keep_header_with_first_row prevents a header from appearing alone, and repeat_headers_on_overflow repeats it as rows continue onto later pages.
For the CSV 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 CSV 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 for inventory reviews, financial reconciliations, exception lists, and customer-facing data extracts. Explicit column rules are especially valuable when long descriptions and compact numeric fields must share the same page.
Tags provide a logical table hierarchy for assistive and automated consumers without guaranteeing a specific compliance level. Explore the layout interactively with API Lab, then reference the Convert to PDF API guide for supported values and limits.