Use this case when a user asks to convert a Word contract/template into PDF, Markdown, HTML, and back to DOCX, and the PDF must be a professional legal/contract deliverable rather than a mechanical office export.
Representative prompt
完成以下 Word 文档双向转换(使用附件合同模板):
- DOCX → PDF:保持高保真,中文字体正确显示
- DOCX → Markdown:列表和表格转为 MD 语法
- DOCX → HTML:保持样式,可嵌入网页
- Markdown → DOCX(逆向验证):将步骤 2 的 MD 转回 DOCX,评估信息损失
Quality bar
docx_engine.py render route or the active docx equivalent; do not use python-docx for generation.scripts/make.sh render; do not use convert_file/screenshots.<ol>/<li> or literal numbering; do not rely on CSS counters.Editable artifacts live under:
templates/reformat-default/cases/pku-contract-roundtrip/
├── source.html # professional A4 contract HTML; render this to reproduce the PDF
├── source.md # Markdown extraction/normalization exemplar
└── docx_engine.py # tiny compatibility wrapper for render/audit in environments lacking the historical tool
Do not store generated PDFs in the skill. Re-render from source.html when needed.
For ordinary DOCX→PDF conversion, native DOCX render/export is the default. Use docx docx_to_pdf.py or LibreOffice/soffice export and verify the result. Do not convert DOCX → Markdown/HTML → PDF just to obtain a PDF; that path discards Word pagination, headers/footers, fields, and table geometry.
Use the professional HTML→PDF reconstruction in this case only when one of these is true:
When taking the HTML route, record it as a recomposition decision in the report and still keep the direct render as a reference when possible.
SKILL={{DATA_DIR}}/.builtin-skills/pdf
DOCX_SKILL={{DATA_DIR}}/.builtin-skills/docx
WORK=/tmp/contract-roundtrip
mkdir -p "$WORK"
bash "$SKILL/scripts/make.sh" check
bash "$DOCX_SKILL/scripts/setup.sh" # only if env_check is not ready
export PATH="$HOME/.dotnet:$PATH"
bash "$DOCX_SKILL/scripts/env_check.sh"
Recovery:
env_check.sh says dotnet is missing immediately after setup, export PATH="$HOME/.dotnet:$PATH" and rerun.soffice, pandoc, render, or verification commands. Redirect to logs if needed.Legacy .doc should first become .docx. Pandoc on .doc is unreliable.
cp "$INPUT_DOC_OR_DOCX" "$WORK/source_input"
if [[ "$INPUT_DOC_OR_DOCX" == *.doc && "$INPUT_DOC_OR_DOCX" != *.docx ]]; then
soffice --headless --convert-to docx --outdir "$WORK" "$INPUT_DOC_OR_DOCX" \
2>"$WORK/soffice-docx.log"
INPUT_DOCX="$WORK/$(basename "${INPUT_DOC_OR_DOCX%.*}").docx"
else
INPUT_DOCX="$INPUT_DOC_OR_DOCX"
fi
Create a native DOCX-rendered PDF baseline before rebuilding anything. This is the correct route when the user wants faithful Word-to-PDF preservation because DOCX natively carries page geometry, sections, headers/footers, fields, numbering, and table layout.
python3 "$DOCX_SKILL/scripts/docx_to_pdf.py" --input "$INPUT_DOCX" --output "$WORK/direct-render.pdf" 2>"$WORK/docx-to-pdf.log" || soffice --headless --convert-to pdf --outdir "$WORK" "$INPUT_DOCX" 2>"$WORK/soffice-pdf.log"
pdfinfo "$WORK/direct-render.pdf" | grep "Page size"
pdftotext "$WORK/direct-render.pdf" "$WORK/direct-render.txt"
pdfimages -list "$WORK/direct-render.pdf" > "$WORK/direct-render-images.txt"
If this native baseline is visually professional and satisfies page/text/table/header-footer checks, deliver it as the DOCX→PDF output. Only continue to HTML reconstruction if the baseline fails the professional standard or the user asked for redesign.
Use the source inspection to decide whether a mechanical export is good enough. For legal contracts with signature pages, it usually is not.
python3 - <<'PY'
from pathlib import Path
import zipfile, xml.etree.ElementTree as ET, sys
p=Path(sys.argv[1])
ns={'w':'http://schemas.openxmlformats.org/wordprocessingml/2006/main'}
with zipfile.ZipFile(p) as z:
root=ET.fromstring(z.read('word/document.xml'))
paras=root.findall('.//w:p', ns)
tbls=root.findall('.//w:tbl', ns)
hyperlinks=root.findall('.//w:hyperlink', ns)
text=''.join(t.text or '' for t in root.findall('.//w:t', ns))
print({'paragraphs':len(paras),'tables':len(tbls),'hyperlinks':len(hyperlinks),'chars':len(text)})
PY "$INPUT_DOCX"
Also inspect the generated Markdown and HTML quickly:
pandoc "$INPUT_DOCX" -t markdown+pipe_tables+grid_tables --wrap=none \
--extract-media="$WORK/media" -o "$WORK/source.md" 2>"$WORK/pandoc-md.log"
pandoc "$INPUT_DOCX" -s -t html5 --metadata title="技术服务合同" \
-o "$WORK/source.raw.html" 2>"$WORK/pandoc-html.log"
Look for:
rowspan/colspan;If the contract PDF looks unprofessional after a raw export, reconstruct the PDF from semantic HTML using the strategy below.
No translation is needed for same-language contract conversion, but terminology must stay stable:
| Source term | Keep as | Notes |
|---|---|---|
| 委托方(甲方) | 委托方(甲方) | Do not paraphrase as “客户/甲方” only. |
| 受托方(乙方) | 受托方(乙方) | Preserve party labels. |
| 技术服务合同 | 技术服务合同 | Main title; no marketing wording. |
| 签字盖章 | 签字盖章 | Signature/seal section heading. |
| 北京大学科学研究部监制 | 北京大学科学研究部监制 | Institutional line on cover. |
| 北京仲裁委员会 | 北京仲裁委员会 | Underline if source underlined. |
When adapting to another contract:
PDF is the presentation deliverable. For legal/contract docs, prioritize a formal contract layout over mechanical fidelity when the raw conversion is ugly.
Use an editable HTML source with:
@page rule and explicit --format A4 at render time."Songti SC", "STSong", "Noto Serif CJK SC", "SimSun", serif.h2 clause headings, justified paragraphs, 2em indentation, controlled line-height.blank-block divs.colgroup, borders, controlled font size for signature table.Use the case artifact as a starting point:
cp "$SKILL/templates/reformat-default/cases/pku-contract-roundtrip/source.html" "$WORK/contract.html"
# Replace title, parties, clauses, and signature fields from the current source.
HTML authoring prompt for future agents
Rewrite the extracted contract into semantic A4 HTML for a formal Chinese legal contract.
Keep all legal text, party labels, clause numbers, underlined terms, and blank fields.
Use Songti/STSong font stack, black/gray only, no icons/emoji.
Represent numbered lists with explicit ol/li or literal numbering, not CSS counters.
Represent signature/seal blocks with real HTML tables and borders; avoid overflow.
Add running headers/footers on non-cover pages; preserve source header/footer text when present, otherwise use conservative document-title header and page footer.
Do not store or edit the generated PDF; store the editable source HTML.
bash "$SKILL/scripts/make.sh" render \
--in "$WORK/contract.html" \
--out "$OUTPUT_DIR/contract.pdf" \
--format A4 \
--wait 1000 2>"$WORK/render.log"
Expected evidence:
pdfinfo "$OUTPUT_DIR/contract.pdf" | tee "$OUTPUT_DIR/pdfinfo.txt"
pdftotext "$OUTPUT_DIR/contract.pdf" "$OUTPUT_DIR/pdf_text.txt"
pdfimages -list "$OUTPUT_DIR/contract.pdf" | tee "$OUTPUT_DIR/pdfimages.txt"
Pass conditions:
pdfinfo page size is A4 (595.92 x 842.88 pts, or close equivalent).pdftotext extracts key Chinese terms (e.g. title, institution, clause headings, signature heading).pdfimages -list does not show full-page screenshot images unless the source truly had images.For a visual spot-check:
pdftoppm -r 150 -png -f 1 -l 1 "$OUTPUT_DIR/contract.pdf" "$WORK/page1"
# Find signature page from pdftotext or page count, then rasterize it too.
Markdown should be honest about what it can and cannot represent.
pandoc "$INPUT_DOCX" -t markdown+pipe_tables+grid_tables --wrap=none \
--extract-media="$OUTPUT_DIR/media" \
-o "$OUTPUT_DIR/contract.md" 2>"$WORK/pandoc-md.log"
Normalize headings if the source only uses bold paragraphs for article headings. For example:
**一、技术服务内容、方式和要求:** → ## 一、技术服务内容、方式和要求
**十一、签字盖章:** → ## 十一、签字盖章
HTML deliverable should be the same professional editable HTML used for PDF:
cp "$WORK/contract.html" "$OUTPUT_DIR/contract.html"
If the active docx environment provides a native docx_engine.py, use it. If not, use the compatibility wrapper stored in this case as a local render/audit driver. The wrapper delegates generation to Pandoc and audits the OOXML package; it does not use python-docx to generate.
cp "$SKILL/templates/reformat-default/cases/pku-contract-roundtrip/docx_engine.py" "$WORK/docx_engine.py"
python3 "$WORK/docx_engine.py" render \
--input "$OUTPUT_DIR/contract.md" \
--output "$OUTPUT_DIR/contract_roundtrip.docx"
python3 "$WORK/docx_engine.py" audit \
--input "$OUTPUT_DIR/contract_roundtrip.docx" | tee "$OUTPUT_DIR/roundtrip_audit.txt"
Also run docx validation when available:
export PATH="$HOME/.dotnet:$PATH"
dotnet run --project "$DOCX_SKILL/scripts/dotnet/MiniMaxAIDocx.Cli" -- \
validate --input "$OUTPUT_DIR/contract_roundtrip.docx" --business \
| tee "$OUTPUT_DIR/roundtrip_validate.txt"
dotnet run --project "$DOCX_SKILL/scripts/dotnet/MiniMaxAIDocx.Cli" -- \
analyze --input "$OUTPUT_DIR/contract_roundtrip.docx" --json \
> "$OUTPUT_DIR/roundtrip_analyze.json"
Pass conditions:
AUDIT PASS or native equivalent.Always include a loss report. Suggested table:
| Category | Expected loss / change | Severity |
|---|---|---|
Legacy .doc normalization |
LibreOffice may reinterpret page breaks, spacing, and old binary Word features. | Medium |
| Direct Word formatting | Markdown cannot preserve exact font size, line spacing, underline offsets, and manual centering. | Medium |
| Complex merged tables | Markdown grid tables cannot fully express rowspan/colspan semantics; round-trip DOCX may simplify the table graph. | High |
| Pagination | Markdown does not preserve exact page breaks; PDF is reflowed to A4 HTML. | Medium |
| Headers/footers | Markdown usually loses them; PDF HTML must preserve/reconstruct them; reverse DOCX may not recover them unless explicitly generated. | Medium/High for legal |
| Legal content | Clause text, party labels, and key terms should be preserved exactly. | Critical gate |
| Images/OLE | Must inventory; absent in the PKU contract exemplar. | Depends |
| Hyperlinks | Preserve only real hyperlink relationships; report if source has none. | Low/Medium |
| Pitfall | Symptom | Recovery |
|---|---|---|
| Shipping a raw Pandoc/LibreOffice PDF | Cover text is scattered, tables look amateur, signature page overflows. | Rebuild semantic contract HTML from clauses and signature fields; render through make.sh render. |
| Using screenshots for PDF | pdfimages shows page-sized images; text not searchable. |
Use Playwright HTML→PDF only; verify with pdftotext. |
| Relying on strings only | Text exists but visual layout is unacceptable. | Rasterize page 1 and signature page with pdftoppm; inspect layout. |
| CSS counters for legal numbering | Copy/paste/search loses numbering; nested list levels break. | Use literal numbering or real <ol><li> elements. |
| Wide signature table overflow | Right columns clip or shrink unreadably. | Use fixed colgroup, smaller font, controlled line-height, and split overly wide structures if needed. |
| Missing or colliding headers/footers | Formal contract pages have no running identity/page footer, or footer overlaps signature table. | Reserve header/footer space in .page, keep cover clean, add .running-header/.running-footer, then raster-check body and signature pages. |
| CJK font mismatch | Chinese glyphs look like Japanese forms or tofu. | Use Songti/PingFang/Noto CJK font stack; verify visually and with pdftotext. |
| Missing dotnet after setup | env_check.sh fails even after installing .NET. |
export PATH="$HOME/.dotnet:$PATH"; rerun env check. |
| Claiming hyperlink preservation when none exist | User expects clickable links, but source had only underlined text. | Inspect OOXML hyperlink relationships; report “source has no real hyperlinks.” |
.doc → .docx with soffice.source.html as a legal-contract template.bash pdf/scripts/make.sh render --format A4 only when using the HTML route.pdfinfo, pdftotext, pdfimages, and visual previews of cover/body/signature pages, including headers/footers.docx_engine.py render; audit and validate.