Metadata-Version: 2.4
Name: docxspec
Version: 0.3.0
Summary: Lightweight Word report generation library based on python-docx
Author-email: Poggi-Tang <2322806855@qq.com>
License-Expression: MIT
Project-URL: Homepage, https://github.com/Poggi-Tang/docxspec
Project-URL: Repository, https://github.com/Poggi-Tang/docxspec
Project-URL: Issues, https://github.com/Poggi-Tang/docxspec/issues
Project-URL: Changelog, https://github.com/Poggi-Tang/docxspec/blob/main/CHANGELOG.md
Project-URL: Documentation, https://github.com/Poggi-Tang/docxspec/blob/main/README.md
Keywords: word,docx,report,automation,python-docx
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Operating System :: OS Independent
Classifier: Topic :: Office/Business
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: python-docx>=1.1.0
Requires-Dist: Pillow>=10.0.0
Requires-Dist: docxtpl>=0.20.2
Requires-Dist: docxcompose>=1.4.1
Provides-Extra: report
Requires-Dist: pydantic<3,>=2; extra == "report"
Provides-Extra: studio
Requires-Dist: fastapi<1,>=0.115; extra == "studio"
Requires-Dist: pydantic<3,>=2; extra == "studio"
Requires-Dist: uvicorn<1,>=0.30; extra == "studio"
Requires-Dist: python-multipart>=0.0.18; extra == "studio"
Requires-Dist: pymupdf<2,>=1.26; extra == "studio"
Requires-Dist: psutil>=6; extra == "studio"
Provides-Extra: word
Requires-Dist: pywin32>=306; platform_system == "Windows" and extra == "word"
Provides-Extra: dev
Requires-Dist: build>=1.2.2; extra == "dev"
Requires-Dist: pydantic<3,>=2; extra == "dev"
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: pytest-cov>=5.0.0; extra == "dev"
Requires-Dist: ruff>=0.11.0; extra == "dev"
Requires-Dist: python-semantic-release>=9.15.0; extra == "dev"
Dynamic: license-file

# docxspec

