docx4j

Choosing a document library, from Python

docx4j from Python

There are now two ways to use docx4j from Python. docx4j for Python (pip install docx4j) is a port: docx4j's object model and engine in pure Python, with no JVM. For what the port doesn't do yet, PDF output above all, a Python program can still call Java docx4j across the JVM boundary. And for generating simple documents, python-docx and docxtpl remain a good answer.

The decision rule
  • Generate a document from a simple template, set some formatting: python-docx or docxtpl. They're small and quick to import.
  • Pull out the text: docx4j for Python. It reads the text Word shows; python-docx loses tracked insertions and everything in content controls, and keeps hidden text.
  • Edit real documents and lose nothing on the way through: docx4j for Python. That means tracked changes and comments, templates bound to XML, the whole format typed, and an API an agent can drive. It also keeps python-docx code running.
  • PDF without Office, OpenDoPE repeats and conditions, PowerPoint or Excel: call Java docx4j, over JPype or as a small service. The two can share one process.

docx4j for Python

docx4j on PyPI is docx4j ported to Python, not a wrapper around it. The import name is docx4j_py, as python-docx imports as docx. Its WordprocessingML object model is generated from docx4j's own schema tree and carries docx4j's class names (P, R, PPr, Tbl), so docx4j's documentation and examples read across. Its Open Packaging engine is written by hand over that model. Java docx4j is the behavioural oracle, and where Word's behaviour matters, the tests hold the port to Word 365's own answers.

Version 0.2.0 (October 2026) handles WordprocessingML (.docx) only, on Python 3.12 or later. A .pptx or .xlsx loads and saves, every part byte for byte, but nothing in it is typed yet. What it gives you:

  • Nothing lost on the way through. A part your code never reads is copied back byte for byte (only the relationship lists are always rewritten), and one read and saved unchanged is canonically identical to its source. Anything the parser can't place is reported, part by part, rather than silently dropped; strict loading raises instead.
  • The whole format, typed. All of ECMA-376 WordprocessingML, with the DrawingML, VML and math it embeds and Word's w14 to w16 extensions, as typed classes. docx4j's PropertyResolver, numbering emulator and font selection are ported too.
  • Tracked changes and comments, as Word does them. Edits can be tracked under an author. Tracked changes are listed, accepted and rejected the way Word 365 resolves them, in the body, headers, footers, notes and comments. Comments have replies and can be resolved.
  • Templates bound to XML. describe() lists what a template's content controls are bound to, and fill() sets the custom XML and refreshes the controls, as Word does when it opens the file. OpenDoPE's repeats and conditions are still Java docx4j's (see below).
  • An API in Office JS's vocabulary, built for agents. Body, Paragraph, Range, Table, content controls and lists, with Office JS's text and semantics. For agents: addresses that survive edits, an outline of a 200-page document in under 64 KB, a report of what each edit did, and errors that say what to do instead.
  • The text Word shows. docx4j's text model gives a document's plain text or Markdown in its accepted, original or markup view: tracked changes as Word's Accept All or Reject All would leave them, or both marked; content controls read, and a bound control's value as Word shows it; hidden text left out; each text box once, after its anchor; the notes; charts as tables and equations as LaTeX. Markdown (CommonMark, with GFM tables) can be written in too, through the document's own styles.
  • python-docx code runs. docx4j_py.docx is python-docx's API over this engine: 305 of the 312 public members of python-docx 1.2.0, and each of the other seven refused with a reason.

Fill a template and make a tracked edit, no JVM

from docx4j_py import load
from docx4j_py.model.content import Author

pkg = load("invoice2013.docx")          # its controls are bound to custom XML
pkg.custom_xml_parts.fill({             # set the data and refresh the controls
    "/invoice[1]/customer[1]/company[1]": "Acme Manufacturing Ltd",
    "/invoice[1]/customer[1]/contact[1]": "Ada Lovelace",
})

pkg.author = Author("Claude", initials="C")
pkg.change_tracking_mode = "TrackAll"   # from here, every edit is tracked
pkg.body.replace_text("Purchase Order No", "Order reference")
print([(c.type, c.text) for c in pkg.get_tracked_changes()])
# [('Added', 'Order reference'), ('Deleted', 'Purchase Order No')]

