Skip to content

About

Create and manipulate Word .docx files in Python through a complete, schema-generated OOXML object model, in the style of docx4j.

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

docx4j-python

docx4j for Python: the whole of ECMA-376 as typed objects, generated from docx4j's own schema tree by a fork of xsdata, and docx4j's Open Packaging engine written by hand over them: .docx in, typed parts and relationships, .docx out. The classes carry docx4j's names (P, R, Text, PPr, Tbl, Document, Styles), so fifteen years of docx4j documentation and examples read across. The design is the same as docx4j-core-ts, so the two read across too.

Status: the object model (CR-001 Phases A to C), the Open Packaging engine (CR-002 Phase A) and the content API (CR-003 Phase A, the tree-layer builders; Phase B, Body, Paragraph, Range and Font in Office JS's vocabulary; Phase D, the agent surface — addresses, outline(), find(), describe(), ChangeReport, dry_run and DocumentSession; Phase K, markdown in and out; Phase C, tables, pictures, insert_ooxml and content controls; Phase G, comments; Phase F, change tracking and replace_text; and Phase E, custom XML parts, XML mapping, the typed content-control kinds and describe() / fill(); Phase H, lists, with docx4j's numbering emulator under them; Phase I, to_api_script, the reveal codes of this API; and Phase J, the python-docx facade) are in --- every phase of CR-003 is implemented. Over 16 real documents, every part not touched is written back byte for byte, all 141 typed WordprocessingML parts unmarshal and re-serialise canonically identical to the source, and nothing is dropped. Saved output opens in Word.

WordprocessingML only, for now. .pptx and .xlsx load and save through the generic OPC path, every part byte for byte, but nothing in them is typed: PresentationML and SpreadsheetML are CR-001 Phase D (the object model) and CR-002 Phase C (the engine), with their content APIs in CR-004 and CR-005. The package is on PyPI as docx4j (pip install docx4j; the import name is docx4j_py, as python-docx imports as docx), released by CR-007 with docs/pypi-readme.md as its page --- a short version of this file whose every example the test suite executes. The "how do I" answers --- hyperlinks, document properties, find and replace --- are under docs/user/.

from docx4j_py import load

pkg = load("in.docx")                                # a WordprocessingMLPackage; the kind is sniffed
body = pkg.body                                      # Word.Body over word/document.xml

text = body.text                                     # Office JS's body.text: a mark \r per paragraph
print(text.replace("\r", "\n"))                      # split paragraphs with split("\r"), not splitlines()
for paragraph in body.paragraphs:                    # tables and content controls descended into
    print(paragraph.style, paragraph.text)

title = body.insert_paragraph("Report", location="Start", style="Heading 1")
title.alignment = "Centered"
hit = body.search("quick brown fox")[0]              # matches span runs freely
hit.font.italic = True                               # the runs are split at the boundaries
hit.insert_text("slow red fox")                      # Replace is a Range's default location
body.paragraphs[-1].insert_paragraph("The end.")     # After is a Paragraph's

pkg.save("out.docx")                                 # only the parts you touched are re-marshalled

The text is Office JS's, in Word's own characters (CR-013 Phase A): body.text ends each paragraph with \r and writes a table's cells a \t apart and its rows ended \r\n, as do a cell's value, a block control's text and a comment's content; in a paragraph a line break is U+000B, a page break U+000C, a note reference U+0002, and hidden text is left out. str.splitlines() splits at U+000B too, so split paragraphs with split("\r"). Every text writer takes the characters back as the elements they read from, and refuses U+0002.

A part that is never touched is written back byte for byte; reading contents --- which pkg.body does for word/document.xml --- marks a part for re-marshalling. Everything is synchronous. load takes a path, bytes, a file object or a PartStore; save takes a path, a file object or nothing (bytes), and saving over the file you loaded is fine.

From nothing to a .docx

from docx4j_py import create_package

pkg = create_package()                                       # docx4j's createPackage: A4, one section
pkg.body.insert_paragraph("Hello World")
pkg.save("hello.docx")

Longer, with the verbs of Office JS's Word.Body (docx4j_py.model.content, CR-003):

from docx4j_py import create_package

pkg = create_package(page_size="A4")        # docx4j's createPackage: one section, its default styles
body = pkg.body

body.insert_paragraph("Created by docx4j-python", style="Heading 1")
paragraph = body.insert_paragraph("One paragraph, three runs")
paragraph.search("three runs")[0].font.italic = True
body.insert_break("Page")

table = body.insert_table(3, 2, values=[["Name", "Value"], ["a", "1"]], style="TableGrid")
table.header_row_count = 1                   # w:tblHeader on the leading rows
table.add_rows(1, values=[["b", "2"]])       # the table's own columns and widths
table.values                                 # [['Name', 'Value'], ['a', '1'], ['', ''], ['b', '2']]
table.cell(1, 1).text                        # '1'
table.cell(1, 1).address                     # 'body/3/1/1' --- table, row, cell
table.cell(1, 1).paragraphs[0].ordinal       # 'body/3/1/1/0' --- the cell's own body, addressed
pkg.save("hello.docx")

The columns are equal over the section's text width, taken from w:sectPr, and the grid sums to it exactly; no style is set unless style= is given, so a new table is borderless until table.style_built_in = "TableGrid". TableCell.body is a Body like any other, so cell.insert_paragraph(...), cell.body.search(...) and the addresses all carry on into it.

python-docx code runs

The API in every tutorial and in every model's memory is python-docx's, so docx4j_py.docx is a structural subset of it (CR-003 section 3.6 and section 20) --- python-docx's names, python-docx's semantics, this engine underneath:

from docx4j_py.docx import Document, Pt

doc = Document("in.docx")                             # or Document() for a new one
doc.add_heading("Report", level=1)                    # a built-in style it lacks is defined
p = doc.add_paragraph("Plain, ")
p.add_run("bold").bold = True
p.add_run(" and off").bold = False                    # python-docx's tri-state: w:b w:val="0"
p.runs[1].font.size = Pt(14)                          # a Length of EMU, as python-docx has it
p.style = "Heading 2"                                 # the display name, as python-docx
doc.add_table(rows=2, cols=2, style="Table Grid").cell(0, 0).text = "a"
for paragraph in doc.paragraphs:
    print(paragraph.style.name, paragraph.text)

print(doc.package.last_change.to_dict())              # a ChangeReport per call: an extension
print(type(p._p).__name__, doc.part.body.text[:23])   # the typed P, and the Office JS Body
doc.save("out.docx")

The last two lines are what python-docx code gets here that python-docx does not have: the whole schema (paragraph._p is the typed P, not lxml), parts never touched written back byte for byte, a ChangeReport for every mutation, dry_run, tracked changes, comments, lists, addresses and custom XML, all of it through doc.package and doc.part.body. Paragraph, Run, Font, Table, _Cell, Section with its headers and footers, Styles, CoreProperties, Comment, the Length units and the WD_* enums are all there; the promise is a committed member list (tests/python_docx_subset.json, derived by introspecting python-docx 1.2.0: 305 of its 312 members implemented, eight refused with a reason each) and a parity test that runs one script through both libraries and lets python-docx read both files back. python-docx itself is not a dependency. The Office JS vocabulary above remains the primary API; this namespace exists so that code already written, by people or by models, runs. One semantics is better than python-docx's: a Length Word would misread (a page 500 cm wide, a 5,000 pt space before; Word keeps the low 16 bits) is refused with Word's range, where python-docx writes the broken file (CR-022).

Setting a style --- paragraph.style, style_built_in, or style= on insert_paragraph and insert_table --- adds the definition when the style is one of Word's built-ins and the document does not define it (docx4j's KnownStyles.xml, and /word/styles.xml shows up in the ChangeReport's parts_touched). Word renders a dangling w:pStyle as Normal rather than creating the style, so writing the id alone would lose it silently. A custom name the document does not define is refused, with the five closest names; style_id is the escape hatch and writes the id exactly as given. Reading a style unmarshals nothing.

create_package writes docProps/app.xml (Application, AppVersion) and docProps/core.xml (created, modified); author and title are yours to set on those parts' contents.

The tree stays reachable. Nothing is wrapped: paragraph.element is the P, body.content is the live ChildList, and the low-level route of CR-001 works exactly as it did, on the same objects the views hand out.

from docx4j_py.wml import p, r, tbl, br, text_of

document = pkg.main_document_part.contents               # unmarshalled on first access, as docx4j does
body = document.body                                     # the typed w:body; pkg.body is the view over it
body.content.append(p("Plain, ", r("bold", bold=True), r(" and red.", color="FF0000")))
body.content.append(tbl([["Name", "Value"], ["a", "1"]], style="TableGrid"))
text_of(document)                                        # docx4j TextUtils, over any subtree

Adding an image

One call does the three steps: the ImagePart under the first free /word/media/imageN.<ext>, the relationship from the part the body belongs to (a picture in a header is related from the header), and the w:drawing sized from the image's own header --- PNG, JPEG, GIF and BMP, read here, no Pillow --- and scaled down to the text column as docx4j's CxCy.scale does. Sizes are points, as Office JS reports them.

picture = body.insert_inline_picture(png_bytes, width=180, alt_text_description="A pangolin")

picture                                      # <InlinePicture w14:6FA720E8 Png 180x131.294pt 'A pangolin'>
                                             # (the paraId is the package's; set pkg.id_seed to fix it)
picture.image_part.part_name                 # /word/media/image1.png
picture.rel_id, picture.image_format         # ('rId3', 'Png')
picture.width, round(picture.height, 1)      # (180.0, 131.3) --- the ratio is kept
picture.get_bytes() == png_bytes             # True; get_base64() is the base64 twin
pkg.last_change.parts_touched
# ('/word/document.xml', '/word/media/image1.png', '/word/_rels/document.xml.rels')

paragraph.insert_inline_picture(data, location="Start" | "End" | "Replace") puts one in a paragraph that already exists, and both verbs have a ..._from_base64 twin.

The part underneath. An image is a part related from the main document part, and the picture refers to it by relationship id; inline_picture writes the w:drawing exactly as docx4j's BinaryPartAbstractImage.createImageInline does, and image_size reads the size and the density out of the header, so the low-level route is there when the parts are what you are working on:

from docx4j_py.openpackaging import ImagePart, AddPartBehaviour
from docx4j_py.wml import el, r, emu_for, image_size, inline_picture

main = pkg.main_document_part
image = ImagePart("/word/media/image1.png")
image.set_bytes(png_bytes)
rel = main.add_target_part(image, AddPartBehaviour.RENAME_IF_NAME_EXISTS)   # rel.id is the r:embed

size = emu_for(image_size(png_bytes), max_width_emu=5731510)   # scaled to the text column
body.content.append(el.p(content=[
    r(inline_picture(rel.id, cx=size.cx, cy=size.cy, id=1, name="image1.png", descr="A pangolin"))
]))

wml("<w:p><w:r><w:drawing>…") still takes the whole thing as a fragment when you want to write the XML yourself; it declares docx4j's prefix table for you.

scripts/acceptance.py builds exactly this, and five other documents, for the manual Word checklist in tests/README.md.

Pasting a whole package, and reading content controls

insert_ooxml takes what Word's clipboard and Office JS's insertOoxml hand over: a flat OPC pkg:package string. Every part its content references is copied in under a free name with a fresh relationship id, its own relationships copied recursively keeping their ids, and the references in the inserted content rewritten --- by attribute name, and only where the incoming package really has a relationship of that id, so a numeric wp:docPr/@id is never touched. Styles and numbering are not merged: that is docx4j's MergeDocx. A bare w:p / w:tbl fragment is accepted too, which is what insert_xml takes.

from docx4j_py import load

pkg = load("in.docx")
views = pkg.body.insert_ooxml(package_xml)   # or "<w:p><w:r><w:t>plain</w:t></w:r></w:p>"

[type(view).__name__ for view in views]      # ['Paragraph', 'Paragraph']
[view.address for view in views]             # ['w14:4FBB3E23', 'w14:20B26C1D']
pkg.last_change.parts_touched                # ('/word/document.xml', '/word/media/image1.png')
pkg.body.inline_pictures[0].rel_id           # 'rId7' --- fresh, and the drawing was rewritten to it

ContentControl reads a w:sdt in all four of its forms --- block, run, row and cell --- and a row- or cell-level one is transparent to Table.rows and TableRow.cells, which is how an OpenDoPE repeat reads as the rows Word shows:

pkg = load("samples/invoice2013.docx")
controls = pkg.body.content_controls        # 22, in document order, nested ones included

control = controls[1]
control                                      # <ContentControl body/2/0/0/0/0 PlainText
                                             #  '/invoice[1]/customer[1]/contact[1]' 'John Citizen'>
control.type, control.form                   # ('PlainText', 'run')
control.get_range()                          # <Range 0:12 'John Citizen'> --- exact, for a run control
repeat = next(c for c in controls if c.form == "row")
repeat.tables[0].values[0]                   # ['productcode', 'description', 'quantity', 'price']

control.delete() keeps what the control held and puts it where the control was, as Word's "remove content control" does; delete(keep_content=False) takes the content with it.

Filling a template

A Word template is a document whose content controls are bound to nodes of a custom XML part, and filling one in is two calls. describe() says what the template wants --- the XPaths it binds, the kind of control that shows each, the repeats, and the value the data holds now --- and fill() sets the nodes and applies the bindings, which is what Word itself does on open.

from docx4j_py import load

