Skip to content
pdfconversionapi

Guide7 min read

Convert DOCX to PDF in Java: the open-source options, tested

XDocReport printed a contract's deleted words and hidden note, docx4j failed on tracked changes, LibreOffice adds 375 MB. Or HttpClient and PDFConversionAPI.

Written and tested by Zeel Shekhaliya, Founder

Contents (8 sections)

The open-source answers for turning a Word file into a PDF in Java each failed one of our three files. Apache POI with XDocReport, a common answer in forum threads, printed the contract draft's deleted and inserted words side by side, "within 3045 days" and "twelveeighteen months", with nothing to mark them, and printed a note the author had hidden. docx4j laid out the report closely but threw an exception on the same contract. documents4j needs Microsoft Word on Windows. LibreOffice converted all three after a 375 MB install. PDFConversionAPI, our API, needs java.net.http, plus Jackson to read the JSON reply: send the .docx, get the PDF back. It can return PDF/A too; our DOCX to PDF page has that option and the others.

With PDFConversionAPI: HttpClient and Jackson

PdfConversionApi.java
// Word to PDF with pdfconversionapi.com. Java 11 or later, plus Jackson (com.fasterxml.jackson.core:jackson-databind).
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.Base64;
import java.util.Map;
import java.util.UUID;

public final class PdfConversionApi {
    private static final URI API = URI.create("https://api.pdfconversionapi.com/v2/convert/docx/to/pdf");
    private static final HttpClient HTTP = HttpClient.newHttpClient();
    private static final ObjectMapper JSON = new ObjectMapper();

    /** Sends a .docx and writes the PDF. Options are API parameters, such as Map.of("UpdateFields", "true"). */
    public static void docxToPdf(Path docx, Path pdf, Map<String, String> options) throws IOException, InterruptedException {
        String boundary = UUID.randomUUID().toString();
        var body = new ByteArrayOutputStream();
        for (var option : options.entrySet()) {
            body.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"" + option.getKey() + "\"\r\n\r\n"
                    + option.getValue() + "\r\n").getBytes(StandardCharsets.UTF_8));
        }
        body.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"File\"; filename=\"" + docx.getFileName()
                + "\"\r\nContent-Type: application/octet-stream\r\n\r\n").getBytes(StandardCharsets.UTF_8));
        body.write(Files.readAllBytes(docx));
        body.write(("\r\n--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8));

        var request = HttpRequest.newBuilder(API)
                .header("Authorization", "Bearer " + System.getenv("PDFCONVERSIONAPI_KEY"))
                .header("Content-Type", "multipart/form-data; boundary=" + boundary)
                .timeout(Duration.ofSeconds(240))
                .POST(HttpRequest.BodyPublishers.ofByteArray(body.toByteArray()))
                .build();
        HttpResponse<byte[]> response = HTTP.send(request, HttpResponse.BodyHandlers.ofByteArray());
        JsonNode json = JSON.readTree(response.body());
        if (response.statusCode() != 200) {
            throw new IOException(response.statusCode() + " " + json.path("Message").asText());
        }
        Files.write(pdf, Base64.getDecoder().decode(json.path("Files").path(0).path("FileData").asText()));
    }

    public static void docxToPdf(Path docx, Path pdf) throws IOException, InterruptedException {
        docxToPdf(docx, pdf, Map.of());
    }
}

Set PDFCONVERSIONAPI_KEY to your key (you get one by signing in at app.pdfconversionapi.com), then:

Text
PdfConversionApi.docxToPdf(Path.of("quarterly-report.docx"), Path.of("quarterly-report.pdf"));
PdfConversionApi.docxToPdf(Path.of("field-service-handbook.docx"), Path.of("field-service-handbook.pdf"), Map.of("UpdateFields", "true"));

try (Stream<Path> files = Files.list(Path.of("contracts"))) {
    for (Path docx : files.filter(p -> p.toString().endsWith(".docx")).toList()) {
        PdfConversionApi.docxToPdf(docx, docx.resolveSibling(docx.getFileName().toString().replaceAll("\\.docx$", ".pdf")));
    }
}
  • java.net.http ships with Java 11 and later. It has no multipart body, so the code writes the form by hand, and Java has no JSON parser, so Jackson reads the reply. Jackson and its two dependencies take 2.4 MB.
  • The PDF arrives as base64 in the JSON response, in Files[0].FileData.
  • Map.of("UpdateFields", "true") rebuilds the table of contents before the PDF is written: the handbook's contents list, saved before its last edits, came out with the new section names and page numbers. Table of contents not updating has the details.
  • An option DOCX to PDF can't apply is refused, not ignored: Map.of("PageRange", "1-2") threw IOException: 400 PageRange is not supported yet for DOCX → PDF.
  • The 240-second timeout leaves room for a conversion of up to 120 seconds plus the upload (Limits).
  • The loop sends one file at a time, which is what the Free plan allows: a second request while one is running gets 429 with Retry-After: 5. Paid plans run 4 to 30 at once (Pricing), so a small thread pool works there.

