使用Python将word转换为pdf

使用Python可以将多个word文件一起转为pdf,操作比较便捷,可以实现自动化办公。

代码如下:

from win32com.client import constants,gencache
import os
# Word转pdf方法,第一个参数代表word文档路径,第二个参数代表pdf文档路径
def Word_to_Pdf(Word_path,Pdf_path):
    word = gencache.EnsureDispatch('Word.Application')
    doc = word.Documents.Open(Word_path,ReadOnly = 1)
    # 转换方法
    doc.ExportAsFixedFormat(Pdf_path,constants.wdExportFormatPDF)
    word.Quit()
# # 调用方法,进行单个文件的转换
# Word_to_Pdf('E:/B_pycharm/python_word_create.docx','E:/B_pycharm/python_word_create.pdf')
# 多个文件的转换
print(os.listdir('.')) # 当前文件夹下的所有文件
Word_files = []
for file in os.listdir('.'):
    # 找出所有后缀为doc或者docx的文件
    if file.endswith(('.doc','.docx')):
        Word_files.append(file)
print(Word_files)
for file in Word_files:
    file_path = os.path.abspath(file)
    index = file_path.rindex('.')
    pdf_path = file_path[:index] + '.pdf'
    print(file_path)
    print(pdf_path)
    Word_to_Pdf(file_path,pdf_path)

运行结果:

使用Python将word转换为pdf_第1张图片
使用Python将word转换为pdf_第2张图片


欢迎大家查看作者的主页,主页中还有关于编程与算法方面的更多内容,欢迎大家相互沟通学习。

你可能感兴趣的:(python,开发语言,自动化)