# Python Word DOCX libraries

Python DOCX libraries create, read, and convert Microsoft Word documents from Python code. A DOCX file is a zip archive of XML parts that a library can edit without opening Word. These libraries let apps and AI agents generate reports, contracts, and letters as Word files.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [python-docx](#python-docx) | 139.9M | 5.8K | Jun 2025 | MIT |
| [Mammoth](#mammoth) | 18.2M | 1.1K | Sep 2026 | BSD-2-Clause |
| [docx2txt](#docxtwotxt) | 5.0M | 584 | Mar 2025 | MIT |
| [docxtpl](#docxtpl) | 4.7M | 2.7K | Nov 2025 | LGPL-2.1-only |
| [docxcompose](#docxcompose) | 2.0M | 139 | Jun 2026 | MIT |
| [docx2pdf](#docxtwopdf) | 581.5K | 600 | Dec 2021 | MIT |
| [docx2python](#docxtwopython) | 514.0K | 213 | Oct 2026 | MIT |
| [aspose-words](#aspose-words) | 465.1K | 135 | Nov 2026 | Commercial |

Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[python-docx](#python-docx) has the most monthly downloads in this comparison, at 139.9M.

## Capabilities

| Library | DOCX authoring | PDF rendering |
| --- | --- | --- |
| [python-docx](#python-docx) | Yes | No |
| [Mammoth](#mammoth) | No | No |
| [docx2txt](#docxtwotxt) | No | No |
| [docxtpl](#docxtpl) | Yes | No |
| [docxcompose](#docxcompose) | Yes | No |
| [docx2pdf](#docxtwopdf) | No | Yes |
| [docx2python](#docxtwopython) | No | No |
| [aspose-words](#aspose-words) | Yes | Yes |

## Libraries

### python-docx

[GitHub](https://github.com/python-openxml/python-docx) · [PyPI](https://pypi.org/project/python-docx) · [Docs](https://python-docx.readthedocs.org/en/latest/)

Creates and updates Microsoft Word DOCX files.

- Downloads / mo: 139.9M
- Stars: 5.8K
- Last release: 1.2.0
- License: MIT
- Capabilities: [From the python-docx docs](https://python-docx.readthedocs.org/en/latest/)

**Strengths**

- **Creates Word documents programmatically.** Add bold or italic text runs to a paragraph.
- **Opens existing DOCX files.** Read and change supported elements in an existing Word document.

**Watch out for**

- **Legacy DOC files need conversion.** Convert older binary Word documents to DOCX before opening them.
- **Paragraph lists skip tracked changes.** Inspect revision XML separately when inserted or deleted paragraphs must be included.

```sh
pip install python-docx
```

**agno-agi/agno** (43.2K stars)

[agno-agi/agno](https://github.com/agno-agi/agno) 

```python
def generate_docx_file(
    self, content: str, filename: Optional[str] = None, title: Optional[str] = None
) -> ToolResult:
    """Generate a DOCX file from the provided content.

    Args:
        content: The text content to write to the DOCX file.
        filename: Optional filename for the generated file. If not provided, a UUID will be used.
        title: Optional title for the DOCX document.

    Returns:
        ToolResult: Result containing the generated DOCX file as a FileArtifact.
    """
    if not DOCX_AVAILABLE:
        return ToolResult(
            content="DOCX generation is not available. Please install python-docx: pip install python-docx"
        )

    try:
        log_debug(f"Generating DOCX file with content length: {len(content)}")

        document = Document()

        if title:
            document.add_paragraph(title)

        paragraphs = content.split("\n\n")
        for para in paragraphs:
            if para.strip():
                document.add_paragraph(para.strip())

        buffer = io.BytesIO()
        document.save(buffer)
        docx_content = buffer.getvalue()
        buffer.close()

        return self._create_file_artifact(
            docx_content,
            filename,
            file_type="docx",
            mime_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
            display_name="DOCX",
        )

    except Exception as e:
        logger.exception("Failed to generate DOCX file")
        return ToolResult(content=f"Error generating DOCX file: {e}")
```

[libs/agno/agno/tools/file/generation.py](https://github.com/agno-agi/agno/blob/821be55d1ec3bb472abe8bd94c3b2a0d6c78392f/libs/agno/agno/tools/file/generation.py#L437-L483) · [More projects using python-docx →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20python-docx%20to%20preserve%20Word%20relationships%2C%20render%20document%20templates%20and%20handle%20embedded%20DOCX%20images&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from docx import Document
document = Document()
document.add_paragraph('Hello, world.')
document.save('output.docx')

```

From [index.rst](https://python-docx.readthedocs.io/en/latest/user/quickstart.html)

### Mammoth

[GitHub](https://github.com/mwilliamson/python-mammoth) · [PyPI](https://pypi.org/project/mammoth) · [Docs](https://pypi.org/project/mammoth/)

Converts DOCX documents into semantic HTML.

- Downloads / mo: 18.2M
- Stars: 1.1K
- Last release: 1.13.0
- License: BSD-2-Clause
- Capabilities: [From the Mammoth docs](https://pypi.org/project/mammoth/)

**Strengths**

- **Keeps Word heading structure.** Convert heading styles into semantic HTML headings.
- **Accepts custom style maps.** Map named Word styles to the HTML elements the application expects.

**Watch out for**

- **Generated HTML needs sanitizing.** Sanitize converted HTML before inserting it into an application page.
- **External file access stays disabled.** Enable external_file_access only when trusted external document references must be read.

```sh
pip install mammoth
```

**microsoft/markitdown** (195.6K stars)

[microsoft/markitdown](https://github.com/microsoft/markitdown) 

```python
def convert_image(self, image: Any) -> list[Any]:
    stream_info = StreamInfo(
        mimetype=image.content_type,
        extension=(
            mimetypes.guess_extension(image.content_type)
            if image.content_type
            else None
        ),
    )
    with image.open() as image_stream:
        try:
            fragment = self._render(image_stream, stream_info, **self._options)
        except InvalidFileReferenceError as exc:
            # Mammoth swallows this exception for missing document images,
            # but an error raised by the override must reach the dispatcher.
            raise RuntimeError("_image_to_html failed") from exc
    soup = _parse_image_html(fragment)
    if soup is None:
        return images.data_uri(image)

    key = str(len(self._fragments))
    self._fragments[key] = soup
    return [html.element("img", {self._attribute: key})]
```

[packages/markitdown/src/markitdown/converter_utils/docx/_images.py](https://github.com/microsoft/markitdown/blob/ed178952a6672abdfd35b5f9e76a80b6cefc086e/packages/markitdown/src/markitdown/converter_utils/docx/_images.py#L60-L82) · [More projects using Mammoth →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20mammoth%20to%20preserve%20Word%20relationships%2C%20render%20document%20templates%20and%20handle%20embedded%20DOCX%20images&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import mammoth
with open('input.docx', 'rb') as source:
    result = mammoth.convert_to_html(source)
html = result.value

```

From [README.md](https://github.com/mwilliamson/python-mammoth)

### docx2txt

[GitHub](https://github.com/ankushshah89/python-docx2txt) · [PyPI](https://pypi.org/project/docx2txt) · [Docs](https://pypi.org/project/docx2txt/)

Extracts text and images from DOCX files in pure Python.

- Downloads / mo: 5.0M
- Stars: 584
- Last release: 0.9
- License: MIT
- Capabilities: [From the docx2txt docs](https://pypi.org/project/docx2txt/)

```sh
pip install docx2txt
```

**langchain-ai/langchain-community** (285 stars)

[langchain-ai/langchain-community](https://github.com/langchain-ai/langchain-community) 

```python
def load(self) -> List[Document]:
    """Load given path as single page."""
    import docx2txt

    return [
        Document(
            page_content=docx2txt.process(self.file_path),
            metadata={"source": self.original_file_path},
        )
    ]
```

[libs/community/langchain_community/document_loaders/word_document.py](https://github.com/langchain-ai/langchain-community/blob/f425a3ed1933173fb3694b81359d1519c4f82d36/libs/community/langchain_community/document_loaders/word_document.py#L55-L64) · [More projects using docx2txt →](https://dashboard.exa.ai/playground/search?q=docx2txt%20GitHub%20projects)

**Quickstart**

```python
import docx2txt
text = docx2txt.process('input.docx')

```

From [README.md](https://github.com/ankushshah89/python-docx2txt)

### docxtpl

[GitHub](https://github.com/elapouya/python-docx-template) · [PyPI](https://pypi.org/project/docxtpl) · [Docs](https://pypi.org/project/docxtpl/)

Fills Word document templates using Jinja-style tags and Python context values.

- Downloads / mo: 4.7M
- Stars: 2.7K
- Last release: 0.20.2
- License: LGPL-2.1-only
- Runs on: Jinja2
- Capabilities: [From the docxtpl docs](https://pypi.org/project/docxtpl/)

**Strengths**

- **Keeps templates editable in Word.** Design the document in Word, then fill its template tags from Python.
- **Accepts custom Jinja filters.** Pass a Jinja environment containing the template filters the application needs.

**Watch out for**

- **Template tags must stay together.** Keep each tag inside one Word run, a single formatted text segment.
- **Context escaping starts disabled.** Enable autoescape for values containing angle brackets or ampersands.

```sh
pip install docxtpl
```

**OCA/reporting-engine** (447 stars)

[OCA/reporting-engine](https://github.com/OCA/reporting-engine) 

```python
def _render_docx(self, report_ref, res_ids, data=None):
    report = self._get_report(report_ref)
    if report.docx_multi_mode == "zip" and len(res_ids) > 1:
        zip_buffer = io.BytesIO()
        with ZipFile(zip_buffer, "a") as zip_file:
            for res_id in res_ids:
                docx, ext = self._render_docx(report_ref, [res_id], data=data)
                zip_file.writestr(
                    self._render_docx_filename(report, [res_id], data, ext),
                    docx,
                )
        return zip_buffer.getvalue(), "zip"
    template = DocxTemplate(io.BytesIO(b64decode(report.docx_template)))
    template.render(self._render_docx_eval_context(report, res_ids, data))
    result = io.BytesIO()
    template.save(result)
    return result.getvalue(), "docx"
```

[report_docx/models/ir_actions_report.py](https://github.com/OCA/reporting-engine/blob/eebd72b4e2b6b60c35972e6a3ee5d7de310bec8e/report_docx/models/ir_actions_report.py#L112-L128) · [More projects using docxtpl →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20docxtpl%20to%20preserve%20Word%20relationships%2C%20render%20document%20templates%20and%20handle%20embedded%20DOCX%20images&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from docxtpl import DocxTemplate
template = DocxTemplate('template.docx')
template.render({'name': 'Ada'}, autoescape=True)
template.save('output.docx')

```

From [latest.md](https://docxtpl.readthedocs.io/en/latest/)

### docxcompose

[GitHub](https://github.com/4teamwork/docxcompose) · [PyPI](https://pypi.org/project/docxcompose) · [Docs](https://pypi.org/project/docxcompose/)

Composes .docx documents.

- Downloads / mo: 2.0M
- Stars: 139
- Last release: 2.2.0
- License: MIT
- Capabilities: [From the docxcompose docs](https://pypi.org/project/docxcompose/)

```sh
pip install docxcompose
```

**153lsr/thesis-typeset** (166 stars)

[153lsr/thesis-typeset](https://github.com/153lsr/thesis-typeset) 

```python
def insert_custom_cover_via_compose(target_doc_path, cover_path, output_path):
    """
    使用 docxcompose 合并文档，保留更多格式信息。

    需要安装: pip install docxcompose

    Args:
        target_doc_path: 目标文档路径
        cover_path: 封面文档路径
        output_path: 输出文档路径

    Returns:
        bool: 成功返回 True，失败返回 False
    """
    try:
        from docxcompose.composer import Composer

        target = Document(target_doc_path)
        cover = Document(cover_path)

        composer = Composer(target)
        composer.append(cover)

        composer.save(output_path)
        return True
    except ImportError:
        print("警告: 未安装 docxcompose，可使用 'pip install docxcompose' 安装")
        return False
    except Exception as e:
        print(f"docxcompose 合并失败: {e}")
        return False
```

[thesis_formatter/cover.py](https://github.com/153lsr/thesis-typeset/blob/84b01d7555673374c777c7785954ec086d78bb49/thesis_formatter/cover.py#L67-L97) · [More projects using docxcompose →](https://dashboard.exa.ai/playground/search?q=docxcompose%20GitHub%20projects)

**Quickstart**

```python
from docx import Document
from docxcompose.composer import Composer
composer = Composer(Document('master.docx'))
composer.append(Document('append.docx'))
composer.save('combined.docx')

```

From [README.md](https://github.com/4teamwork/docxcompose)

### docx2pdf

[GitHub](https://github.com/AlJohri/docx2pdf) · [PyPI](https://pypi.org/project/docx2pdf) · [Docs](https://pypi.org/project/docx2pdf/)

Converts DOCX to PDF on Windows or macOS through an installed copy of Microsoft Word.

- Downloads / mo: 581.5K
- Stars: 600
- Last release: 0.1.8
- License: MIT
- Capabilities: [From the docx2pdf docs](https://pypi.org/project/docx2pdf/)

```sh
pip install docx2pdf
```

**rtcatc/Packer-Fuzzer** (3.2K stars)

[rtcatc/Packer-Fuzzer](https://github.com/rtcatc/Packer-Fuzzer) 

```python
def CreatMe(self):
    try:
        convert(self.new_filepath,self.pdf_filepath)
        self.log.debug("正确获取到pdf转化模块")
    except Exception as e:
        self.log.error("[Err] %s" % e)
```

[lib/reports/CreatPdf.py](https://github.com/rtcatc/Packer-Fuzzer/blob/bd7c98009e7df6aaa32daa86676ad6887388929c/lib/reports/CreatPdf.py#L16-L21) · [More projects using docx2pdf →](https://dashboard.exa.ai/playground/search?q=docx2pdf%20GitHub%20projects)

**Quickstart**

```python
from docx2pdf import convert
convert('input.docx', 'output.pdf')

```

From [README.md](https://github.com/AlJohri/docx2pdf)

### docx2python

[GitHub](https://github.com/ShayHill/docx2python) · [PyPI](https://pypi.org/project/docx2python) · [Docs](https://pypi.org/project/docx2python/)

Extracts content from DOCX files.

- Downloads / mo: 514.0K
- Stars: 213
- Last release: 3.7.2
- License: MIT
- Capabilities: [From the docx2python docs](https://pypi.org/project/docx2python/)

```sh
pip install docx2python
```

**AccentuSoft/LinkScope_Client** (500 stars)

[AccentuSoft/LinkScope_Client](https://github.com/AccentuSoft/LinkScope_Client) 

```python
def resolution(self, entityJsonList, parameters):
    from docx2python import docx2python
    import magic
    from pathlib import Path

    returnResults = []

    for entity in entityJsonList:
        uid = entity['uid']
        filePath = Path(parameters['Project Files Directory']) / entity['File Path']

        if not filePath.exists() or not filePath.is_file():
            continue

        if magic.from_file(str(filePath), mime=True) != \
                'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
            continue  # We only care about docx files

        metadata = docx2python(filePath)

        data = metadata.properties
        defaultDateProperties = ['created', 'modified']

        modifiedDate = str(data.get('modified'))
        modifiedDate = modifiedDate.replace('Z', '')
        returnResults.append([{'Date': modifiedDate,
                               'Entity Type': 'Date'},
                              {uid: {'Resolution': 'modified', 'Notes': ''}}])
        createdDate = str(data.get('created'))
        createdDate = createdDate.replace('Z', '')
        returnResults.append([{'Date': createdDate,
                               'Entity Type': 'Date'},
                              {uid: {'Resolution': 'created', 'Notes': ''}}])

        returnResults.extend([{'Phrase': f'{metadataKey}: {str(data.get(metadataKey))}', 'Entity Type': 'Phrase'},
                              {uid: {'Resolution': metadataKey, 'Notes': ''}}] for metadataKey in
                             [dataKey for dataKey in data if dataKey not in defaultDateProperties])

    return returnResults
```

[Core/Resolutions/Core/ExtractDOCXMeta.py](https://github.com/AccentuSoft/LinkScope_Client/blob/16be1c5ee4e5aecc5d0b07a61841046341fe70ec/Core/Resolutions/Core/ExtractDOCXMeta.py#L18-L56) · [More projects using docx2python →](https://dashboard.exa.ai/playground/search?q=docx2python%20GitHub%20projects)

**Quickstart**

```python
from docx2python import docx2python
with docx2python('input.docx') as document:
    text = document.text

```

From [README.md](https://github.com/ShayHill/docx2python)

### aspose-words

[GitHub](https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET) · [PyPI](https://pypi.org/project/aspose-words) · [Docs](https://pypi.org/project/aspose-words/)

Creates, edits, converts, and renders Word documents locally.

- Downloads / mo: 465.1K
- Stars: 135
- Last release: 26.11.0
- License: Commercial
- Capabilities: [From the aspose-words docs](https://pypi.org/project/aspose-words/)

**Strengths**

- **Converts Word documents to PDF.** Save Word documents as PDF, HTML, or supported image formats.
- **Fills Word mail-merge templates.** Generate documents by filling merge templates with application data.

**Watch out for**

- **Evaluation mode adds watermarks.** Apply a license for documents without evaluation watermarks.

```sh
pip install aspose-words
```

**Quickstart**

```python
import aspose.words as aw
document = aw.Document('input.docx')
document.save('output.pdf')

```

From [README.md](https://reference.aspose.com/words/python-net/aspose.words/document/save/) · [Find projects using aspose-words →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20aspose-words%20to%20preserve%20Word%20relationships%2C%20render%20document%20templates%20and%20handle%20embedded%20DOCX%20images&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

## FAQ

### Which Python DOCX library should I use?

[python-docx](#python-docx) suits creating and editing Word files paragraph by paragraph. [docxtpl](#docxtpl) suits filling a Word template with Jinja-style tags. [Mammoth](#mammoth) suits converting DOCX into clean HTML.

### What is python-docx?

[python-docx](#python-docx) creates, reads, and updates Microsoft Word .docx files. Its document API covers paragraphs, tables, sections, and inline shapes.

### What is docxtpl?

[docxtpl](#docxtpl) fills a template authored in Word with Jinja tags and values from a Python context. It also supports rich text and subdocuments.

### How do I convert DOCX to PDF in Python?

[docx2pdf](#docxtwopdf) converts DOCX to PDF on Windows or macOS through an installed copy of Microsoft Word. [aspose-words](#aspose-words) renders Word documents to other formats without Office.

### How do I extract text from a DOCX file in Python?

[docx2txt](#docxtwotxt) extracts plain text, including headers, footers, and hyperlinks, and can save embedded images. [docx2python](#docxtwopython) returns nested body, header, and footer content with images.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best Python DOCX Word libraries python-docx docxtpl Mammoth Aspose Words templates HTML PDF code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