Against the container on our own machine, a conversion took 0.03 to 0.08 seconds after the first. Over the internet you add the upload and download; from Google's servers to the hosted API, a call took 1.0 to 3.7 seconds in our Apps Script test.

Apache POI with XDocReport

Apache POI reads .docx files, and XDocReport adds a PDF converter on top. We ran it as forum answers show it:

Text
// Maven: fr.opensagres.xdocreport:fr.opensagres.poi.xwpf.converter.pdf (it brings Apache POI)
try (var in = Files.newInputStream(docx); var out = Files.newOutputStream(pdf)) {
    XWPFDocument document = new XWPFDocument(in);
    PdfConverter.getInstance().convert(document, out, PdfOptions.create());
}

It converted all three files in 0.03 to 0.67 seconds, from 16 jars and 26 MB. The contract draft is the problem:

The contract draft side by side. Our API: "within 45 days", "fixed for eighteen months", and no internal note. Apache POI with XDocReport: "within 3045 days", "fixed for twelveeighteen months", the hidden internal note printed under the price paragraph, and a deleted sentence about paying by check
The contract draft. Left: our API. Right: Apache POI with XDocReport 2.2.
  • Deleted and inserted words were printed together as plain text: "within 3045 days", "twelveeighteen months", "3060 days' written notice". The PDF reads like a contract with wrong numbers, with nothing to show the edits.
  • A whole deleted sentence, "The buyer may pay by check within 60 days.", is in the PDF, and the sentence a reviewer moved appears twice.
  • The draft's hidden text, "Internal note: we can accept 9.50 per unit if they push back.", is printed under the price. Word never shows it.
  • Every page uses Helvetica, which is not embedded in the PDF, so each viewer substitutes its own font. The report's bullets are gone, its table headings broke mid-word ("Shipment s"), and no PDF has bookmarks.

Accept or reject all changes and delete hidden text before converting, or don't use this route for documents that have been reviewed.

docx4j

docx4j lays the document out as XSL-FO, and Apache FOP writes the PDF:

Text
// Maven: org.docx4j:docx4j-JAXB-ReferenceImpl and org.docx4j:docx4j-export-fo
WordprocessingMLPackage document = WordprocessingMLPackage.load(docx.toFile());
try (var out = Files.newOutputStream(pdf)) {
    Docx4J.toPDF(document, out);
}
  • The report came out close to the original, with metric-compatible fonts (Tinos and Arimo) embedded, in 2.87 seconds for the first file. The handbook took 0.34 seconds. Neither PDF has bookmarks.
  • The contract draft threw Docx4JException: Exception exporting package, caused by "fo:inline" is not a valid child of "fo:flow"!, and left a 15-byte file where the PDF should be. Write to a temporary file and move it into place only when the call succeeds.
  • It needs 64 jars, 37 MB.

documents4j: Windows and Word only

documents4j converts by driving Microsoft Word through a script, so it needs Windows with Word installed. On Linux the first call threw IllegalStateException: class com.documents4j.conversion.msoffice.MicrosoftWordBridge could not be created.

With LibreOffice, called from Java

LibreOffice converts Word files without a screen. In the Ubuntu 26.04 image, apt-get install --no-install-recommends libreoffice-writer-nogui added 97 packages: 110 MB to download and 375 MB on disk. This is the code we ran:

LibreOfficePdf.java
// Word to PDF with LibreOffice, run headless. Needs LibreOffice installed (apt install libreoffice-writer-nogui).
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

