最近在微信看到一篇文章介绍说批量将ppt文件转化为pdf文件,自己尝试了一下,后面想能否自己封装一个类,既能将ppt转换为pdf,而且能够将word转换为pdf,或者其他类型转化为pdf。花了半天时间研究和找资料,终于完成了。
本人是在windows 10 、python3.6虚拟环境下完成的, 以下是具体内容:
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
#作者:cacho_37967865
#博客:https://blog.csdn.net/sinat_37967865
#文件:pdfConverter.py
#日期:2018-04-22
#备注:通过调用Python访问COM对象的comtypes包,批量将ppt或者word转换为PDF文件,先要在python环境安装comtypes
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
# F:\python_env\PaChong_env
# -*- coding: utf-8 -*-from comtypes.client import CreateObject
import osclass pdfConverter:def __init__(self):#word文档转化为pdf文档时使用的格式为17self.wdFormatPDF = 17self.wdToPDF = CreateObject("Word.Application")#ppt文档转化为pdf文档时使用的格式为32self.pptFormatPDF = 32self.pptToPDF = CreateObject("Powerpoint.Application")self.pptToPDF.Visible = 1def wd_to_pdf(self, folder):#获取指定目录下面的所有文件files = os.listdir(folder)#获取word类型的文件放到一个列表里面wdfiles = [f for f in files if f.endswith((".doc", ".docx"))]for wdfile in wdfiles:#将word文件放到指定的路径下面wdPath = os.path.join(folder, wdfile)#设置将要存放pdf文件的路径pdfPath = wdPath#判断是否已经存在对应的pdf文件,如果不存在就加入到存放pdf的路径内if pdfPath[-3:] != 'pdf':pdfPath = pdfPath + ".pdf"#将word文档转化为pdf文件,先打开word所在路径文件,然后在处理后保存pdf文件,最后关闭pdfCreate = self.wdToPDF.Documents.Open(wdPath)pdfCreate.SaveAs(pdfPath, self.wdFormatPDF)pdfCreate.Close()def ppt_to_pdf(self, folder):files = os.listdir(folder)pptfiles = [f for f in files if f.endswith((".ppt", ".pptx"))]for pptfile in pptfiles:pptPath = os.path.join(folder, pptfile)pdfPath = pptPathif pdfPath[-3:] != 'pdf':pdfPath = pdfPath + ".pdf"pdfCreate = self.pptToPDF.Presentations.Open(pptPath)pdfCreate.SaveAs(pdfPath, self.pptFormatPDF)pdfCreate.Close()if __name__ == "__main__":converter = pdfConverter()converter.ppt_to_pdf("F:\PythonProject\Pacong\ppt")converter.wd_to_pdf("F:\PythonProject\Pacong\ppt")
以后如果还想将其他类型的文件转换为pdf,可以在这个类中创建新的函数。在写这个类时遇到几个问题,大家也可能会遇到:
1. 刚开始运行时一直报错“Presentations.Open(pptPath)AttributeError: 'POINTER(IUnknown)' object has no attribute 'Presentations'”,找了好久才找到说好像是权限问题,需要在组件服务的DCOM配置进行处理。
2. word文档转换时的函数是:Documents.Open(),ppt转换时是:Presentations.Open()
3. 文件转换时有一个参数formatype,不同转换类型不一样:wdFormatPDF = 17,pptFormatPDF = 32
4. ppt转换时需要进行处理:pptToPDF.Visible = 1,word好像不需要
5. 这个转换用到了一个Python访问COM对象的comtypes包,可以通过pip直接安装
pip3 install comtypes