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_paragraph_text(para_id, text) is an alias of replace_text. 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

Text renders with the bundled fonts, which the package installs as the betteroffice-fonts-latin, -intl and -cjk wheels and reads from disk (Carlito stands in for Calibri, for example):

png = document.render_png({"page": 0}, scale=1.0)
png.write("page-0.png")
print(len(png), png.skipped_images)

render_png accepts a PngTarget dictionary. For an existing layout, use document.render_display_list_png(layout.display_list, 0).

register_font adds a family or replaces a bundled one:

from pathlib import Path

document.register_font("Brand Sans", Path("BrandSans-Regular.ttf").read_bytes())

Without the font wheels (installed with --no-deps), text whose family has no registered face raises RenderError naming the chain it wanted (missing font chain for `calibri|0|0` ).

png.skipped_images counts unresolved references, and png.skipped_effects maps each effect kind the renderer could not draw yet (for example text.textOutline) to how often it was left out. 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.replace_text_at(index, text) rewrite one paragraph by index, ID or not
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(target, *, scale=1.0) lay out and rasterize a zero-based page
document.render_display_list_png(display_list, page=0) rasterize an existing layout
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.

Compatibility

Releases are versioned with Changesets. The API can change between minor versions; every change is listed in the changelog, and deprecations are announced before removal.

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.3.0

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.3.0
File Size Uploaded Provenance Actions
betteroffice_docx-0.3.0.tar.gz 5.7 MB With provenance Details for betteroffice_docx-0.3.0.tar.gz

Built distributions (wheels)

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

Total release size: 80.4 MB

Release files / betteroffice_docx-0.3.0.tar.gz

Download URL betteroffice_docx-0.3.0.tar.gz
Size 5.7 MB
Tags Source
SHA-256 checksum
How to use checksums
1cd718b6e728a29c0cecbe29d83053376c11e6c35bb72c200b76fdb271b2a650
BLAKE2b-256 checksum
How to use checksums
e79ca6d0ea77240ffa4ff7331e58494d9027155f49c3f1cd36181506616bd305
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 Nov 25, 2026.

Transparency log

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

Download URL betteroffice_docx-0.3.0-cp39-abi3-win_amd64.whl
Size 16.2 MB
Tags CPython 3.9 Windows x86-64 abi3
SHA-256 checksum
How to use checksums
d4806cb96a34733109dd00a63e0a7335fdc843823a94f433a8d4ba6e62f3b5e2
BLAKE2b-256 checksum
How to use checksums
88d660f95a294c0cb3cfb293fca7e5bd6bdca12cc7f1bbdc396b69a7a630dc40
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 Nov 25, 2026.

Transparency log

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

Download URL betteroffice_docx-0.3.0-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
Size 15.3 MB
Tags CPython 3.9 Linux glibc 2.17+ x86-64 abi3
SHA-256 checksum
How to use checksums
20a349aa336d94bccdb5cfc83d846d4ec32b82c3d4cf0adc03e5a2c667c260ff
BLAKE2b-256 checksum
How to use checksums
de75071cd44fa8cb14c13d391842f3bde685ec2418a954d218cb8a257db5f464
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 Nov 25, 2026.

Transparency log

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

Download URL betteroffice_docx-0.3.0-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl
Size 14.2 MB
Tags CPython 3.9 Linux glibc 2.17+ ARM64 abi3
SHA-256 checksum
How to use checksums
285d3442547de63a51d17c0656c920a237aea5beb213b29a4c935874071ee0a2
BLAKE2b-256 checksum
How to use checksums
01858731d375207db6350af8d164c91af82b381736623c61708b6fe1f59d22cf
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 Nov 25, 2026.

Transparency log

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

Download URL betteroffice_docx-0.3.0-cp39-abi3-macosx_11_0_arm64.whl
Size 14.1 MB
Tags CPython 3.9 abi3 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
3c12f15e290f38c552faee74d78706d78511df0afb54c208fb3a7f736c369329
BLAKE2b-256 checksum
How to use checksums
41a75e3887428e27443f31bdf495709d8963147a54a0f6ecfdd6b14987238d05
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 Nov 25, 2026.

Transparency log

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

Download URL betteroffice_docx-0.3.0-cp39-abi3-macosx_10_12_x86_64.whl
Size 15.0 MB
Tags CPython 3.9 abi3 macOS 10.12+ x86-64
SHA-256 checksum
How to use checksums
7d21a10b09ac009e1fa16d54d65178c7b6537c0c6b7405e2c75ce387fc8a879d
BLAKE2b-256 checksum
How to use checksums
aae9691086f050f4c5dd7f33d634ef4157b66e8d29e3c618801f7bfb9d98d2b4
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 Nov 25, 2026.

Transparency log

Security for betteroffice-docx 0.3.0

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.3.0.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 Nov 25, 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