docx-formatter-cn 使用文档

📦 安装

从源码安装

git clone https://github.com/vajhXajhcv/docx-formatter-cn.git
cd docx-formatter-cn
pip install -e .

依赖要求

🖥️ 命令行使用

Markdown 转 Word

python -m docx_formatter.cli convert input.md -o output.docx -t 课程论文

批量转换

python -m docx_formatter.cli batch input_dir/ -o output_dir/ -t 课程论文

修正现有 Word

python -m docx_formatter.cli format input.docx -o output.docx -t 毕业论文 --add-toc

查看模板信息

python -m docx_formatter.cli info -t 毕业论文
python -m docx_formatter.cli export-template -t 课程论文 -o template.json

常用参数

参数说明
-t, --template模板预设:课程论文 / 毕业论文 / 数学建模 / 公文
--template-file自定义模板 JSON/YAML 文件
--image-dir图片基础目录
--add-toc添加目录(format 命令)

🐍 Python API

Markdown 转 Word

from docx_formatter import convert_markdown_to_docx

with open("论文.md", "r", encoding="utf-8") as f:
    md_text = f.read()

convert_markdown_to_docx(md_text, "output.docx", template="课程论文")

修正已有 docx

from docx_formatter import format_docx

format_docx("old.docx", "formatted.docx", template="毕业论文", add_toc=True)

📝 Markdown 语法支持

YAML Frontmatter

---
title: 论文标题
author: 作者姓名
date: 2026-05-28
abstract: 摘要内容...
keywords: [关键词1, 关键词2]
---

基础语法

语法效果
# 标题一级标题
**粗体**粗体
*斜体*斜体
<u>下划线</u>下划线
~~删除线~~删除线
`code`行内代码

公式

行内公式:$E = mc^2$ 或 \(E = mc^2\)

块级公式:
$$E = mc^2$$

或:
\[E = mc^2\]

图片尺寸控制

![图1](images/fig1.png)
![图2](images/fig2.png =400x300)

表格

| 算法 | 时间复杂度 | 空间复杂度 |
|------|-----------|-----------|
| 快速排序 | O(n log n) | O(log n) |

其他

🎨 模板系统

预设模板

模板适用场景
课程论文日常课程作业、小论文
毕业论文本科/硕士毕业论文
数学建模数学建模竞赛论文
公文政府机关公文格式

自定义模板

{
  "name": "我的模板",
  "chinese": "宋体",
  "english": "Times New Roman",
  "size_pt": 12,
  "line_spacing": 1.5,
  "margin_top_mm": 25,
  ...
}
提示:使用 export-template 命令导出预设模板作为自定义模板的基础。

❓ 常见问题

公式显示为乱码?

确保文档中使用的是 Cambria Math 字体。该字体在 Windows 和 macOS 上默认安装。

中文字体显示不正确?

模板默认使用 SimSun(宋体)和 SimHei(黑体)。如果系统没有这些字体,可以在自定义模板中指定其他中文字体,如 "chinese": "Source Han Serif CN"

图片无法加载?

支持相对路径和 HTTP/HTTPS URL。对于本地图片,请使用 --image-dir 指定图片所在目录。

如何添加页眉页脚?

在自定义模板中设置 header_textfooter_page_number 字段。