Skip to main content

betteroffice-docx

Read, edit, lay out, and rasterize DOCX documents from Python. python-docx reads a document and writes one back; this also paginates it (page boxes, a display list, PNG pages) because the Rust BetterOffice DOCX core is compiled into the wheel: no Word, no LibreOffice subprocess, no COM.

pip install betteroffice-docx

The distribution is hyphenated, the module is not: import betteroffice_docx.

Read a document

from betteroffice_docx import Document

document = Document.open_path("report.docx")

print(document.structure())          # Structure(body_paragraphs=42, body_tables=3, sections=2)
for paragraph in document:
    print(paragraph.id, paragraph.style, repr(paragraph.text))

for table in document.tables():
    for row in table.rows:
        print([cell.text for cell in row.cells])

paragraphs() walks the body in document order and descends into table cells and content controls, so a cell paragraph is reachable both ways. document[key] and document.paragraph(key) take either a w14:paraId or a body index. Everything a read returns is a value, not a live view. Read again after an edit.

Page geometry is in twips (1440 to the inch). The module exports TWIPS_PER_INCH and TWIPS_PER_POINT.

section = document.sections()[0]
print(section.page_width, section.page_height, section.margin_left)
print(document.headers()[0].text)

Edit text

edit = document.replace_text("11111111", "Edited from Python")
print(edit.para_id, edit.start, edit.end)

document.save_path("report-edited.docx")

replace_text rewrites one paragraph and keeps its style, alignment, and the run formatting it already had. The engine rebuilds the paragraph from a single run, so a paragraph that mixes runs (half bold, a hyperlink, a field) raises UnsupportedEditError rather than flattening the formatting you did not ask it to touch. An unknown w14:paraId raises KeyError.

replace_text uses non-None entries from paragraph_ids. Repeated IDs receive fresh identities that are saved after editing.

Write

save() serializes the edited model; reopening it returns the edited text.

document = Document.open_path("report.docx")
document.replace_text(document.paragraph_ids[0], "New first line")
print(Document.open(document.save()).paragraph(0).text)

Saving is deterministic. The engine has no clock, so timestamps come from document.timestamp (the epoch until you set one), and the same input plus the same edits produce the same bytes. save(now=..., update_modified_date=True, modified_by=...) overrides that for one call.

Saving rebuilds the ZIP container and preserves untouched retained parts.

Export structured content

content = document.export_structured(revision_view="accepted", stories=["body", "comments"])
for block in content["stories"][0]["blocks"]:
    print(block["kind"], block["anchor"])

markdown = document.export_markdown(revision_view="markup")
print(markdown["markdown"])

export_structured returns plain dicts in the same camelCase schema the JavaScript and Rust APIs produce: ordered stories of paragraphs, headings, list items, tables and content controls, each with the location it was read from, and diagnostics for everything omitted or not represented. revision_view is required (accepted, original, or markup); only the body is exported unless stories selects headers, footers, footnotes, endnotes or comments. Fields export cached results; images export alt text and relationship metadata. max_blocks and max_bytes stop the export at a whole block and set truncated. export_markdown and render_docx_markdown(content) add a <!-- docx-export:N --> marker per block, mapped to its anchor in anchors. Content with no location of its own is anchored {"kind": "unlocated", "story": ..., "reason": ...}, never as a paragraph.

List content controls

for control in document.list_content_controls()["controls"]:
    print(control["tag"], control["controlType"], control["value"])

matches = document.find_content_controls({"kind": "tag", "tag": "customer.name"})

Controls come in document order with the same camelCase fields the JavaScript and Rust APIs produce: the control's id, w:id, type, tag, alias, lock and placeholder state, whether it is data-bound, its placement, anchor, parent, current value and effective lock. stories defaults to every category, and max_controls or max_bytes refuse with ExportError rather than returning a partial list. Tags, aliases and ooxmlIds match exactly.

Lay a document out

Layout is a two-stage contract. Something else measures text (the browser, or ooxml-text), and the engine paginates the measured blocks and compiles them into a display list:

layout = document.layout(open("layout-input.json").read())
print(len(layout), layout.pages)
layout.write("layout.json")

pages = layout.display_list
print(len(pages), pages.primitives)

layout() takes the envelope as a dict or as a JSON string, and returns the page boxes (layout.json, layout.to_dict()) beside the display list that paints them.

