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)
相关推荐
审小匠OpenCPAi2 分钟前
审计票据与财报 PDF 怎么识别?通用 OCR、表格结构识别与多模态大模型的精度对比
pdf·ocr·审计
李昊哲小课6 分钟前
FastAPI 猫咖预约系统 API
人工智能·python·fastapi
你驴我21 分钟前
WhatsApp 消息撤回与编辑的幂等性设计实践
java·服务器·前端·后端·python
向日的葵00627 分钟前
Redis会话机制vsJWT机制深度解析
数据库·redis·python·缓存·系统架构·jwt
祉猷并茂,雯华若锦28 分钟前
Win下完美解决Allure报错,生成Web自动化测试报告
android·python·selenium·自动化
2501_930707781 小时前
使用C#代码将 PDF 文件转换为 Markdown 格式
pdf
cui_ruicheng1 小时前
Python数据分析(一):数据分析概述与环境搭建
开发语言·python·数据分析
aqi001 小时前
15天学会AI应用开发(十六)LangChain实现对话记忆功能
人工智能·python·大模型·ai编程·ai应用
blns_yxl1 小时前
正则驱动实时表单验证(HTML+CSS+JS+正则)
javascript·css·html