public final class LibreOfficePdf {
    /** Writes <name>.pdf into outDir. A profile of its own per call lets several conversions run at once. */
    public static void docxToPdf(Path docx, Path outDir) throws IOException, InterruptedException {
        Path profile = Files.createTempDirectory("soffice-profile-");
        try {
            Path log = profile.resolve("soffice.log");
            Process process = new ProcessBuilder("soffice", "-env:UserInstallation=" + profile.toUri(), "--headless",
                    "--convert-to", "pdf", "--outdir", outDir.toString(), docx.toString())
                    .redirectErrorStream(true).redirectOutput(log.toFile()).start();
            if (!process.waitFor(120, TimeUnit.SECONDS)) {
                process.destroyForcibly();
                throw new IOException("soffice timed out");
            }
            if (process.exitValue() != 0) throw new IOException("soffice exited with " + process.exitValue() + ": " + Files.readString(log));
        } finally {
            try (Stream<Path> files = Files.walk(profile)) {
                files.sorted(Comparator.reverseOrder()).forEach(p -> p.toFile().delete());
            }
        }
    }
}
  • The first file took 1.46 seconds and the rest 0.26 to 0.49. Four calls at once on four threads wrote all four PDFs in 0.91 seconds.
  • Keep the profile per call. In our Python test, four conversions sharing the default profile wrote only two PDFs, and the other two exited with code 1 and no useful message.
  • The image had none of the fonts these files name, so LibreOffice drew every page in DejaVu. On Linux, install the fonts your documents use (for Word's defaults, fonts-crosextra-carlito and fonts-crosextra-caladea).
  • It printed the contract's tracked changes as markup, struck through and underlined in color. It left the hidden note out.
  • JODConverter 5.1.1, which keeps one LibreOffice process running for many conversions, converted the report in 0.11 seconds once warm, but failed on the contract draft in every one of five tries (OfficeException: Local conversion failed), and a batch of four that included it failed too. The command line above converted the same file with the same LibreOffice.

What the PDFs contain

Our APILibreOffice 26.2Apache POI + XDocReportdocx4j
Files converted3 of 33 of 33 of 32 of 3 (exception on the contract)
The contract's tracked changesPrinted as acceptedPrinted as markupDeleted and inserted words run together, unmarkedNo PDF
The contract's hidden noteLeft outLeft outPrintedNo PDF
Bookmarks from headingsYesYesNoNo
Fonts, with nothing installed on your sideLiberation for the report, Carlito and Caladea for the contractDejaVuHelvetica, not embeddedTinos and Arimo for the report
What your server needsJava 11 or later and Jackson97 packages, 375 MB16 jars, 26 MB64 jars, 37 MB

Which one to use

  • Apache POI with XDocReport: only for documents with no tracked changes, comments or hidden text, such as files your own code generates. Check the output before you send it to anyone.
  • docx4j: for clean documents where you want a pure-Java route, with the temporary-file step above.
  • LibreOffice: when you control the server image, can add about 375 MB to it, install the fonts your documents name, and accept tracked changes in the PDF or clean them out first.
  • Our API: when the files are reviewed business documents, the code runs in a small container or a function, or you'd rather not keep an office suite on your server. The Free plan includes 250 conversions a month, files up to 10 MB and 1 conversion at a time; files are converted and returned, and nothing is kept unless you ask for a download link.

How we tested

Date
2026-11-26. Every request and result on this page ran that day.
System
Containers from the Maven image with Eclipse Temurin 25 (maven:3-eclipse-temurin-25: Java 25.0.5 on Ubuntu 26.04), on an arm64 Mac, with no fonts beyond the image's DejaVu. From Maven Central: XDocReport 2.2.0 (fr.opensagres.poi.xwpf.converter.pdf, with the Apache POI version it depends on), docx4j-JAXB-ReferenceImpl and docx4j-export-fo 17.3.6, documents4j-local and its Word transformer 1.1.13, jodconverter-local-lo 5.1.1 and jackson-databind 2.23.0. LibreOffice 26.2.7.3 from the image's package manager, apt.
Server
Our API running locally in a container, built from the same source as the hosted API; on 2026-11-25 the same build's PDF of the contract draft was byte for byte the PDF the hosted API returned. The code shows the hosted address; we ran it with only the address changed. The API times on this page therefore leave out the trip over the internet.
Files
The three Word files from our Python guide (download them above): a 3-page quarterly report that names Liberation Serif and Liberation Sans; a contract draft that names Calibri and Cambria, with tracked changes, two comments and a hidden note; and a 6-page handbook whose table of contents was saved before its last edits.
Runs
Our API three times per file, the handbook with UpdateFields=true, the usage lines on this page (with the paths under a test folder), and one request with an option DOCX to PDF doesn't support. LibreOffice twice per file, with a new profile each call, and four conversions at once on four threads. XDocReport and docx4j once per file, documents4j once. JODConverter twice per file, four at once, and the contract three more times in a separate run.
Checked with
Page count, fonts and whether they are embedded, bookmarks, document properties and page text read with PyMuPDF 1.27.2; pages rendered with PyMuPDF and compared by eye; install sizes as apt and du reported them.
Not checked
These libraries with extra fonts installed, other versions of them, Windows, Microsoft Word itself, and files larger than 26 KB.

Run your own files through the API.