Rasterize

Register a face under each family the text names before rasterizing; here Carlito stands in for Calibri:

from pathlib import Path

document.register_font("Calibri", Path("Carlito-Regular.ttf").read_bytes())
document.register_font("Calibri", Path("Carlito-Bold.ttf").read_bytes(), bold=True)

png = document.render_png(layout.display_list, 0)
png.write("page-0.png")
print(len(png), png.skipped_images)

Text whose family has no chain raises RenderError naming the chain it wanted (missing font chain for `calibri|0|0` ), so a missing face is loud rather than silently blank.

png.skipped_images counts unresolved references. Register image bytes under the relationship ID and owning part:

document.register_image(
    "rId9", Path("header.png").read_bytes(), scope="header_footer", part="rId7"
)

Images the display list already carries as data: URLs need no registration. A page past MAX_PIXMAP_DIM per side or MAX_PIXMAP_PIXELS in area is refused before any surface is allocated.

Compared with python-docx

python-docx betteroffice-docx
Read paragraphs, tables, sections yes yes
Write text back to a file yes yes, single-run paragraphs
Paginate (page boxes, display list) no yes
Rasterize pages to PNG no yes
Engine pure Python Rust, compiled

python-docx is a far broader authoring library. If what you need is pagination, page images, or an engine that reads what Word actually wrote, that is the gap this fills.

API

Document.open(data) / open_path(path) open from bytes or a path
document.structure() paragraph, table, section, and note counts
document.paragraphs() / tables() / sections() body content
document.headers() / footers() header and footer stories
document[key] / document.paragraph(key) one paragraph by ID or index
document.paragraph_ids / text body IDs, and the whole text
document.warnings / template_variables what the parser found
document.replace_text(para_id, text) rewrite one paragraph
document.export_structured(...) / export_markdown(...) read-only structured content or Markdown
document.list_content_controls(...) / find_content_controls(query) the document's content controls
render_docx_markdown(content) render exported content as Markdown
document.author / origin / timestamp how an edit is attributed and stamped
document.layout(input) paginate a measured envelope
document.register_font / register_image raster resources
document.render_png(display_list, page) rasterize one page
document.save() / save_path(path) serialize to DOCX

Errors raise DocxError or a more specific subclass: ParseError, EditError, UnsupportedEditError, LayoutError, RenderError, ExportError (export or content-control read options the engine refuses; its failure is the refusal as a dict). An unknown paragraph ID raises KeyError, an out-of-range index IndexError, and a bad argument (an unknown parse limit, an unknown image scope, malformed font bytes) raises ValueError.

Parser bounds can be tightened for untrusted input:

Document.open_path("untrusted.docx", limits={"max_paragraphs": 5_000, "max_tables": 500})

An unknown limit name raises ValueError rather than being ignored.

Threads

A Document is not pinned to a thread: the engine's document type is Send and Sync, so opening on one thread and dropping on another is fine. Parsing, layout, rasterization, and saving release the GIL for their duration, so several documents genuinely proceed in parallel.

Status

Pre-1.0: the API may change between minor versions. Text replacement preserves paragraph and run formatting.

Wheels are built for Linux (x86_64, aarch64), macOS (arm64, x86_64), and Windows (x86_64) against the stable ABI for CPython 3.9 and up.

Apache-2.0.

Metadata

Release files for betteroffice-docx 0.2.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for betteroffice-docx 0.2.2
File Size Uploaded Provenance Actions
betteroffice_docx-0.2.2.tar.gz 3.7 MB With provenance Details for betteroffice_docx-0.2.2.tar.gz

Built distributions (wheels)

Table of built distributions (wheels) for betteroffice-docx 0.2.2
File Actions
betteroffice_docx-0.2.2-cp39-abi3-win_amd64.whl CPython 3.9 abi3 Windows x86-64 Details for betteroffice_docx-0.2.2-cp39-abi3-win_amd64.whl
betteroffice_docx-0.2.2-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl CPython 3.9 abi3 Linux glibc 2.17+ x86-64 Details for betteroffice_docx-0.2.2-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
betteroffice_docx-0.2.2-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl CPython 3.9 abi3 Linux glibc 2.17+ ARM64 Details for betteroffice_docx-0.2.2-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
betteroffice_docx-0.2.2-cp39-abi3-macosx_11_0_arm64.whl CPython 3.9 abi3 macOS 11.0+ ARM64 Details for betteroffice_docx-0.2.2-cp39-abi3-macosx_11_0_arm64.whl
betteroffice_docx-0.2.2-cp39-abi3-macosx_10_12_x86_64.whl CPython 3.9 abi3 macOS 10.12+ x86-64 Details for betteroffice_docx-0.2.2-cp39-abi3-macosx_10_12_x86_64.whl