pkg.save("invoice-edited.docx")         # styles and images copied byte for byte

Code written for python-docx needs only its imports changed:

# was: from docx import Document; from docx.shared import Pt
from docx4j_py.docx import Document, Pt

doc = Document("invoice2013.docx")
p = doc.add_paragraph("Paid with thanks, ")
p.add_run("25 October 2026").bold = True
p.runs[1].font.size = Pt(14)
doc.save("invoice-paid.docx")

What it costs: a 1.5 MB wheel, because the whole of WordprocessingML is in it as classes, and about 0.7 s to import, once per process. A long-running process is the intended host. The repository has the full README, the changelog and the design, recorded as change requests.

Text extraction: what python-docx misses

Many Python pipelines read a .docx through python-docx's Paragraph.text, Haystack, Dify, CrewAI and Unstructured among them. On one test document, python-docx 1.2.0 and docx4j for Python 0.2.0 read this:

The document holdspython-docxdocx4j for Python
A tracked change: 100 inserted, 90 deleted neither: Price: Price: 100
A value in a content control missing: Supplier: Supplier: Acme Ltd
A clause in a block content control missingread
Hidden text, such as a prompt injection read as if visibleleft out, as Word shows it
A bound control whose stored text is stale missingthe value Word shows, with a warning

python-docx doesn't reach text boxes or notes either. In docx4j for Python, reading the text is one call, and the warnings say where what Word shows differs from what the file stores:

from docx4j_py import load
from docx4j_py.model.text import extract, plain_text

result = extract(load("in.docx"))   # as Word's Accept All leaves it
print(plain_text(result))
for warning in result.warnings:     # e.g. sdt.binding_differs at body/2/0/0/1
    print(warning)

extract(pkg, view="markup") keeps both sides of each tracked change, marked up as {++inserted++} and {--deleted--}, and include="headers, footers" adds the headers and footers. The package is never changed by reading it.

What still needs Java docx4j

None of these is in docx4j for Python yet, and the first two have no real equivalent in any Python library. For them, bridging to Java docx4j is less total effort than fighting the format in Python: you're buying twenty years of edge-case handling for the cost of a process boundary.

  • Headless docx to PDF, no Word, no LibreOffice. docx4j converts via XSL-FO and its own fork of Apache FOP, including Tagged PDF, PDF/A and PDF/UA output. The Python options are docx2pdf (requires Word), LibreOffice headless (fidelity and operational pain), or paid conversion APIs.
  • OpenDoPE. Content-control binding with repeats, conditions, position conditions and template composition, and a reverter for round-tripping edited documents. docxtpl's Jinja-tags-in-runs approach is string templating inside a format that fights it.
  • PowerPoint and Excel, typed. pptx and xlsx in the same object model. In docx4j for Python they're planned.
  • The surrounding machinery. docx to HTML, XHTML import, digital signatures, diffing, anonymization, TOC generation and field updating, and merging (with the commercial MergeDocx).

The routes across the boundary

JPype: an in-process JVM
A JVM inside the Python process; Java classes look like Python objects. The usual choice for scripts, notebooks and batch jobs, and what the examples below use. One JVM per process (it can't be restarted), and its memory sits alongside Python's. docx4j for Python shares the process happily: hand the document across as bytes.
A small service or CLI wrapper
The production answer: wrap the docx4j operations you need behind a tiny HTTP service or CLI and call it like any other service. You get a clean process boundary, a warm JVM and independent scaling.
Py4J
A socket gateway to a separately running JVM (PySpark's mechanism): the JVM stays long-lived but out of process, without designing a REST API.
GraalPy
Python on GraalVM with direct Java interop; check your C-extension needs before committing. (Jython is Python 2 only, so avoid it.)

Edit in Python, PDF from Java

docx4j for Python fills the template and Java docx4j renders it, the document passing between them as bytes:

from docx4j_py import load

pkg = load("invoice2013.docx")
pkg.custom_xml_parts.fill({
    "/invoice[1]/customer[1]/company[1]": "Acme Manufacturing Ltd",
})
data = pkg.save()                       # bytes, no file

import jpype, jpype.imports
jars = ["docx4j-bundle-17.3.4.jar", "docx4j-bundle-extras-17.3.4.jar"]
jpype.startJVM(classpath=jars)

from java.io import ByteArrayInputStream, FileOutputStream
from org.docx4j import Docx4J
from org.docx4j.openpackaging.packages import WordprocessingMLPackage

wml = WordprocessingMLPackage.load(ByteArrayInputStream(data))
out = FileOutputStream("invoice.pdf")
Docx4J.toPDF(wml, out)
out.close()

OpenDoPE data binding in eleven lines

import jpype, jpype.imports
jpype.startJVM(classpath=["docx4j-bundle-17.3.4.jar"])

from java.io import File
from org.docx4j.openpackaging.packages import WordprocessingMLPackage
from org.docx4j.model.datastorage import OpenDoPEHandler, BindingHandler

pkg = WordprocessingMLPackage.load(File("invoice-template.docx"))
odh = OpenDoPEHandler(pkg); pkg = odh.preprocess()   # repeats + conditions
bh = BindingHandler(pkg)                             # data binding
bh.setStartingIdForNewBookmarks(odh.getNextBookmarkId())
bh.applyBindings(pkg.getMainDocumentPart())
pkg.save(File("invoice-out.docx"))

That's a repeating-row invoice template, expanded and populated from its XML data, the kind of job that in docxtpl means hand-managing Jinja tags inside table rows.

Every example on this page was tested with Python 3.14, Java 21, docx4j for Python 0.2.0 and JPype 1.7.1 from PyPI, and docx4j 17.3.4's two bundle jars from Maven Central. The templates are from docx4j's samples, sample-docs/databinding/: invoice2013.docx, and invoice.docx as invoice-template.docx.

Full setup for the JVM routes, covering the jars, the PDF configuration, logging and practical notes, is maintained with the code: docs/Docx4j_from_Python.md in the docx4j repository.

Frequently asked questions

Is there a Python version of docx4j?
Yes: docx4j for Python, pip install docx4j, imported as docx4j_py. It's a port, not a wrapper, so no JVM is involved. The object model is generated from docx4j's schemas by a fork of xsdata, the engine is written by hand in Python, and the design follows docx4j-core-ts, docx4j's TypeScript engine. Names, defaults and quirks are docx4j's unless a recorded change request says otherwise. Version 0.2.0 handles .docx only.
Will my python-docx code run on docx4j for Python?
Mostly, after changing the imports: 305 of python-docx 1.2.0's 312 public members are there, with python-docx's names and semantics, and each of the other seven is refused with a reason. python-docx is not a dependency.
Can Python convert docx to PDF without Microsoft Word or LibreOffice?
Not natively: docx2pdf requires Word, and docx4j for Python doesn't render PDF yet. Call Java docx4j as shown above, with the bundle jar plus docx4j-bundle-extras, then Docx4J.toPDF; it writes Tagged PDF, PDF/A and PDF/UA too.
When should I stay with python-docx or docxtpl instead?
When the job is generating a document from a simple template or setting some formatting: python-docx and docxtpl are small, quick to import and well known. Not for reading the text of documents you didn't write, though: see the next question.
How do I extract the text of a .docx in Python?
To get the text Word shows, use docx4j for Python's text model, plain_text(extract(load(path))), as above. python-docx's Paragraph.text loses tracked insertions and everything in content controls, includes hidden text, and doesn't reach text boxes or notes.
Is there a single jar I can point JPype at?
Yes. The docx4j-bundle jar on Maven Central is self-contained for loading, manipulating, binding and saving docx, pptx and xlsx, and from 17.3.4 it holds digital signatures and Markdown too. For PDF output, put docx4j-bundle-extras of the same version beside it, and not Apache FOP's own jars.
What does the JVM cost me operationally?
A second runtime to start (start it once per process), its heap alongside Python's, and Java exceptions to translate at the boundary. For production loads, the service-wrapper route moves all of that out of your Python processes entirely.
Why not just run LibreOffice headless for PDF?
It works until it doesn't: conversion fidelity varies with the LibreOffice version, and a crashed soffice process is a familiar operational headache. FOP-based conversion is a library call: deterministic, headless, and configurable down to PDF/A and PDF/UA.
Where does the "twenty years of edge-case handling" claim come from?
docx4j has been developed continuously since 2007, in the open: the repository, its history and its issue record are all inspectable, and so are docx4j for Python's. See why that openness matters more than ever.

See also