word批量转换成pdf

# -*- coding:utf-8 -*-

from win32com.client import gencache
from win32com.client import constants
import os
import time

def create_pdf(word_path, pdf_path):
    """ word转pdf :param word_path: word路径 :param pdf_path: pdf路径 :return: """
    word = gencache.EnsureDispatch('Word.Application')
    doc = word.Documents.Open(word_path, ReadOnly=1)
    doc.ExportAsFixedFormat(pdf_path,
                            constants.wdExportFormatPDF,
                            Item=constants.wdExportDocumentWithMarkup,
                            CreateBookmarks=constants.wdExportCreateHeadingBookmarks)
    word.Quit(constants.wdDoNotSaveChanges)


# 遍历当前目录,并把word转成pdf
def word_to_pdf():
    print('转换中........')
    # 获取当前运行路径
    path = os.getcwd()
    # 获取所有文件名(列表形式)
    filename_list = os.listdir(path)
    # 获取所有word文件名列表
    wordname_list = [filename for filename in filename_list if filename.endswith(('.doc', '.docx'))]
    for wordname in wordname_list:
        pdfname = os.path.splitext(wordname)[0] + '.pdf'
        if pdfname in filename_list:
            continue
        # 拼接路径和文件名
        word_path = os.path.join(path, wordname)
        pdf_path = os.path.join(path, pdfname)
        create_pdf(word_path, pdf_path)
        time.sleep(5)
        print(f'{ pdfname}转换成功')

if __name__ == '__main__':
    word_to_pdf()
    print('Done')

    原文作者:市民先生
    原文地址: https://blog.csdn.net/weixin_45983953/article/details/121133319
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