pkg = load("samples/invoice2013.docx")

skeleton = pkg.custom_xml_parts.describe()
len(skeleton)                                # 20 bindings
skeleton.repeats                             # ('/invoice[1]/lines[1]/lineitem[1]',
                                             #  '/invoice[1]/notes[1]/note[1]')
skeleton.parts[0].id                         # '{5D7BA57F-1E52-4637-9F82-2D4025768D4F}'
binding = skeleton.bindings[1]
binding.xpath, binding.kind, binding.value   # ('/invoice[1]/customer[1]/contact[1]',
                                             #  'PlainText', 'John Citizen')

result = pkg.custom_xml_parts.fill({
    "/invoice[1]/customer[1]/company[1]": "Acme Manufacturing Ltd",
    "/invoice[1]/invoicenumber[1]": "INV-2026-0917",
    "/invoice[1]/VAT[1]/@applies": "false",
})
result                                       # <FillResult 3 set, 0 skipped, 16 bound>
pkg.save("invoice-filled.docx")

Word refreshes a bound control from its data when it opens the document, so the saved file shows the new values either way; fill() applies them there and then, so that the same document read back through this library shows them too:

controls = {c.title: c for c in pkg.body.content_controls}
controls["/invoice[1]/customer[1]/company[1]"].text   # 'Acme Manufacturing Ltd'
controls["/invoice[1]/VAT[1]/@applies"].text          # '☐' --- the checkbox glyph, MS Gothic
[c for c in pkg.body.content_controls
 if c.type == "DatePicker"][0].text                   # '29 January 2015' --- w:dateFormat, applied

describe() and fill() are the shorthand; the whole WordApiDesktop 1.3 surface is underneath. pkg.custom_xml_parts is a collection of CustomXmlParts with get_item (brace- and case-insensitive, because Word writes the store item id both ways), add(xml) and apply_bindings(); a part's nodes are CustomXmlNodes with the DOM's members and lxml's XPath; and control.xml_mapping reads and writes the w:dataBinding:

part = pkg.custom_xml_parts.get_item("{5D7BA57F-1E52-4637-9F82-2D4025768D4F}")
part.select_single_node("/invoice[1]/customer[1]/company[1]").text   # 'Acme Manufacturing Ltd'

Reading a custom XML part costs nothing: a part that is only read is written back byte for byte, and only a mutation makes it re-marshal.

The object model

Every element name has a constructor in the namespace's el module, generated from the class metadata so it always returns the right class for that element; p, r, t, tbl, tr, tc, br and tab are the hand-written sugar on top:

from docx4j_py.wml import el, p, r, t, P, R, Text, Tbl, Drawing

el.p(content=[el.r(content=[el.t("Hello World")])])   # docx4j's ObjectFactory, one function per element
el.t("  two spaces  ")                                # xml:space="preserve" set for you
el.pPr(); el.sdt_run(); el.del_(); el.t_math()        # 604 names in wml: scope-qualified (sdt_run) and
                                                      # keyword-renamed (del_) where they have to be
r("bold", bold=True, size=12, color="FF0000", underline="Single", font="Arial")   # Office JS names, as docx4j-core-ts

Fragments and XML: wml(...) parses one element written as it would appear inside document.xml, with the standard prefixes declared for you (docx4j's XmlUtils.unmarshalString with W_NAMESPACE_DECLARATION); to_xml is the inverse. Parsing is strict by default: anything the model would drop raises, lenient=True reports it instead.

from docx4j_py.wml import wml, to_xml

para = wml('<w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr>'
           '<w:r><w:rPr><w14:glow w14:rad="101600"><w14:srgbClr w14:val="FF0000"/></w14:glow></w:rPr>'
           '<w:t>Hello</w:t></w:r></w:p>')
paras = wml.all("<w:p>...</w:p><w:p>...</w:p>")     # several siblings
to_xml(para)                                        # declarations trimmed to what the fragment uses

Marshalling goes the other way for any object in the tree, a P say, with to_xml (docx4j XmlUtils.marshaltoString); the part as a whole is part.xml, the bytes save would write:

from docx4j_py.wml import find, P, p, r

second = find(document, P)[1]                       # a paragraph from the loaded document
print(to_xml(second, pretty=True))
<w:p xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" w:rsidR="00D15781" w:rsidRDefault="00945132">
  <w:r>
    <w:t>This is a document exhibiting basic docx features.</w:t>
  </w:r>
  <w:r w:rsidR="00665DAE">
    <w:t xml:space="preserve">  </w:t>
  </w:r>
</w:p>
print(to_xml(p("Hello ", r("World", bold=True), style="Heading1"), pretty=True))
<w:p xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
  <w:pPr>
    <w:pStyle w:val="Heading1"/>
  </w:pPr>
  <w:r>
    <w:t xml:space="preserve">Hello </w:t>
  </w:r>
  <w:r>
    <w:rPr>
      <w:b/>
      <w:bCs/>
    </w:rPr>
    <w:t>World</w:t>
  </w:r>
</w:p>
main.xml                                            # bytes: the whole word/document.xml, as save() writes it
repr(second)                                        # the dataclass: P(p_pr=None, content=[R(r_pr=None, content=[RT(value='This is ...

Traversal is metadata-driven, so it needs no per-class code and covers every namespace:

from docx4j_py.wml import (text_of, walk, walk_all, find, iter_nodes, run_items_of,
                           deep_copy, deep_copy_as, PPrBase)

text_of(document)                          # w:t, w:tab, w:br, w:sym; w:delText and fields excluded, as docx4j
find(document, P)                          # docx4j ClassFinder; isinstance, so subclasses match
find(document, (Tbl, Drawing))
walk(document, lambda node, parent, name: print(name))   # docx4j TraversalUtil; return False to stop descending
for node in iter_nodes(document): ...
walk_all(document, on_node, on_wildcard)   # and into the xs:any content, where a stray r:embed hides
run_items_of(para)                         # the run list of a w:p, w:hyperlink, w:ins, w:sdt, ...

copy = deep_copy(para)                     # the subtree, not the document; copy.parent is None until placed
base = deep_copy_as(para.p_pr, PPrBase)    # a copy re-typed as a base class, so no xsi:type is written

Content controls have their own builders, over a w:sdtPr the model keeps as one choice list, as docx4j does:

from docx4j_py.wml import p
from docx4j_py.wml.sdt import sdt, sdt_property, sdt_kind_of, next_sdt_id   # the module, not the package: see CR-003 section 11

control = sdt([p("Acme Ltd")], kind="RichText", tag="customer", id=next_sdt_id(document))
sdt_kind_of(control.sdt_pr)                # Office JS Word.ContentControlType: 'RichText'
sdt_property(control, "dataBinding")       # looks in w: and w15:, because Word writes w15:dataBinding

Every object is a Child: it knows its parent (node.parent), and appending to a content list sets the child's parent, as docx4j's ArrayListDocx4j does. Objects are slotted dataclasses; equality and repr ignore the parent, and so does serialisation.

A content list also refuses what its element cannot hold, at the line that adds it, as docx4j's checkParent does (CR-020): every typed list checks what code appends, inserts, extends or sets against what the schema allows there, and raises MisplacedContentError (target.misplaced, a TypeError too) with where the item goes. Word refuses to open most such files outright (11 of 18 in docx4j-core-ts's check 72) and repairs the rest, once losing text. A load is never checked: a file is read as written. unchecked() builds a forbidden tree on purpose, and misplaced() walks a tree, a part or a package for what got past the check: a list assigned whole, a single field, a table cell that does not end with a paragraph, an integer measurement Word would misread. save(check=True) refuses a save that would write what the session introduced, and writes nothing.

