使用Python实现Markdown转Word:一个优雅的文档转换工具

2025/5/22

在日常工作中,我们经常需要将Markdown格式的文档转换为Word格式。本文将介绍如何使用Python实现一个功能强大、使用简单的Markdown转Word转换工具,支持图片、表格等复杂格式的转换,并且完美支持中文排版。

# 为什么需要这个工具?

当我在写微信公众号的时候发现文档导入只支持docx,而我平时习惯编写markdown格式的文档,所以就尝试借助ai工具实现一个小工具方便使用。

# 工具特点

这个工具具有以下特点:

  1. 完美支持中文排版

    • 使用宋体作为默认字体
    • 自动处理中文字符
    • 支持中文标点符号
  2. 保持格式完整性

    • 支持图片转换
    • 支持表格转换
    • 支持代码高亮
    • 保持标题层级结构
  3. 智能排版

    • 自动生成目录
    • 优化段落间距
    • 合理的行间距
    • 专业的标题样式
  4. 用户友好

    • 图形界面操作
    • 支持拖拽文件
    • 详细的错误提示
    • 安装简单

# 实现原理

这个工具主要使用了以下技术:

  1. Pandoc:强大的文档转换引擎
  2. python-docx:Word文档处理库
  3. tkinter:图形界面实现
  4. pypandoc:Python的Pandoc接口

# 代码实现

首先,我们需要安装必要的依赖:

pip install pypandoc==1.11

然后,我们需要安装Pandoc软件:

  1. 访问 https://github.com/jgm/pandoc/releases/latest
  2. 下载并安装Windows安装包
  3. 确保选中"Add to PATH"选项

接下来是核心代码实现:

import os
import sys
import tkinter as tk
from tkinter import filedialog, messagebox
import pypandoc
from docx import Document
from docx.shared import Pt
from docx.enum.style import WD_STYLE_TYPE

def create_template():
    """创建默认的Word模板文件"""
    doc = Document()
    
    # 设置默认段落样式
    style = doc.styles['Normal']
    style.font.name = '宋体'
    style.font.size = Pt(12)
    style.paragraph_format.line_spacing = 1.5
    style.paragraph_format.space_after = Pt(10)
    
    # 设置标题样式
    for i in range(1, 7):
        style_name = f'Heading {i}'
        if style_name not in doc.styles:
            style = doc.styles.add_style(style_name, WD_STYLE_TYPE.PARAGRAPH)
        else:
            style = doc.styles[style_name]
        
        style.font.name = '宋体'
        style.font.size = Pt(16 - (i * 1))
        style.font.bold = True
        style.paragraph_format.space_before = Pt(12)
        style.paragraph_format.space_after = Pt(12)
        style.paragraph_format.line_spacing = 1.5
    
    return doc

def convert_md_to_docx(md_file_path, docx_file_path=None):
    """将Markdown文件转换为DOCX文件"""
    if docx_file_path is None:
        docx_file_path = os.path.splitext(md_file_path)[0] + '.docx'
    
    # 创建模板
    template_doc = create_template()
    template_path = 'template.docx'
    template_doc.save(template_path)
    
    # 转换参数
    extra_args = [
        '--standalone',
        '--wrap=none',
        '--toc',
        '--toc-depth=3',
        '--highlight-style=tango',
        f'--reference-doc={template_path}',
        '--variable', 'mainfont="宋体"',
        '--variable', 'fontsize=12pt',
        '--variable', 'geometry:margin=1in',
        '--variable', 'linestretch=1.5'
    ]
    
    # 执行转换
    pypandoc.convert_file(
        md_file_path,
        'docx',
        outputfile=docx_file_path,
        extra_args=extra_args
    )

# 使用方法

  1. 图形界面模式:
def select_file_and_convert():
    root = tk.Tk()
    root.withdraw()
    
    md_file = filedialog.askopenfilename(
        title="选择Markdown文件",
        filetypes=[("Markdown文件", "*.md"), ("所有文件", "*.*")]
    )
    
    if md_file:
        docx_file = filedialog.asksaveasfilename(
            title="保存DOCX文件",
            defaultextension=".docx",
            filetypes=[("Word文档", "*.docx")]
        )
        if docx_file:
            convert_md_to_docx(md_file, docx_file)
  1. 命令行模式:
python md_to_docx.py input.md output.docx

效果展示:

# 注意事项

  1. 确保正确安装Pandoc
  2. 检查图片路径是否正确
  3. 注意特殊字符的处理
  4. 保持Markdown格式的规范性

# 总结

这个工具通过结合Pandoc的强大功能和Python的灵活性,实现了一个功能完整、使用简单的Markdown转Word转换工具。它不仅支持基本的文本转换,还能完美处理图片、表格等复杂格式,特别适合中文文档的转换需求。

如果你有类似的需求,不妨试试这个工具。(从图片中可以看出特殊符号还是没有转换成功,还需要进行完善)