English | [简体中文](https://github.com/Poggi-Tang/DocxSpec/blob/main/README.zh-CN.md)

[![PyPI](https://img.shields.io/pypi/v/docxspec?cacheSeconds=300)](https://pypi.org/project/docxspec/)
[![Python](https://img.shields.io/pypi/pyversions/docxspec?cacheSeconds=300)](https://pypi.org/project/docxspec/)
[![License](https://img.shields.io/github/license/Poggi-Tang/DocxSpec)](https://github.com/Poggi-Tang/DocxSpec/blob/main/LICENSE)
[![CI](https://github.com/Poggi-Tang/DocxSpec/actions/workflows/ci.yml/badge.svg)](https://github.com/Poggi-Tang/DocxSpec/actions/workflows/ci.yml)
[![Publish](https://github.com/Poggi-Tang/DocxSpec/actions/workflows/publish.yml/badge.svg)](https://github.com/Poggi-Tang/DocxSpec/actions/workflows/publish.yml)

`docxspec` is a structured Word report generation library built on top of `python-docx`.

It provides a small, template-driven API for generating `.docx` reports from user-supplied templates and containerized content blocks. It is designed for automated test reports, simulation reports, and other engineering document workflows.

## Features

* Template-based Word report generation
* Structured content container API
* Text, image, and table insertion
* Rich text style helpers
* Automatic figure and table caption numbering
* Page field helpers such as `PAGE` and `NUMPAGES`
* Word field refresh helpers for TOC, figure lists, table lists, and captions
* DS-standard document classification, validation, and standard document assembly
* PyPI-ready packaging and CI/CD workflows

## Installation

Install from PyPI:

```bash id="a01x9k"
pip install docxspec
```

Or install from source:

```bash id="frx0as"
git clone https://github.com/Poggi-Tang/DocxSpec.git
cd DocxSpec
pip install -e .
```

## Quick Start

```python id="24yi91"
from docxspec import BODY_STYLE, WordAPI, make_rich_text

api = WordAPI("your_template.docx")

text = make_rich_text(
    "This text is inserted into the template.",
    BODY_STYLE,
)

image_container = api.new_container()
image_container.add_image(
    "your_image.png",
    width_cm=8.0,
    align="center",
)

table_container = api.new_container()
table_container.add_table_by_config(
    {
        "data": [
            ["Name", "Value"],
            ["Example", "123"],
        ]
    }
)

api.render(
    {
        "text": text,
        "image": image_container.subdoc,
        "table": table_container.subdoc,
    },
    "report.docx",
)
```

When a custom chapter heading style is used, reset the figure or table sequence explicitly
on the first caption in each chapter. This avoids Word continuing the sequence from the
previous chapter even when the `STYLEREF` chapter number changes:

```python
chapter = api.new_container()
chapter.add_heading("Test records", level=1)
chapter.add_table_caption_auto("First table", reset_sequence=True)
chapter.add_table([["Name", "Value"]])
chapter.add_table_caption_auto("Second table")
chapter.add_table([["Name", "Value"]])
```

The first caption uses `SEQ 表 \r 1`; later captions continue the same sequence. The
same `reset_sequence` option is available for `add_figure_caption_auto()`.

Table cells can also contain mixed text and images. Image parts support explicit sizing:

```python
table_container.add_table(
    [
        ["Field", "Content"],
        [
            "Test method",
            [
                "1. Build test topology\n",
                {"image": "topology.png", "width_cm": 6.0},
                "\n2. Run simulation and record output",
            ],
        ],
    ]
)
```

For JSON-like configurations, use `{"type": "mixed", "parts": [...]}` and
`{"type": "image", "path": "...", "width_cm": 3.0}` when a more explicit schema is preferred.

## How It Works

`docxspec` uses two main ideas:

1. `WordAPI` loads a `.docx` template and renders the final output.
2. Containers are used to build structured sub-document blocks such as images, tables, captions, and styled paragraphs.

A typical workflow is:

1. Prepare a Word template
2. Build text or container content
3. Pass the rendered blocks into `api.render(...)`
4. Export the final report

## DocxSpec Studio

[Studio V2](studio/v2/README.md) and Python use the same report compiler. Select
**导出模板包** in Studio V2 to export the current component template and its
referenced static images. Pass your report data separately:

```bash
python -m pip install "docxspec[report]"
```

```python
import json
from pathlib import Path

from docxspec.report import render_report

data = json.loads(Path("data.json").read_text(encoding="utf-8"))
render_report("template.zip", data, "report.docx")
```

The report API uses the same content, numbering, styles, and page settings as
Studio V2. DOCX generation runs without an Office engine. Office layout, PDF
preview, and AI conversion are available from Studio with their respective
dependencies.

Run Studio V1 without Node.js:

```bash
python -m pip install -e .
python studio/server.py --data-dir .local-acceptance-data
```

Open `http://127.0.0.1:4175`. The default chapter tree comes from the built-in DS
master: cover, revision history, TOC, figure/table lists and the master's heading
hierarchy. Exports retain the master styles, numbering and section headers/footers.
Use `--port` if another application already occupies the default port.

On Windows, install `python -m pip install -e ".[word]"` and add `--refresh-fields`
to refresh field caches through local Microsoft Word before download. A refresh
failure stops export. Without this option, only the update-on-open flag is set.
See [Studio instructions](studio/README.md) and [update notes](CHANGELOG.md).
The current Word/WPS rendering and PDF behavior still require manual verification.

## Template Requirements

`docxspec` is template-driven.

When preparing your own template, make sure that:

* the template structure matches the placeholders or render targets used by your code
* the required paragraph / table styles exist in the template
* custom report styles are defined in advance if your project depends on them

`WordAPI` also embeds all 17 DS styles from the built-in master, including unused
heading levels, captions, tables, pictures, TOC and header/footer styles for later
manual editing. Missing style and numbering dependencies are copied with remapped
IDs; existing styles in a custom template are preserved. These are font references
and formatting definitions, not embedded font files.

The demo template in `Demo/template.docx` is a runnable example. The published wheel includes the DS base document and front-matter templates separately from the demo assets.

## DS Standard Documents

`docxspec` also provides DS-standard document utilities for workflows that start from an
existing body-only `.docx` file and need a standardized output document.

```python
from docxspec import build_standard_docx, check_word_standard, classify_docx_body

report = classify_docx_body("body.docx")
build_result = build_standard_docx("body.docx", "standard.docx")
check_result = check_word_standard("standard.docx")
```

`build_standard_docx()` uses the bundled `body.docx` as the source of the default DS styles.
It adds `cover.docx`, `revision.docx`, and `contents.docx` to every report. It adds `figures.docx`
and `tables.docx` only when the final body contains matching Word caption fields.

To customize the front matter, copy the `.docx` files you want to edit from `docxspec.DEFAULT_DS_SECTIONS`
into your own folder, then pass `front_matter_dir="my_layout"`. Each file has one Word section
and can span several pages. Keep the native caption-list field when editing `figures.docx` or
`tables.docx`. The remaining sections come from the package. The DS base document supplies the
definitions for same-named DS styles.

To use an existing whole-document template, pass `template_docx=`. `WordAPI.render()` also removes
empty standalone figure and table lists from existing templates. Other renderers can call
`prune_empty_caption_lists(path)` on their finished DOCX.

## Refreshing Word Fields

Standard generation, `WordAPI.render()`, and `render_report()` request field
updates when a DOCX opens by default. Set `field_engine` to `"word"`, `"wps"`, or
`"libreoffice"` to update the final DOCX and check its saved field results.

```python
from docxspec import refresh_docx_fields

result = refresh_docx_fields("report.docx", engine="word", strict=True)
print(result.status)
```

COM automation requires Windows, the desktop application, and the optional dependency:

```bash
pip install "docxspec[word]"
```

WPS must register `KWPS.Application` and start an isolated instance. LibreOffice
requires Python UNO bindings, typically provided by `python3-uno` on Linux.
`DOCXSPEC_SOFFICE` and `DOCXSPEC_UNO_PYTHON` can point to those executables.

`verify_docx_fields()` inspects saved caches in documents updated by any Office
application. It can compare against a source DOCX and check page-count fields
against the actual page count.

## Demo Directory

The repository includes a runnable demo set in `Demo/`.

Shared template:

* `Demo/template.docx`

Example scripts:

* `Demo/demo1_paragraph.py`
* `Demo/demo2_container_paragraph.py`
* `Demo/demo3_container_image_caption.py`
* `Demo/demo4_container_table_caption.py`
* `Demo/demo5_container_table_image_caption.py`
* `Demo/demo6_header_footer.py`
* `Demo/demo7_styles_in_container.py`
* `Demo/demo8_all_in_one.py`
* `Demo/demo9_block_template.py`
* `Demo/demo10_kl_standard.py`
* `Demo/demo11_table_mixed_cell.py`

Run them from the repository root, for example:

```bash id="zr2qj0"
python Demo/demo1_paragraph.py
python Demo/demo8_all_in_one.py
python Demo/demo9_block_template.py
python Demo/demo10_kl_standard.py
```

Generated files are written to `Demo/output/`.

## Reusing Word Blocks

`BlockTemplate` can extract a repeated `caption + table` block from an existing Word
template and insert cloned copies back into a document or a container. This is useful
when the template already contains field captions, merged cells, images, or carefully
prepared table styles.

Place a marker paragraph immediately before the source caption and table:

```text
{{SOURCE_TABLE_BLOCK}}
Table <SEQ field> {{TABLE_TITLE}}
<table with placeholders>
```

Then extract and reuse the block:

```python
from docxspec import WordAPI

api = WordAPI("template.docx")
block_template = api.extract_table_block("{{SOURCE_TABLE_BLOCK}}", remove_block=True)

container = api.new_container()
container.add_block(
    block_template.clone().replace_text(
        {
            "{{TABLE_TITLE}}": "Default icon display",
            "{{ITEM_ID}}": "FT_Demo_UI_001",
        }
    )
)

api.render({"result": container.subdoc}, "report.docx")
```

For documents that must preserve Word field captions as strictly as possible, prefer
`insert_block_at_marker(...)` followed by saving the document directly.

## Project Structure

```text id="8r4z09"
DocxSpec
├── .github/
│   └── workflows/
├── Demo/
├── src/
│   └── docxspec/
│       ├── __init__.py
│       ├── word_api.py
│       └── word_styles.py
├── tests/
├── CHANGELOG.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── README.zh-CN.md
└── pyproject.toml
```

## Release Automation

This repository is prepared for a professional Python package workflow:

* CI runs lint and tests on push and pull request
* Trusted Publishing publishes to PyPI from GitHub Actions
* Build artifacts include both source distribution and wheel

## Development

```bash id="jlwm2z"
pip install -e .[dev]
pytest
ruff check .
```

When developing locally, prepare your own `.docx` template files in the repository or project workspace and pass their paths explicitly to `WordAPI`.

## License

MIT License. See [LICENSE](https://github.com/Poggi-Tang/DocxSpec/blob/main/LICENSE).