from docx4j_py import create_package
from docx4j_py.child import unchecked
from docx4j_py.model.content import MisplacedContentError, SaveCheckError
from docx4j_py.traversal import misplaced
from docx4j_py.wml import r, tbl

run = r("text")
try:
    run.content.append(tbl([]))            # a table inside a run
except MisplacedContentError as error:
    print(error.code, error.hint)          # target.misplaced a table is the paragraph's sibling: put it in the body, ...

with unchecked():                          # a broken Word file, reproduced on purpose
    run.content.append(tbl([]))
print([finding.code for finding in misplaced(run)])     # ['target.misplaced']

doc = create_package()
doc.body.insert_paragraph("Checked").element.content[0].content = [tbl([])]   # a whole list, past the check
print([finding.to_dict()["path"] for finding in doc.misplaced()])  # ['/w:document/w:body[1]/w:p[1]/w:r[1]/w:tbl[1]']
try:
    doc.save("checked.docx", check=True)   # off by default
except SaveCheckError as error:
    print(error.code)                      # target.misplaced, and checked.docx is not written

The engine

from docx4j_py.openpackaging import (
    OpcPackage, WordprocessingMLPackage, LoadOptions, PartName,
    ImagePart, DefaultXmlPart, AddPartBehaviour, ContentTypes, Namespaces,
    ZipPartStore, DirectoryPartStore, MemoryPartStore, MemoryPartSink,
)

pkg = OpcPackage.load("in.pptx")                  # anything OPC loads; .docx comes back as WordprocessingMLPackage
pkg.parts["/ppt/presentation.xml"]                # case-insensitive, as OPC says; untyped parts are DefaultXmlPart (lxml)
pkg.content_type_manager.get_content_type("/ppt/slides/slide1.xml")
pkg.relationships_part.get_relationships_by_type(Namespaces.DOCUMENT)   # docx4j's constant names

with load("in.docx") as pkg:                      # a context manager: the zip stays open for lazy loads
    part = pkg.get_part("/word/settings.xml")
    part.is_unmarshalled                          # False: load cost the relationships and content types, nothing else
    settings = part.contents                      # now True, and this part will be re-marshalled on save
    part.skipped                                  # what lenient parsing dropped from it: empty is the norm
    pkg.skipped                                   # the same, over every unmarshalled part
    pkg.unmarshal_all()                           # for callers who prefer no laziness
    pkg.save()                                    # bytes
    pkg.save_to(MemoryPartSink())                 # or any sink: a directory, a zip, memory

load("in.docx", options=LoadOptions(strict=True))              # raise on the first dropped node instead
load("in.docx", options=LoadOptions(mce_preprocess=True))     # resolve mc:AlternateContent on read, as docx4j does

Markup compatibility: by default both branches of every mc:AlternateContent are kept, so an unmarshalled part loses nothing on save. The branches are wildcard content, which means a w:drawing inside one is not a typed Drawing until you opt into mce_preprocess=True, which replaces each mc:AlternateContent with the branch Word would take, as docx4j's preprocessor does. The traversal functions take mce="resolve" (default, descend into the understood mc:Choice, else the mc:Fallback), "all" or "none".

A document from create_package() targets Word 2013 and later: its w:settings carries compatibilityMode 15 (which is what Word 2016, 2019 and 365 write too — there is no 16) and the five settings Word writes beside it, so Word does not open it in Compatibility Mode. pkg.compatibility_mode reads it on any document — 14 for a Word 2010 one, and 12 when the document declares nothing, which is what Word assumes — and pkg.compatibility_mode = 15 (11, 12, 14 or 15) changes it. Reading unmarshals nothing; writing re-marshals /word/settings.xml and is reported. A verb that writes a Word 2013 feature into an older document — a resolved comment, a repeating section, a w15:dataBinding — writes it and says so in that call's ChangeReport.warnings, naming the fix; the mode is never changed behind the caller.

Under docx4j_py.openpackaging: PartName (OPC part names, case-insensitive equality, relationship target resolution), ContentTypeManager and ContentTypes, RelationshipsPart with add_part / add_relationship / remove_part and docx4j's AddPartBehaviour, Namespaces for the relationship types, PartRegistry (content type to part class, extensible), the typed WordprocessingML parts (MainDocumentPart, StyleDefinitionsPart, NumberingDefinitionsPart, FontTablePart, DocumentSettingsPart, HeaderPart, FooterPart, FootnotesPart, EndnotesPart, CommentsPart and the w15 and w16 comment parts, GlossaryDocumentPart, ThemePart, the three DocProps*Parts, chart and diagram parts), and CustomXmlDataStoragePart, VMLPart and DefaultXmlPart as lxml trees.

For agents

An agent cannot hold a Python object across tool calls, and a 200-page document does not fit in its context window. So the API gives it addresses — strings that survive an edit — and budgets on everything it reads. Four calls are the whole loop: read the outline, find the text, edit by address, check the report.

from docx4j_py import load

pkg = load("in.docx")

outline = pkg.outline()                       # small, structured, enough to choose an address from
outline.to_markdown()                         # the cheapest thing to show a model
outline.stats.to_dict()                       # {'paragraphs': 412, 'tables': 9, 'words': 11_204, ...}
outline.to_json()                             # under 64 KB for a 200-page document

hits = pkg.find("quick brown fox")            # matches with their addresses and 40 characters either side
hits[0].address, hits[0].snippet              # ('w14:5A2B1C3D', '… over the quick brown fox, which …')

paragraph = pkg.paragraph_at(hits[0].address) # 'w14:5A2B1C3D', 'body/3', or contains='Chapter 1'
paragraph.insert_paragraph("Added by an agent.", location="After")

pkg.last_change.to_json()                     # what that call did, for the tool result
pkg.save("out.docx")

Three address forms, accepted wherever a block-level target is and reported everywhere a view is. w14:5A2B1C3D is the w14:paraId Word writes, and it survives every edit including an insert in front of it; body/3 and body/4/0/1/0 (a paragraph in a cell) are the ordinal, stable until something is inserted or deleted before them; contains="Chapter 1" is the first text match. paragraph.address is the paraId when there is one and the ordinal otherwise, paragraph.ordinal is always the ordinal. A document Word has not stamped can be stamped here:

pkg.id_seed = 1234                            # same seed, same ids, same bytes
pkg.body.ensure_para_ids()                    # every paragraph gets a stable handle

(That one re-marshals word/document.xml, because it writes an attribute on every paragraph. A document created with create_package() stamps every paragraph it is given, so nothing is needed there.)

Every mutation says what it did. A ChangeReport is recorded for every content-API call — always, because a server needs one on every call anyway — and costs about 5 µs on a 40 µs insert. pkg.last_change is the last; pkg.changes accumulates until pkg.changes.clear().

pkg.last_change.to_dict()
# {'operation': 'insert_paragraph',
#  'addresses': ['w14:1C24BE5D'],
#  'moved': [['body/4', 'body/5'], ['body/5', 'body/6']],   # the ordinals that shifted
#  'created_para_ids': ['1C24BE5D'],
#  'text_after': 'Added by an agent.',
#  'parts_touched': ['/word/document.xml'],
#  'at': '2026-09-16T12:46:08.749252+00:00'}

Try it first. A dry_run applies the calls to a deep copy of the parts it touches and throws the copy away; the real package is byte for byte what it was.

with pkg.dry_run() as trial:
    count = trial.body.replace_text("colour", "color")
    preview = trial.last_change.to_dict()      # what it would do

pkg.body.replace_text("colour", "color")       # commit, having seen the number

What can I use here? describe() is docx4j-mcp's describe_template widened to any document: the styles it defines and which it uses, the page, the parts, the comment and revision authors, whether tracking is on. It reads every part as bytes with lxml, so it unmarshals nothing and an untouched part stays byte for byte.

description = pkg.describe()
description.style_names(kind="paragraph", in_use=True)   # ['Heading 1', 'Heading 2', 'Caption', ...]
description.page.width_pt, description.page.orientation  # (595.3, 'portrait')
description.authors                                      # {'comments': [...], 'revisions': [...]}

Budgets everywhere, and when a result is cut the dataclass says so: outline(depth=, max_chars=80, headings_only=True, limit=300), find(context=40, limit=20), get_text(max_chars=), and text_budget(max_chars) for the caller who needs the flag rather than the string.

Errors say what to do instead. Every one carries a stable code, the message, and a hint an agent can act on: an address that is gone names the nearest surviving one, an element a container cannot hold names what it takes, a style that does not exist lists the five closest names, a span that crosses a hyperlink says where to split, a measurement Word would misread names Word's range in the caller's units (Word stores twips in 16 bits and keeps the low 16 of anything larger, so an indent of 400,000 pt would read as -3,959 twips; every setter that writes an integer measurement refuses it instead, before changing anything, at Office JS's limits where Office JS has them and Word's measured range elsewhere; CR-022).

pkg.element_at("body/99")
# AddressError: nothing at 'body/99'; the nearest surviving address is 'body/6'
#               (use 'body/6', or call outline() to list current addresses)

paragraph.left_indent = 400000
# MeasureRangeError: left indent 400000 pt (8,000,000 twips) is beyond Word's range,
#                    -1,638.4 to 1,638.35 pt (pass a left indent from -1,638.4 to 1,638.35 pt)

Reveal codes. to_api_script(target) is the other direction: shown a document, it writes the content-API calls that would make it, as Python against a name body. An agent that has to edit a document learns the verbs from the document in front of it, and what no verb expresses comes out as one insert_xml with a comment saying which construct forced it — decided per block, so a paragraph comes out whole either way. Paragraph, Range and Table have it too, and limit= is the budget.

print(pkg.body.to_api_script(addresses=True))
# # body/0
# p1 = body.insert_paragraph("Quarterly Report")
# p1.style_built_in = "Heading1"
# p1.alignment = "Centered"
#
# # body/1
# p2 = body.insert_paragraph("Revenue rose ")
# r1 = p2.insert_text("12%")
# r1.font.bold = True
# r2 = p2.insert_text(" this quarter.")
# r2.font.bold = False
#
# # body/2
# # w:hyperlink in the paragraph: as XML
# body.insert_xml("""<w:p xmlns:w="…"><w:hyperlink r:id="rId9">…</w:hyperlink></w:p>""")

from docx4j_py import create_package
exec(pkg.body.to_api_script(), {"body": create_package().body})   # and it runs, as it stands

The audit trail

An agent that edits a document should leave the trail Word already has: tracked changes for what it did and a comment for why, in the document, where the human who opens it will see it — not in a chat log they will never read. That is what pkg.author, pkg.change_tracking_mode and insert_comment are for, and CR-003 calls it the single most useful thing this API does for an AI workflow.

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

pkg = load("in.docx")
pkg.author = Author("Claude", initials="C", email="claude@example.com")
pkg.change_tracking_mode = "TrackAll"          # every edit from here is a revision

hit = pkg.find("first")[0]                     # edit by address, as an agent does
pkg.paragraph_at(hit.address).insert_text("Reviewed. ", location="Start")

with pkg.dry_run() as trial:                   # how many would it touch?
    trial.body.replace_text("document", "report")
# 1
pkg.body.replace_text("document", "report")    # and now for real, as a w:del and a w:ins
# 1

pkg.find("report")[0].range(pkg.body).insert_comment(
    "Changed 'document' to 'report': the brief asks for a report."
)

pkg.get_tracked_changes()
# [<TrackedChange Added 'Claude' body/0 'Reviewed. '>,
#  <TrackedChange Deleted 'Claude' body/0 'document'>,
#  <TrackedChange Added 'Claude' body/0 'report'>]

pkg.get_tracked_changes()[1].to_dict()
# {'type': 'Deleted', 'author': 'Claude', 'date': '2026-09-17T01:07:23+00:00',
#  'text': 'document', 'id': 2, 'kind': 'run_deletion', 'address': 'body/0',
#  'part': '/word/document.xml'}

pkg.body.paragraphs[0].text                    # the accepted view
# 'Reviewed. My first 2010 report.'
pkg.body.paragraphs[0].get_text(view="original")
# 'My first 2010 document.'
pkg.save("out.docx")

A human reviews that in Word, with Review → Accept and Reject, exactly as they would a colleague's edits; nothing about the markup says it came from a program except the author name you chose. accept_all() and reject_all() on a body do the same thing here, as Word's own Accept All and Reject All do (docx4j_py.model.revisions, the port of docx4j's org.docx4j.model.revisions, held to Word's saves; CR-010): the changes are grouped as Word's Review pane lists them, a field or an inserted content control goes whole, a move goes by its name, a deleted paragraph mark joins the next paragraph, and a note, a comment, a bookmark or an image goes with the content that held it. docx4j_py.model.revisions.accept_all(pkg) does it in every story --- headers, footers, notes and comments too:

pkg.body.accept_all()
# 3
pkg.body.paragraphs[0].text
# 'Reviewed. My first 2010 report.'
[c.content for c in pkg.body.get_comments()]   # the comment survives either way
# ["Changed 'document' to 'report': the brief asks for a report."]

Every mutation is tracked while the mode is on, because the tracking sits in the paragraph-level primitives: insert_text, the text setter, Range.delete, insert_paragraph (whose mark is marked inserted), Paragraph.delete (whose content becomes a w:del and whose mark is marked deleted), insert_table, the row verbs (w:trPr/w:ins and w:trPr/w:del; a deleted row stays in the tree until it is accepted, so row_count still counts it), insert_markdown, insert_inline_picture and the Font and paragraph-property setters, which record the properties as they stood in w:rPrChange and w:pPrChange. Word's rules come with it: a run already inside a w:ins by the same author is extended rather than nested, deleting text that author inserted takes it back, a replacement is the w:del first and the w:ins after it, and the runs are split at the span's boundaries so a partly deleted run is not wholly deleted. Each revision carries its date as Word 365 writes it: w:date on the local wall clock with a Z that does not mean UTC, and the true UTC in w16du:dateUtc, to the minute, with w16du declared in the part's mc:Ignorable; a revision's date reads them back as one instant. pkg.tracked_change_date fixes that instant (a naive datetime is UTC), which is what makes a tracked edit byte-reproducible in a given time zone. The time zone is the package's: pkg.date_time_zone names the client's (a tzinfo or an IANA name, never saved), so a server stamps and reads a revision's and a comment's w:date on its user's clock, not its own; unset, it is the process's (CR-025, the ports' one date rule). pkg.write_times_on_save, off by default, stamps dcterms:modified on each save, as docx4j's docx4j.dcterms.write does.

The comment half is the same identity and a different id space:

pkg = load("in.docx")
pkg.author = Author("Claude", initials="C", email="claude@example.com")

hit = pkg.find("first")[0]                    # the range the agent is about to change
comment = hit.range(pkg.body).insert_comment("Changed 'first' because the source says 'red'.")

pkg.last_change.parts_touched
# ('/word/document.xml', '/word/styles.xml', '/word/comments.xml',
#  '/word/commentsExtended.xml', '/word/commentsIds.xml', '/word/people.xml')

comment.reply("Checked against the source; agreed.")   # a reply in the same thread
comment.resolved = True                                # w15:done, which Word shows as Resolved

pkg.body.get_comments()
# [<Comment 0 body/0 'Claude' "Changed 'first' because the so…" resolved>]
pkg.save("out.docx")

The document had no comment parts at all; insert_comment created four of them — w:comments, w15:commentsEx, w16cid:commentsIds and w:people — with their relationships and content types, and added CommentText, CommentTextChar and CommentReference to styles.xml, because Word renders a style it cannot resolve as Normal. A w16cex:commentsExtensible is kept in step when the document already has one and is never created, which is what Word does.

A comment is a Comment whether it is a comment or a reply, as it is in the file; parent and replies thread them through w15:paraIdParent. The whole thing is one JSON object for a tool result:

comment.to_dict()
# {'id': 0,
#  'author_name': 'Claude', 'initials': 'C', 'author_email': 'claude@example.com',
#  'content': "Changed 'first' because the source says 'red'.",
#  'creation_date': '2026-09-16T23:45:00+00:00',
#  'para_id': '7C98CE4D', 'address': 'body/0', 'resolved': True,
#  'replies': [{'id': 1, 'author_name': 'Claude', 'initials': 'C',
#               'author_email': 'claude@example.com',
#               'content': 'Checked against the source; agreed.',
#               'creation_date': '2026-09-16T23:45:00+00:00',
#               'para_id': '4CD9291E', 'address': 'body/0'}]}

comment.get_range().text                      # exactly what the markers surround, one Range as Office JS's
# 'first'
comment.get_ranges()                          # the same a paragraph at a time
# [<Range 3:8 'first'>]
pkg.body.to_markdown(view="markup")           # the same comments as CriticMarkup
# "My first{>>Changed 'first' because the source says 'red'.<<}{>>Checked against the source;
#  agreed.<<} 2010 document."

get_comments() is on Body, Paragraph, Range and ContentControl; insert_comment(text) on Paragraph (the whole paragraph) and Range (a span, with the runs split at its boundaries). Reading comments unmarshals three parts, writing touches five, and a document whose comments are never read keeps all five byte for byte. A comment is not a revision. On text in a w:ins its markers are written in Word's own form: the range start inside the w:ins, the range end and the reference run after it, the w:ins split there when the comment ends inside it. Accepting the insertion leaves the comment on its text, and rejecting it removes the comment, as current Word does. A comment's w:id comes from its own counter rather than from the revisions'.

Lists

Word.List and Word.ListItem, over w:num and w:numPr. The label is the one Word paints: it comes from the numbering emulator (docx4j's org.docx4j.model.listnumbering, ported here), so a restart, a w:startOverride, a w:lvlRestart and a list numbered through a paragraph style all read correctly — not from a count this library keeps.

from docx4j_py import create_package

pkg = create_package()
body = pkg.body

steps = body.insert_paragraph("Check the invoice total")
checklist = steps.start_new_list()             # a new w:num, and numbering.xml if there is none
body.insert_paragraph("Check the licence key").attach_to_list(checklist.id)
body.insert_paragraph("Ship it by Friday").attach_to_list(checklist.id, 1)   # a level deeper

[p.list_item.list_string for p in body.paragraphs]
# ['1.', '2.', 'a.']
body.paragraphs[2].to_dict()["list_item"]
# {'level': 1, 'list_string': 'a.', 'sibling_index': 0}
pkg.last_change.to_dict()["parts_touched"]     # for start_new_list, three parts
# ['/word/document.xml', '/word/numbering.xml', '/word/styles.xml']

checklist.set_level_numbering(0, "LowerLetter", "%1)")
[p.list_item.list_string for p in body.paragraphs]
# ['a)', 'b)', 'a.']

body.insert_paragraph("A second list").start_new_list(like=checklist)   # Word's "restart at 1"
body.paragraphs[2].detach_from_list()
[(p.text, p.is_list_item) for p in body.paragraphs]
# [('Check the invoice total', True), ('Check the licence key', True),
#  ('Ship it by Friday', False), ('A second list', True)]

body.lists gives one List per w:numId in document order; list.paragraphs, list.get_level_paragraphs(level) and list_item.get_ancestor() / get_descendants() walk it; set_level_numbering, set_level_bullet and set_level_indents are Office JS's level setters, and each copies the w:abstractNum first when another list shares it, so a change stays local. Attaching and detaching go through the paragraph's properties, so with tracking on they record the w:pPrChange Word records for a numbering change.

Markdown, coarse and fine

Markdown is what models read and write best, and it is the exchange format docx4j-mcp settled on. There are two ways to use it, and they are for different jobs.

Coarse: markdown in, markdown out. Cheapest, and it loses whatever the markdown could not carry. CommonMark plus GFM tables and strikethrough, through markdown-it-py (the one dependency this API adds, imported on the first insert_markdown; to_markdown needs nothing).

from docx4j_py import create_package, WordprocessingMLPackage

pkg = create_package()
views = pkg.body.insert_markdown("""# Weekly brief

Three things happened, and one was **important**.

- the build went green
- the corpus grew
  - two new fixtures

| Area | State |
| --- | --- |
| engine | green |

See [the CR](https://example.invalid/cr-003).
""")

[type(v).__name__ for v in views]
# ['Paragraph', 'Paragraph', 'Paragraph', 'Paragraph', 'Paragraph', 'Block', 'Paragraph']
pkg.last_change.to_dict()["parts_touched"]
# ['/word/document.xml', '/word/numbering.xml', '/word/styles.xml']

WordprocessingMLPackage.load(pkg.save()).to_markdown()
# '# Weekly brief\n\nThree things happened, and one was **important**.\n\n- the build went green\n
#  - the corpus grew\n  - two new fixtures\n\n|Area|State|\n|---|---|\n|engine|green|\n\n
#  See [the CR](https://example.invalid/cr-003).\n'

The fragment is one ChangeReport however many blocks it brings; the styles it needs are added from docx4j's KnownStyles.xml if the document lacks them (an existing definition always wins), a list creates the numbering part when there is none, and a link gets an external relationship. An image is never fetched: it becomes a link to its destination, and the report's warnings say so, as they do for an HTML block, which is skipped. Nothing is dropped quietly.

A document can't write markup into what you show. Every to_markdown, markdown() and Outline.to_markdown() treats the document's values as text. A link whose scheme isn't http, https, ftp, mailto, file, news or tel, read as a browser reads it and again with its character references decoded, is written as its text with no link, so javascript:alert(1) is never a destination, and the first of a call is logged on docx4j_py.model.text.markdown. A document with onenote: links passes to_markdown(link_schemes=["onenote"]). It can only add, and it isn't a text option, so a tool's arguments can't reach it unless a server wires them to it. A change's author and date are text too, as are an address comment's value and an outline's entries.

Fine: read with addresses, then edit by one. Nothing outside the blocks the agent names changes, and every untouched part is still written back byte for byte.

from docx4j_py import load
from docx4j_py.model.markdown import ADDRESS_COMMENT

pkg = load("in.docx")

pkg.to_markdown()[:64]
# 'Docx sample document\n\nThis is a document exhibiting basic docx f'

markdown = pkg.to_markdown(addresses=True)      # each block's address on its own line before it
markdown[:120]
# '<!-- body/0 -->\nDocx sample document\n\n<!-- body/1 -->\nThis is a document exhibiting basic docx
#  features.  \n\n<!-- body/2 '

ADDRESS_COMMENT.pattern                         # the regex that recovers one
# '^[ \t]*<!--\\s(?P<address>\\S+)\\s-->$'

address = next(                                 # the model picks the block it wants
    m.group("address")
    for m, text in zip(ADDRESS_COMMENT.finditer(markdown),
                       ADDRESS_COMMENT.split(markdown)[1:], strict=False)
    if text.strip().startswith("# Tables")
)
# 'body/11'

pkg.paragraph_at(address).insert_paragraph("Two tables follow.", location="After")
pkg.last_change.to_dict()
# {'operation': 'insert_paragraph', 'addresses': ['body/12'],
#  'moved': [['body/12', 'body/13'], ... 52 pairs ...],
#  'text_after': 'Two tables follow.', 'parts_touched': ['/word/document.xml'],
#  'at': '2026-09-16T20:35:40.325800+00:00'}

The address is paragraph.address: the w14:paraId when Word has stamped one, so it survives an insert in front of it, and the ordinal otherwise; a text box's paragraph has the text model's body/3/textbox:0/0, which is for reading. view="markup" writes tracked changes and comments as CriticMarkup ({++inserted++}, {--deleted--}, {>>a comment<<}) where the default view="accepted" reads the document as Accept All leaves it, and view="original" as Reject All does; max_chars= cuts at a block boundary and markdown_budget(max_chars) is the twin that says whether it bit:

pkg.markdown_budget(60).to_dict()
# {'text': 'Docx sample document', 'chars': 1585, 'truncated': True}

Which to use when. Round trip is not a goal — markdown cannot hold a docx. Use the coarse pair to create a document from what a model wrote, or to read one whose formatting does not matter. Use to_markdown(addresses=True) plus in-place edits to change a document that exists: the coarse route would rewrite the whole body and throw away everything the markdown has no form for.

One text model. to_markdown and outline() read the document through docx4j_py.model.text, the port of docx4j's text model (CR-011): each text box after its anchor, notes as [^1], hidden text left out, fields' results, bound values, charts, equations as LaTeX, and the views by resolution, so a deleted paragraph mark is joined as Accept All joins it. The same reading gives plain text, Markdown byte for byte as docx4j-markdown writes it, and a block model as JSON:

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

pkg = load("in.docx")
result = extract(pkg, view="accepted")   # the block model; nothing is unmarshalled
plain_text(result)[:42]
# 'Chapter 1\nMy first document: the quick bro'
markdown(result, pkg)[:12]               # docx4j's Markdown of the same reading
# '# Chapter 1\n'
result.blocks[0].to_dict()["address"]    # REQ-706's block JSON, for a tool
# 'body/0'
[warning.to_dict() for warning in result.warnings]   # where the text is not the whole document
# []

With fields="update", a field that needs neither layout nor a data source shows what Word's F9 computes, held to Word 365's results on docx4j's probes (CR-011 section 6, CR-025): DOCPROPERTY and the core-property fields, CREATEDATE and SAVEDATE in the package's zone in Word's default format, SEQ, REF, QUOTE, INFO, SECTION, NOTEREF, and the user fields from field_user=; anything else keeps the result the file holds.

Paragraph.text, get_text() and search() keep Office JS's text, as Word's own Office JS gives it (CR-011 Q4), and the python-docx facade keeps python-docx's.

Serving many documents

Import costs about 0.7 s and builds no class metadata; the first parse of each class does. In a server, import once and warm the context before the first request; parse and serialise each part with its own ParserConfig (the engine does), and share the rest across threads:

from docx4j_py.wml import warm_up
warm_up()            # 44 ms: parses an embedded document and styles part, so the first request does not

scripts/threads.py is the check: 8 threads over whole packages with a shared XmlContext, output identical to the sequential run.

A server then holds packages open across tool calls, so that "open, edit, edit, save" is four cheap calls and not four loads. DocumentSession is that registry, in the library because the thread rule and the idle-close logic are the library's knowledge:

from docx4j_py import DocumentSession

session = DocumentSession(idle_timeout=900, max_open=32)

handle = session.open("report.docx")          # a short opaque string, not a path
with session.use(handle) as pkg:              # the handle's lock is held: one call at a time
    pkg.body.paragraph_at(contains="Chapter 1").insert_paragraph("New", location="After")
    report = pkg.last_change
session.save(handle, "edited.docx")           # or save(handle) for the bytes, overwrite=True for the source
session.sweep()                               # closes what has been idle; no background thread
session.close(handle)

One lock per handle, so two tool calls on one document serialise and two on different documents do not. There is no background thread: sweep() is the server's to call.

Running it

pip install docx4j is the released package (RELEASING.md is how it gets there). In a checkout, the bindings import docx4j_xsdata, the forked runtime --- published as docx4j-xsdata --- which .venv-fork has installed editable from ~/git/docx4j-xsdata (branch docx4j; docs/fork/CHANGES.md there lists every difference from upstream xsdata).

Every ```python fence in this file and in docs/pypi-readme.md is executed by tests/test_readme.py, in order, in one namespace per file, from a temporary directory holding samples/ and an in.docx. A fence that is a fragment --- it uses a name nothing defines, or it shows an error --- is marked with <!-- fragment --> on the line before it, which the test skips; the PyPI readme may carry no such marker.

.venv-fork/bin/python -m pytest                       # the suite
.venv-fork/bin/python -m pytest -m "not slow"         # without the corpus round trip and the timings
.venv-fork/bin/python -m pytest tests/openpackaging   # the engine
.venv-fork/bin/python -m pytest tests/agent           # the agent surface: outline, find, addresses

codegen/generate.sh                                   # regenerate docx4j_py/ from schemas/
codegen/generate.sh --check                           # regenerate twice and prove it is reproducible

.venv-fork/bin/python scripts/roundtrip.py --models-module docx4j_py.wml --runtime docx4j_xsdata
.venv-fork/bin/python scripts/threads.py              # the thread-safety check
.venv-fork/bin/python scripts/acceptance.py           # the ten documents for the Word checklist

codegen/README.md explains how the bindings are generated, the docx4j name tables in codegen/names/ and the el tables in codegen/el_tables/. schemas/PATCHES.md lists every change to docx4j's schema copy and the docx4j commit it is taken from (c363a969f, 2026-09-20: the bindings carry Word's w16du:dateUtc, w16se:symEx, w16cid:durableId, w14:noSpellErr and the other extension attributes docx4j's CR-023 admitted, and mc:AlternateContent is typed in w:p, w:numPicBullet, charts and spreadsheet drawings).

Layout

docx4j_py/            one package per XML namespace, generated; codegen/generate.sh owns it
  wml/__init__.py       the classes: P, R, Text, PPr, Tbl, Document, Styles, ...
  wml/el.py             the object factory: el.p, el.r, el.t, el.sdt_run, ...
  wml/builders.py       hand written: p, r, t, tbl, tr, tc, br, tab, the run options, rpr_to_elements
  wml/pictures.py       hand written: inline_picture, image_size, emu_for (CR-003 Phase A)
  wml/sdt.py            hand written: sdt, sdt_pr, sdt_property, sdt_kind_of, next_sdt_id
  dml/ math/ mce/ w14/ w15/ w16cid/ w15symex/ ...   the namespaces WordprocessingML embeds, the same shape
  relationships/ docprops/        the .rels classes and the three properties parts
  child.py              hand written: Child, ChildList, link_parents, iter_children, deep_copy(_as)
  namespaces.py         hand written: docx4j's prefix table; UNDERSTOOD is generated
  runtime.py            hand written: the shared XmlContext, warm_up()
  fragments.py          hand written: wml(...) and to_xml(...)
  traversal.py          hand written: walk, walk_all, iter_nodes, find, text_of, run_items_of, misplaced
  placement.py          hand written: what each typed list may hold, and the refusal's messages (CR-020)
  validator.py          hand written: the findings misplaced() reports, and save(check=True)'s check
  openpackaging/        hand written, all of it: the engine (CR-002)
    part_name.py content_types.py stores.py load.py save.py mce.py resources.py api.py
    parts/              Part, BinaryPart, XmlPart, RelationshipsPart, the registry, the typed parts
    packages/           OpcPackage, WordprocessingMLPackage
  model/content/        hand written, all of it: the content API (CR-003 Phases B and D)
    body.py paragraph.py range.py font.py   the views, in Office JS's vocabulary
    text_model.py       the paragraph's text as segments, and grapheme-safe splitting
    styles.py enums.py errors.py            BUILT_IN_STYLES and ensure_style, the Literals and
                                            StrEnums, ContentError
    addresses.py        the three address forms, and the paraId generator's users
    reports.py          Outline, SearchHit, ChangeReport, TextExcerpt, and the recorder
    describe.py trial.py                    describe() (lxml, unmarshals nothing) and dry_run()
  model/sessions.py     hand written: DocumentSession, the registry a server keeps documents in
  docx/                 hand written, all of it: the python-docx facade (CR-003 Phase J)
    document.py text.py table.py section.py styles.py shape.py comments.py coreprops.py
    settings.py shared.py enums.py _base.py   python-docx's names, over the content API
  resources/            the parts warm_up parses; docx4j's default styles, numbering, fontTable
                        and KnownStyles.xml
codegen/              the generator, the name tables and the el tables
schemas/              docx4j's xsd tree with marked patches (schemas/PATCHES.md)
scripts/              roundtrip.py, canon.py, checks.py, parents.py, bench.py, threads.py,
                      acceptance.py, office_js_subset.py, python_docx_subset.py
samples/              16 documents from docx4j (Apache-2.0): 13 .docx, a .dotm, a .pptx, an .xlsx
out/acceptance/       the twelve documents for the manual Word checklist
docs/change-requests/ the design: CR-001 the object model, CR-002 the engine,
                      CR-003 the content API (every phase implemented, 2026-09-16 to 2026-09-18)

Licence

Apache-2.0, as docx4j is (see LICENSE). NOTICE names what the wheel carries from docx4j --- KnownStyles.xml, the default styles, numbering and font table, the three Office theme parts and the font substitution tables under docx4j_py/resources/, all Apache-2.0 --- and ships in the wheel beside the licence. The forked generator and runtime are MIT, as xsdata is. The schemas under schemas/ are derived from ECMA-376 and keep the terms stated in their own headers.

About

Create and manipulate Word .docx files in Python through a complete, schema-generated OOXML object model, in the style of docx4j.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages