python将目录下的所欲md文件转化为html和pdf

python将目录下的所欲md文件转化为html和pdf

python 复制代码
import os
import subprocess
import win32com.client as win32


def md_to_docx(md_path, docx_path):
    """
    将 Markdown 文件转换为 DOCX 文件
    :param md_path: Markdown 文件的路径
    :param docx_path: 输出 DOCX 文件的路径
    :return: 转换成功返回 True,失败返回 False
    """
    try:
        # 构建 pandoc 命令
        command = ['pandoc', md_path, '-o', docx_path]
        # 执行命令
        result = subprocess.run(command, check=True, capture_output=True, text=True)
        print(f"成功将 {md_path} 转换为 {docx_path}")
        return True
    except subprocess.CalledProcessError as e:
        print(f"转换 {md_path} 到 {docx_path} 时出错: {e.stderr.strip()}")
        return False
    except FileNotFoundError:
        print("未找到 pandoc 命令,请确保 pandoc 已正确安装并配置到系统路径中。")
        return False


def docx_to_pdf(docx_path, pdf_path):
    """
    将 DOCX 文件转换为 PDF 文件
    :param docx_path: DOCX 文件的路径
    :param pdf_path: 输出 PDF 文件的路径
    :return: 转换成功返回 True,失败返回 False
    """
    try:
        word = win32.gencache.EnsureDispatch('Word.Application')
        doc = word.Documents.Open(docx_path)
        doc.SaveAs(pdf_path, FileFormat=17)  # 17 代表 PDF 文件格式
        doc.Close()
        word.Quit()
        print(f"成功将 {docx_path} 转换为 {pdf_path}")
        return True
    except Exception as e:
        print(f"转换 {docx_path} 到 {pdf_path} 时出错: {e}")
        return False


def md_to_pdf(input_file, output_file):
    """
    先将 Markdown 转换为 DOCX,再将 DOCX 转换为 PDF
    :param input_file: Markdown 文件路径
    :param output_file: 输出的 PDF 文件路径
    """
    # 生成临时 DOCX 文件路径
    temp_docx_file = os.path.splitext(input_file)[0] + '.temp.docx'
    # 转换 Markdown 到 DOCX
    if md_to_docx(input_file, temp_docx_file):
        # 转换 DOCX 到 PDF
        if docx_to_pdf(temp_docx_file, output_file):
            # 转换成功,删除临时 DOCX 文件
            try:
                os.remove(temp_docx_file)
                print(f"已删除临时文件 {temp_docx_file}")
            except OSError as e:
                print(f"删除临时文件 {temp_docx_file} 时出错: {e}")
        else:
            print(f"未能将 {temp_docx_file} 转换为 {output_file}")
    else:
        print(f"未能将 {input_file} 转换为 {temp_docx_file}")


def convert_all_md_to_pdf(root_dir):
    """
    遍历指定目录下的所有 Markdown 文件并转换为 PDF
    :param root_dir: 根目录
    """
    for root, dirs, files in os.walk(root_dir):
        for file in files:
            if file.endswith('.md'):
                input_file = os.path.join(root, file)
                # 构建输出的 PDF 文件路径
                output_file = os.path.splitext(input_file)[0] + '.pdf'
                md_to_pdf(input_file, output_file)


if __name__ == "__main__":
    # 替换为你要处理的根目录
    root_directory = 'D:\\Code'
    convert_all_md_to_pdf(root_directory)
相关推荐
我命由我123452 小时前
CesiumJS 笔记 - 获取容器中心点、Cartesian3 clone 方法、修改 Cartesian3 对象的高度
前端·javascript·css·前端框架·html·html5·js
从零开始学习人工智能3 小时前
【踩坑实录】WSL2 解决 onnxruntime\-gpu ImportError: libcudart\.so\.13 无 CUDA13 运行库问题
python
卷无止境4 小时前
在 awesome-fastapi 里,哪些库值得一看?
后端·python
zhanghaha13144 小时前
Python进阶教程:6_JSON 数据解析 —— 新手完全指南
开发语言·python·json
Python私教5 小时前
API 输出模型怎么设计:从 model_dump() 到显式展示层
python·fastapi
Python私教5 小时前
本地 AI 工具服务该绑定 127.0.0.1 还是 0.0.0.0?
python·fastapi
卷无止境5 小时前
FastAPI 的Admin面板生态
后端·python
ctlover6 小时前
Streamlit 框架
python
ι:6 小时前
MATLAB 与 Python 搭建无人机地面站:优势、劣势与选型逻辑
python·matlab·无人机
船厂电气自动化ai大模型6 小时前
AI大模型与数学 第32课 函数凹凸性与二阶导数:拐点求解、凹凸区间计算(10道二阶导数计算题)
数据结构·人工智能·python·深度学习·算法