How to Convert Microsoft Word to PDF with Java
In this tutorial, we'll walk through how to convert Microsoft Word to PDF with Java using the Convert to PDF API Tool. The code posts a DOCX document to /pdf, demonstrating the file metadata and response handling needed for server-side Office conversion. You'll see how the request is assembled and how to work with the response returned when you convert Microsoft Word to PDF.
Why Convert Microsoft Word to PDF with Java?
Contract and correspondence systems often generate DOCX files but distribute final versions as PDFs. Automated conversion creates a fixed document that is easier to review consistently and feed into later PDF processing.
The adapted request uploads a .docx file with the Word Open XML media type. The file extension and multipart filename allow the shared /pdf endpoint to select Word conversion.
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 ConvertWordToPDF {
// 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.docx";
// 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;
if (args.length > 0) {
inputFile = new File(args[0]);
} else {
inputFile = new File(DEFAULT_FILE_PATH);
}
final Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load();
final RequestBody inputFileRequestBody =
RequestBody.create(inputFile, MediaType.parse("application/vnd.openxmlformats-officedocument.wordprocessingml.document"));
RequestBody requestBody =
new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", inputFile.getName(), inputFileRequestBody)
.addFormDataPart("output", "pdfrest_word_to_pdf")
.build();
Request request =
new Request.Builder()
.header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
.url(API_URL + "/pdf")
.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. The walkthrough specializes the reusable repository sample for Convert Microsoft Word to PDF.
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 import block brings together the HTTP client, environment-based API key loading, and JSON utilities used later in the example.
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.docx";
// 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;
if (args.length > 0) {
inputFile = new File(args[0]);
} else {
inputFile = new File(DEFAULT_FILE_PATH);
}
final Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load();
final RequestBody inputFileRequestBody =
The constants section shows where the input comes from and keeps the credential outside the request-building logic.
Build the multipart request body
final RequestBody inputFileRequestBody =
RequestBody.create(inputFile, MediaType.parse("application/vnd.openxmlformats-officedocument.wordprocessingml.document"));
RequestBody requestBody =
new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", inputFile.getName(), inputFileRequestBody)
.addFormDataPart("output", "pdfrest_word_to_pdf")
.build();
Request request =
new Request.Builder()
.header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
.url(API_URL + "/pdf")
.post(requestBody)
.build();
try {
OkHttpClient client =
new OkHttpClient().newBuilder().readTimeout(60, TimeUnit.SECONDS).build();
The adapted request uploads a .docx file with the Word Open XML media type. The file extension and multipart filename allow the shared /pdf endpoint to select Word conversion. This payload builder sets MultipartBody.FORM, allowing OkHttp to generate the matching boundary automatically.
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")
.post(requestBody)
.build();
try {
OkHttpClient client =
new OkHttpClient().newBuilder().readTimeout(60, TimeUnit.SECONDS).build();
The outbound call joins authentication, routing, and payload in one place while leaving regional service selection in the API URL constant.
Read the API response
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 returned-data block makes success and failure information available to the caller, including any temporary resources that must be saved or reused before expiration.
Beyond the Tutorial
In this tutorial, we walked through how to convert Microsoft Word to PDF with Java. With that foundation, you can use this integration for contracts, letters, reports, templates, and other generated Office documents.
As you adapt this example for production, keep in mind that templates, fields, embedded fonts, tracked layout changes, and complex section settings can affect conversion. Include representative contracts or reports in validation and compare pagination, headers, footers, and page breaks before treating the PDF as a final version.
To continue exploring the Convert Microsoft Word to PDF operation, visit API Lab. For complete request fields, defaults, and limitations, refer to the Convert to PDF API Tool documentation.
Note: The Convert Microsoft Word to PDF example above uses multipart form data; when a prior API call returned the input ID, see the request shape in the JSON payload example.