How to convert DOCX to PDF using Java

Table of contents

    Convert DOCX files to PDF using Java and Nutrient DWS Processor API. This tutorial covers API setup, Java implementation with OkHttp, and document processing workflows for automating DOCX-to-PDF conversion in your applications.
    How to convert DOCX to PDF using Java
    Summary

    Convert DOCX to PDF using Nutrient’s Java API. Create a free account, get API credentials, and implement conversion using OkHttp and JSON libraries. Combine with 30+ API tools for merging, watermarking, and page manipulation.

    Convert DOCX files to PDFs in your Java application using Nutrient’s DOCX-to-PDF Java API. Get 200 free credits — no payment required. Different operations consume different amounts of credits. Create a free account(opens in a new tab) for your API key.

    Why convert DOCX to PDF?

    Converting DOCX files to PDF is essential for workflows requiring document standardization and sharing. Common use cases include:

    • Document preservation — Convert Word documents to PDFs to preserve formatting, fonts, and layouts, regardless of the software or device used to view them.
    • Professional distribution — Share contracts, reports, and proposals in a universal format that maintains consistent appearance across all platforms.
    • Compliance and archiving — Create tamper-resistant records for legal compliance, audit trails, and long-term document storage.
    • Print-ready documents — Ensure documents print exactly as intended, without formatting issues or missing fonts.
    • Version control — Lock document formatting to prevent accidental edits, while allowing controlled review and approval processes.

    The DOCX-to-PDF API automates this process in your workflow.

    Nutrient DWS Processor API

    Converting DOCX to PDF is one of 30+ operations available through our PDF API tools. Combine DOCX-to-PDF conversion with other tools for complex workflows:

    Your account includes access to all PDF API tools.

    Step 1 — Creating a free account on Nutrient

    Go to our website(opens in a new tab) to create your free account.

    Free account at Nutrient API

    After creating your account, you’ll see your plan details.

    You start with 200 credits and can access all PDF API tools.

    Step 2 — Obtaining the API key

    After verifying your email, get your API key from the dashboard. Click API keys in the left menu to see your keys.

    Convert DOCX to PDF Java API Key

    Copy the Live API key for the DOCX-to-PDF API.

    Step 3 — Setting up folders and files

    Use IntelliJ IDEA as your code editor. Create a new project called docx_to_pdf. Select Java as the language, Gradle as the build system, and Groovy as the Gradle DSL.

    DOCX to PDF Java API

    Create a new directory in your project. Right-click your project’s name and select New > Directory. Choose the src/main/java option. Create a class file inside the src/main/java folder called processor.java, and create two folders called input_documents and processed_documents in the root folder.

    Place your DOCX file in the input_documents folder. Use our demo document as an example.

    Your folder structure:

    docx_to_pdf
    ├── input_documents
    | └── document.docx
    ├── processed_documents
    ├── src
    | └── main
    | └── java
    | └── processor.java

    Step 4 — Installing dependencies

    Install two libraries:

    • OkHttp — This library makes API requests.
    • JSON — This library will parse the JSON payload.

    Open the build.gradle file and add the following dependencies to your project:

    dependencies {
    implementation 'com.squareup.okhttp3:okhttp:4.9.2'
    implementation 'org.json:json:20210307'
    }

    After adding dependencies, click the Add Configuration button in IntelliJ IDEA to open the dropdown menu.

    DOCX to PDF Java API

    Select Application from the menu.

    DOCX to PDF Java API

    Fill the form with required details. Most fields will be prefilled. Select java 18 in the module field, add -cp docx_to_pdf.main as the main class, and add Processor in the field below it.

    DOCX to PDF Java API

    Click the Apply button to save settings.

    Step 5 — Writing the code

    Open the processor.java file and add this code:

    package com.example.pspdfkit;
    import java.io.File;
    import java.io.IOException;
    import java.nio.file.FileSystems;
    import java.nio.file.Files;
    import java.nio.file.StandardCopyOption;
    import org.json.JSONArray;
    import org.json.JSONObject;
    import okhttp3.MediaType;
    import okhttp3.MultipartBody;
    import okhttp3.OkHttpClient;
    import okhttp3.Request;
    import okhttp3.RequestBody;
    import okhttp3.Response;
    public final class Processor {
    public static void main(final String[] args) throws IOException {
    final RequestBody body = new MultipartBody.Builder()
    .setType(MultipartBody.FORM)
    .addFormDataPart(
    "file",
    "document.docx",
    RequestBody.create(
    MediaType.parse("application/vnd.openxmlformats-officedocument.wordprocessingml.document"),
    new File("input_documents/document.docx")
    )
    )
    .addFormDataPart(
    "instructions",
    new JSONObject()
    .put("parts", new JSONArray()
    .put(new JSONObject()
    .put("file", "file")
    )
    ).toString()
    )
    .build();
    final Request request = new Request.Builder()
    .url("https://api.nutrient.io/build")
    .method("POST", body)
    .addHeader("Authorization", "Bearer YOUR_API_KEY_HERE")
    .build();
    final OkHttpClient client = new OkHttpClient()
    .newBuilder()
    .build();
    final Response response = client.newCall(request).execute();
    if (response.isSuccessful()) {
    Files.copy(
    response.body().byteStream(),
    FileSystems.getDefault().getPath("processed_documents/result.pdf"),
    StandardCopyOption.REPLACE_EXISTING
    );
    } else {
    // Handle the error.
    throw new IOException(response.body().string());
    }
    }
    }

    Make sure to replace YOUR_API_KEY_HERE with your API key.

    Code explanation

    The code imports required packages and creates a processor class. The main function creates the request body for the API call with DOCX-to-PDF conversion instructions. The API processes these instructions.

    The execute() function sends the request. The API response saves to the processed_documents folder.

    Output

    Execute the code by clicking the Run button (green arrow) next to the Processor field.

    DOCX to PDF Java API

    After successful execution, you’ll find result.pdf in the processed_documents folder.

    Final folder structure:

    docx_to_pdf
    ├── input_documents
    | └── document.docx
    ├── processed_documents
    | └── result.pdf
    ├── src
    | └── main
    | └── java
    | └── processor.java

    Additional resources

    Explore more ways to work with Nutrient API:

    Conclusion

    This tutorial showed how to convert DOCX files to PDFs in Java using the Nutrient API.

    Integrate this functionality into existing applications. The same API token enables additional operations: document merging, watermarking, and page manipulation. Sign up(opens in a new tab) for a free trial.

    FAQ

    Do I need a paid account to use Nutrient DWS Processor API?

    No. Start with a free account that provides 200 credits for processing documents. Different operations consume different amounts of credits, so you can process varying numbers of documents depending on the operations you use.

    Does Nutrient DWS Processor API preserve DOCX formatting when converting to PDF?

    Yes. Nutrient DWS Processor API maintains document formatting, including fonts, styles, images, tables, and page layouts. Complex elements like headers, footers, and embedded objects are preserved in the PDF output.

    What Java version is required for this code?

    The code requires Java 8 or higher. The example uses Java 18, but the OkHttp and JSON libraries are compatible with Java 8+. Verify your Java version with java -version.

    Can I convert multipage DOCX documents to PDF?

    Yes. Nutrient DWS Processor API converts multipage DOCX documents to PDF while maintaining pagination, page breaks, and document structure across all pages.

    Jonathan D. Rhyne

    Jonathan D. Rhyne

    Co-Founder and CEO

    Jonathan joined PSPDFKit in 2014. As Co-founder and CEO, Jonathan defines the company’s vision and strategic goals, bolsters the team culture, and steers product direction. When he’s not working, he enjoys being a dad, photography, and soccer.

    Explore related topics

    FREE TRIAL Ready to get started?