Total release size: 46.7 MB

Release files / betteroffice_docx-0.2.2.tar.gz

Download URL betteroffice_docx-0.2.2.tar.gz
Size 3.7 MB
Tags Source
SHA-256 checksum
How to use checksums
88148e6cb28844d5df8ce7ffb67e5028e505c61e9597c87b60981d1c77431f3e
BLAKE2b-256 checksum
How to use checksums
7f73a5f1dd6b9bfa3ea0b6c725c22a56ddcda4f75a75c2e9d2b02c1bf6285ebf
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 27, 2026.

Transparency log

Release files / betteroffice_docx-0.2.2-cp39-abi3-win_amd64.whl

Download URL betteroffice_docx-0.2.2-cp39-abi3-win_amd64.whl
Size 9.2 MB
Tags CPython 3.9 Windows x86-64 abi3
SHA-256 checksum
How to use checksums
c1296b64646ae0515f66e815d57e801df1757ef16cc4cb4e4f7b18b8e9aa73c7
BLAKE2b-256 checksum
How to use checksums
b97493f162d6b4f2db6a66c40c6c719129ade9e59aa716b07ea4951ede77ac96
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 27, 2026.

Transparency log

Release files / betteroffice_docx-0.2.2-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl

Download URL betteroffice_docx-0.2.2-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Size 8.8 MB
Tags CPython 3.9 Linux glibc 2.17+ x86-64 abi3
SHA-256 checksum
How to use checksums
27822af030dff4bd8604367ea6655cbf131f0634f63e2e25fbcd5b53d87a4d7d
BLAKE2b-256 checksum
How to use checksums
62417abd8aa39bec4ac98cabc2c3041dd5b7665c694c5f6ff0de56207476d9ce
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 27, 2026.

Transparency log

Release files / betteroffice_docx-0.2.2-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl

Download URL betteroffice_docx-0.2.2-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
Size 8.2 MB
Tags CPython 3.9 Linux glibc 2.17+ ARM64 abi3
SHA-256 checksum
How to use checksums
9c0e4fb242d7ca87a80b9fd74b69fb5211712199984cab2f1b7576f15158556f
BLAKE2b-256 checksum
How to use checksums
12d03acfc49a3042713d6c8a6e137dafd005cceb1214dd3e2511d8b3316a51dc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 27, 2026.

Transparency log

Release files / betteroffice_docx-0.2.2-cp39-abi3-macosx_11_0_arm64.whl

Download URL betteroffice_docx-0.2.2-cp39-abi3-macosx_11_0_arm64.whl
Size 8.1 MB
Tags CPython 3.9 abi3 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
823ec5f2a2ca1e4a7c0786fe14705d0313f3bf4ce2b003e47d14151cdae263f5
BLAKE2b-256 checksum
How to use checksums
bc531d09b944858a71e59361cf0d8e10821121dffbc5584ac3c74f98192c203f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 27, 2026.

Transparency log

Release files / betteroffice_docx-0.2.2-cp39-abi3-macosx_10_12_x86_64.whl

Download URL betteroffice_docx-0.2.2-cp39-abi3-macosx_10_12_x86_64.whl
Size 8.6 MB
Tags CPython 3.9 abi3 macOS 10.12+ x86-64
SHA-256 checksum
How to use checksums
c9f48eb97fdc6ebd2d173cb30c17041815ed443d45ec25bf41f3f6adbd60494c
BLAKE2b-256 checksum
How to use checksums
59eb6915af3c880d572bda8ce10109dc5c79e6a1ec3bfcec73bd6124e7bd7cef
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 27, 2026.

Transparency log

Security for betteroffice-docx 0.2.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

All 6 files in this release have been uploaded with provenance metadata.

Select from 6 files

Attestation for betteroffice_docx-0.2.2.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 27, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page