首页 > 技术文章 > 用python将word转pdf、doc转docx等

SirPi 2021-03-23 17:13 原文

word ==> pdf

def doc2pdf(file_path):
    """
    word格式转换doc|docx ==> pdf
    :return:
    """
    file_name, file_extension = os.path.splitext(file_path)  # 获取文件名、文件扩展名
    file_abs_path = os.path.abspath(file_path)  # 通过相对路径获取绝对路径
    file_abs_name = os.path.splitext(file_abs_path)[0]  # 将文件和后缀分开
    file_new_path = file_abs_name + r".pdf"  # 组合新的文件名
    if file_extension in [".doc", '.docx']:
        # 打开word应用程序
        wd = Dispatch("Word.application")
        # 后台运行
        wd.Visible = 0
        wd.DisplayAlerts = 0
        # 打开doc|docx文档,必须给一个绝对路径
        doc = wd.Documents.Open(file_abs_path)
        # 另存为pdf
        doc.SaveAs(file_new_path, 17)  # 17表示pdf格式
        # 关闭文档
        doc.Close()
        # 退出word应用
        wd.Quit()
    return file_new_path

doc ==> docx

def doc2docx(file_path):
    """
    word格式转换doc ==> docx
    :return:
    """
    file_name, file_extension = os.path.splitext(file_path)  # 获取文件名、文件扩展名
    file_abs_path = os.path.abspath(file_path)  # 通过相对路径获取绝对路径
    file_new_path = file_abs_path + r"x"
    if file_extension in [".doc"]:
        # 打开word应用程序
        wd = Dispatch("Word.application")
        # 后台运行
        wd.Visible = 0
        wd.DisplayAlerts = 0
        # 打开doc文档,必须给一个绝对路径
        doc = wd.Documents.Open(file_abs_path)
        # 另存为docx
        doc.SaveAs(file_new_path, 12)  # 12表示docx格式
        # 关闭文档
        doc.Close()
        # 退出word应用
        wd.Quit()
    return file_new_path

 

推荐阅读