Skip to main content
Glama
docx-lab-mcp
by eljcf

docx-lab-plugin

面向结构化 .docx 实验报告的原位模板填充、WPS 兼容清洗与免 Word 高保真 PDF 导出工具

CI Python 3.10+ Platform License: MIT

简体中文 | English

解决什么问题 · 工作原理 · 快速开始 · MCP 与插件 · 实测基准

第 1 页:独立封面

第 2 页:正文与代码块

第 3 页:截图与图注

第 4 页:批阅与备注栏

第 1 页 · 独立封面

第 2 页 · 样式克隆与代码块

第 3 页 · 净宽自适应截图

第 4 页 · 批阅与备注栏

uv run --extra preview docx-lab fill \
  examples/lab_report/template.docx \
  examples/lab_report/payload.json \
  -o report_filled.docx --audit --pdf report_filled.pdf

解决什么问题

高校课程实验报告、工程测试报告与机构表单通常是未预置模板标签的原始 .docx,自动化填充时最容易遇到四类问题:

常见工程痛点

docx-lab-plugin 的解决方式

原始模板格式复杂且易被破坏含页眉页脚、首页不同、外粗内细边框、碎片化封面 Run 与同行多槽下划线(报告人:__ 学号:__ 班级:__)

原位 OOXML 微创填充:只改目标槽位节点,其余 XML 部件原样保留;自动克隆原表已有正文 <w:pPr> / <w:rPr> 样式 DNA

WPS Office 跨端排版漂移尾随空格下划线消失、列宽漂移、hRule="exact" 固定行高裁切图文、中文字体回退、重复绘图 ID 弹窗报错

7 项 WPS 兼容清洗 + 12 项自动审计:保存前自动修复已知 WPS 雷区,并通过 audit_docx() 逐项校验(支持 --strict 门禁)

无 Word / WPS 环境难以导出高保真 PDF大量 Linux / macOS / Windows 开发机与 CI 未安装桌面办公套件

内置 Rust + Skia(dxpdf)免套件出图:Windows / macOS / Linux 零配置秒级生成 PDF,可选自动回退本机 LibreOffice

AI Agent 难以直接安全操作复杂 Word 文件大模型擅长做实验、截屏和生成 JSON,不适合手写脆弱的 XML 排版代码

CLI + Python SDK + FastMCP + Antigravity 插件:提供确定性工具接口与逐页 PNG 视觉验收闭环


Related MCP server: Document Generator MCP

工作原理

  1. 模板自省(inspect_docx):自动识别封面碎片化/多槽位字段、表格红字提示区、单元格净宽与 WPS 排版隐患。

  2. 样式克隆与原位回填(fill_docx_inplace):保留封面独立下划线,清除红字提示并克隆模板正文样式写入段落、WPS 原生底纹代码块,以及按单元格净宽(tcW - leftMar - rightMar)等比缩放的内嵌 PNG/JPEG 截图与绑定图注。

  3. WPS 7 项清洗与 12 项审计(sanitize_for_wps / audit_docx):自动注入 w:ulTrailSpace、封面硬分页、按 OOXML Schema 序锁定 w:tblLayout="fixed"、放宽内容行 hRule="exact"、保护签字尾块 w:cantSplit、重排全局唯一 Drawing ID 并校验防 XXE 的 XML/媒体完整性。

  4. 免办公套件 PDF 与 PNG 预览(convert_to_pdf / render_pdf_pages):默认调用预编译 Rust + Skia dxpdf 引擎,engine="auto" 模式下支持自动探测系统 LibreOffice 回退。

#

审计项 / 清洗策略

保障内容

1

wps_ul_trail_space

注入 w:compat/w:ulTrailSpace,修复 WPS 忽略封面尾随空格下划线

2

cover_page_break

在首表前一段末尾精准插入 <w:br w:type="page"/>,杜绝表格首行倒灌封面

3

table_fixed_layout

按严格 CT_TblPr 子元素序写入 w:tblLayout="fixed",兼容 gridSpan/vMerge 同步 tblGrid/tcW

4

exact_row_height

放宽内容行与未触碰长行的 hRule="exact" 为 "atLeast";为批阅/备注尾块注入 w:cantSplit

5

inline_images_only & image_width_fit

强制 wp:inline(anchor=0),原生解析 PNG/JPEG 尺寸自适应净宽并约束竖图高度(<= 11.5 cm),keep_with_next 绑定图注

6

unique_drawing_ids

全文档递增重排 wp:docPr 与 pic:cNvPr 唯一 ID,消除 Word/WPS 打开修复告警

7

east_asia_font_coverage / no_residual_red_hints / xml_and_media_integrity / header_footer_integrity / table_borders

显式写入 w:eastAsia/w:ascii/w:hAnsi、清理红字提示、防 XXE 核验 XML 与媒体 rId、确保零幽灵页眉页脚部件


快速开始

