forked from baskbuddy/zhangshun
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
51 lines
1.7 KiB
51 lines
1.7 KiB
import pypandoc
|
|
import os
|
|
|
|
def convert_md_to_word(input_path, output_path):
|
|
"""
|
|
将Markdown文件转换为Word文档
|
|
|
|
Args:
|
|
input_path (str): 输入的Markdown文件路径
|
|
output_path (str): 输出的Word文档路径
|
|
"""
|
|
try:
|
|
# 检查输入文件是否存在
|
|
if not os.path.exists(input_path):
|
|
print(f"错误: 输入文件 '{input_path}' 不存在")
|
|
return False
|
|
|
|
# 检查并获取pandoc路径
|
|
try:
|
|
pandoc_path = pypandoc.get_pandoc_path()
|
|
print(f"已找到 pandoc: {pandoc_path}")
|
|
except OSError:
|
|
print("未检测到 pandoc,正在尝试下载...")
|
|
pypandoc.download_pandoc()
|
|
pandoc_path = pypandoc.get_pandoc_path()
|
|
print(f"pandoc 下载完成: {pandoc_path}")
|
|
|
|
# 执行转换
|
|
print(f"正在转换 {input_path} 到 {output_path}...")
|
|
pypandoc.convert_file(input_path, 'docx', outputfile=output_path)
|
|
print(f"\033[92m转换成功!输出文件: {output_path}\033[0m")
|
|
return True
|
|
|
|
except Exception as e:
|
|
print(f"转换失败: {str(e)}")
|
|
return False
|
|
|
|
# 使用示例
|
|
if __name__ == "__main__":
|
|
# 在这里设置你的输入和输出文件路径
|
|
# 注意:使用原始字符串(r前缀)或双反斜杠来避免转义问题
|
|
input_file = r"D:\Octopus\Documents\看山.md" # 输入的Markdown文件
|
|
output_file = r"D:\Octopus\Documents\看山文档.docx" # 输出的Word文件
|
|
|
|
# 执行转换
|
|
success = convert_md_to_word(input_file, output_file)
|
|
|
|
if success:
|
|
print("文档转换完成!")
|
|
else:
|
|
print("文档转换失败!")
|