需要 Python 3.10+ 与 uv,在 Windows / macOS / Linux 上通用,无需 Word、WPS 或 Rust 编译器。

1. 安装

git clone https://github.com/eljcf/docx-lab-plugin.git
cd docx-lab-plugin

uv sync                  # 核心 CLI、Python SDK、MCP Server 与 dxpdf 引擎
uv sync --extra preview  # 可选:附加 PyMuPDF,用于导出逐页 PNG 预览图与运行评估

2. 直接跑通内置示例(examples/lab_report/)

# ① 扫描模板槽位与 WPS 风险
uv run docx-lab inspect examples/lab_report/template.docx --out slots.json

# ② 原位填充 + WPS 清洗 + 12 项审计 + 一步导出 PDF
uv run docx-lab fill examples/lab_report/template.docx examples/lab_report/payload.json \
  -o report_filled.docx --audit --pdf report_filled.pdf

# ③ 严格门禁校验 & 渲染 150 DPI 逐页 PNG 视觉验收
uv run docx-lab audit report_filled.docx --strict
uv run --extra preview docx-lab pdf report_filled.docx -o report_filled.pdf --preview-dir ./previews --dpi 150
TIP

Windows PowerShell:将续行符 \ 替换为 ` 或合并为单行运行。payload.json 中相对图片路径同时兼容 / 与 \,CLI 已自动处理 Windows 控制台 UTF-8 编码。

{
  "output_path": "report_filled.docx",
  "filled_cover_fields": ["专业", "报告人", "学号", "班级", "实验时间", "实验报告提交时间"],
  "filled_sections": ["实验步骤与结果", "实验结论"],
  "images_inserted": 2,
  "sanitized": true,
  "audit": { "passed": true, "pass_count": 12, "total_checks": 12, "issues": [] },
  "pdf": { "pdf_path": "report_filled.pdf", "engine": "dxpdf", "size_bytes": 406582, "elapsed_ms": 286.2 }
}

3. Python SDK

from docx_lab_plugin import audit_docx, convert_to_pdf, fill_docx_inplace, inspect_docx, render_pdf_pages

slots = inspect_docx("examples/lab_report/template.docx")
fill_docx_inplace("examples/lab_report/template.docx", payload, "report_filled.docx", sanitize_wps=True)
assert audit_docx("report_filled.docx")["passed"]

convert_to_pdf("report_filled.docx", "report_filled.pdf", engine="auto")
render_pdf_pages("report_filled.pdf", "previews", dpi=150)

MCP 与 AI Agent 插件

本仓库同时打包为标准 FastMCP Stdio 服务(docx-lab-mcp,兼容 mcp v1/v2)与 Antigravity 插件包(plugin.json、mcp_config.json、skills/lab-report-docx/SKILL.md)。

MCP 工具

用途

inspect_docx_template

扫描封面槽位、可填表格区、红字提示、单元格净宽与 WPS 风险诊断

fill_docx_report

按 JSON 原位填充模板、自动清洗并附带 12 项审计,可选一步导出 PDF

audit_docx_wps

对任意 .docx 运行 12 项 OOXML 保真度与 WPS 兼容性审计

convert_docx_to_pdf

导出高保真 PDF(auto / dxpdf / libreoffice),可选输出逐页 PNG

  • Antigravity 插件:克隆或软链接至 ~/.gemini/config/plugins/docx-lab-plugin(或工作区 .agents/plugins/docx-lab-plugin)。

  • Claude Code:

    claude mcp add docx-lab-plugin -- uv run --directory /ABSOLUTE/PATH/TO/docx-lab-plugin docx-lab-mcp
  • MCP Inspector 本地联调:

    npx @modelcontextprotocol/inspector uv run --directory /ABSOLUTE/PATH/TO/docx-lab-plugin docx-lab-mcp
{
  "mcpServers": {
    "docx-lab-plugin": {
      "command": "uv",
      "args": ["run", "--directory", "/ABSOLUTE/PATH/TO/docx-lab-plugin", "docx-lab-mcp"]
    }
  }
}

Windows 下可使用正斜杠路径,例如 "C:/Users/YourName/docx-lab-plugin"。


实测评估与基准

所有数据均由仓库内置评估脚本 eval/run_eval.py 实测生成并记录在 eval/results/latest.json,完整环境说明与指标定义见 BENCHMARKS.md。

评估场景

清洗前

清洗后

PDF 输出

dxpdf 中位耗时(Darwin arm64)

状态

institutional_lab_report(内置实验报告示例)

7/12

12/12

有效 / 4 页

191.4 ms

PASS

complex_merged_stress(合并表、OMML 公式、tblHeader)

7/12

12/12

有效 / 3 页

130.1 ms

PASS

edge_no_ref_jpeg_portrait(无参考正文、竖图限高、未触碰固定行高)

—

12/12

有效 / 2 页

97.9 ms

PASS

negative_robustness(损坏 ZIP 拦截、未清洗严格审计、缺失图片异常)

—

3/3 通过

—

—

PASS

本地复现单元测试与全部基准评估(Ubuntu / macOS / Windows CI 同步运行):

uv run --extra dev pytest -v
uv run --extra dev python eval/run_eval.py --check

适用边界与安全

  • 适用范围:.docx(OOXML)格式的实验报告、测试报告与结构化表单模板,支持封面多槽下划线、正文段落、代码块、PNG/JPEG 截图、合并表格、基础 OMML 公式及页眉页脚。

  • 已知边界:旧版二进制 .doc 需先转为 .docx;WordArt、SmartArt 等高级专有图形可配合 --engine libreoffice 使用本机 LibreOffice 渲染;Linux 精简镜像建议安装 Noto / 思源中文字体。

IMPORTANT

本地离线与安全设计:全流程在本地执行,零外部遥测;审计器强制启用防 XXE XML 解析(resolve_entities=False, no_network=True),子进程禁用 shell=True。详情见 SECURITY.md。


参与贡献 · 致谢 · 协议

Available Tools

4 tools
audit_docx_wpsA

Audit a .docx file across 12 OOXML fidelity and WPS Office compatibility checks.

Checks ZIP/XML well-formedness, media relationships, w:ulTrailSpace, cover hard page break, fixed table layout, exact row height clipping, inline image bounds, unique drawing IDs, East Asian font coverage, residual red prompt hints, header/footer integrity, and table borders.

Args: docx_path: Path to the .docx file to audit.

Returns: Formatted JSON string with passed, pass_count, total_checks, checks, and issues.

Inputs: docx_path (required). Returns: result

convert_docx_to_pdfA

Convert a .docx file to high-fidelity PDF and optionally render PNG previews.

Uses the Rust+Skia dxpdf engine by default without requiring Microsoft Word or WPS Office, with automatic LibreOffice headless fallback when engine="auto".

Args: docx_path: Path to the input .docx file. pdf_path: Destination path for the output .pdf file. engine: Conversion engine: auto, dxpdf, or libreoffice (default: auto). preview_dir: Optional directory path to render each PDF page as a PNG for visual verification. dpi: Resolution in DPI for rendered preview PNGs (default: 150).

Returns: Formatted JSON string containing conversion metadata and optional preview_pages paths.

Inputs: pdf_path (required), docx_path (required), dpi, engine, +1 more. Returns: result

fill_docx_reportA

Fill a .docx lab report template in-place while preserving its OOXML styling.

Preserves headers, footers, page numbers, table borders, cover underlines, and signature blocks. Optionally applies WPS Office compatibility sanitization and exports directly to PDF.

Args: template_path: Path to the source template .docx file. payload_json: JSON object string with cover_fields, sections (subheading, paragraph, code, image items), and optional keep_together_headings. output_path: Destination path for the filled .docx file. sanitize_wps: Apply 7-point WPS Office compatibility sanitization (default: True). export_pdf_path: Optional destination path to export a PDF after filling. pdf_engine: PDF engine when export_pdf_path is set: auto, dxpdf, or libreoffice (default: auto).

Returns: Formatted JSON string summarizing filled fields, sections, inserted images, WPS audit status, and optional PDF export details.

Inputs: output_path (required), payload_json (required), template_path (required), pdf_engine, +2 more. Returns: result

inspect_docx_templateB

Inspect a .docx lab report template for fillable slots and WPS diagnostics.

Scans cover fields (including fragmented runs and multi-slot lines), table section headings, red instructional prompts, cell widths, and WPS layout risks.

Args: docx_path: Path to the template .docx file.

Returns: Formatted JSON string containing file, cover_fields, table_slots, and diagnostics.

Inputs: docx_path (required). Returns: result

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.8/5.0

    Scored across 4 tools

    Disambiguation4/5

    The four tools form a mostly distinct pipeline: inspect template, fill report, audit WPS fidelity, and convert to PDF. The only meaningful overlap is between `inspect_docx_template` diagnostics and `audit_docx_wps`, since both surface WPS/layout risks, but the template-inspection vs post-fill-audit distinction is largely clear.

    Naming Consistency5/5

    All tool names use a consistent snake_case verb_docx_* pattern: inspect_docx_template, fill_docx_report, audit_docx_wps, convert_docx_to_pdf. The suffixes vary by target operation, but the naming convention is predictable throughout.

    Tool Count5/5

    Four tools is well-scoped for a focused DOCX lab report workflow. Each tool covers a distinct stage of the lifecycle and none feels redundant or unnecessary.

    Completeness4/5

    The tool set covers the core lifecycle: inspect a template, fill it, audit fidelity, and convert/export PDF with previews. Minor gaps exist around payload validation or repair workflows, but agents can reasonably work around them.

    Maintenance

    ActivityMaintained
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers