【python】PPT转PDF(同一目录下批量)

这里有一大堆ppt需要转成方便记笔记的pdf
可以直接点击下面目录中完整代码获取可以直接使用的脚本,该脚本可以将所在目录下的PPT转成PDF并将其存在当前目录新建文件夹converted_directory


主要借鉴的是 这篇博文,补充了一些解释和py语法的演示示例
可直接使用的完整代码在最后
放进需要转换格式ppt文件的文件夹内运行即可,转换生成的pdf文件在ppt相同目录下名为converted_directory的文件夹中

需要的库

pypiwin32 pip install pypiwin32
导入的模块是win32com
先用pip命令看一下有没有安装pip
在这里插入图片描述
这里看到是安装了
然后用pip下载库
在这里插入图片描述
这里显示pip版本需要更新,没有关系,更新一下就行
在这里插入图片描述
…我还是卸了python重新装一下吧
现在继续,刚刚安装了py3.10.6
现在是已经用pip下载好了pypiwin32(顺手更新一下pip
在这里插入图片描述

win32com 模块主要为 Python 提供调用 windows 底层组件对 word 、Excel、PPT 等进行操作的功能,只能在 Windows 环境下使用,并且需要安装 office 相关软件才行

一般步骤

通常将PPT转为PDF的步骤是:到目标文件所在目录,初始化PowerPoint端口应用程序,另存为pdf文件到目标目录,关闭ppt文件
在自动化程序中,可以调用相关库中的实现函数来实现相应步骤
参考文档:Presentation.ExportAsFixedFormat 方法 (PowerPoint)
这里是批量处理,所以要获取文件夹内所有ppt文件的路径

主函数
def main():
    filePath,pptFlies=GetFilePath();
    NewDirectory=os.path.join(filePath,"converted_directory")
    if not os.path.exists(NewDirectory):
        os.mkdir(os.path.join(NewDirectory))#crate the directory if it not exits
    for each in pptFlies:
        pptToPDF(each,NewDirectory)
筛选出路径中的.ppt/.pptx文件
os.path模块

os.path模块详细使用说明
os.path.abspath((__file__))abspath()获取当前文件的绝对路径
os.path.split(examplePath)将examplePath分割成目录和文件名二元组返回//split:分割
示例程序:

import os
print(os.path.abspath(__file__)) # "__file__" 表示当前文件
import os
examplePath=os.path.abspath(__file__)
print(examplePath)
print(os.path.split(examplePath))

运行结果
在这里插入图片描述
在这里插入图片描述
该元组后面加方括号可以选择返回二元组的元素
示例程序:

import os
examplePath=os.path.abspath(__file__)
print(examplePath)
print(os.path.split(examplePath))
print(os.path.split(examplePath)[0])
print(os.path.split(examplePath)[1])

运行结果:
在这里插入图片描述
dirnamebasename顾名思义是返回examplePath的目录和文件名
示例程序:

import os
examplePath=os.path.abspath(__file__)
print(examplePath)
print(os.path.split(examplePath))
print('\n')
print(os.path.split(examplePath)[0])
print(os.path.dirname(examplePath))
print('\n')
print(os.path.split(examplePath)[1])
print(os.path.basename(examplePath))

运行结果:
在这里插入图片描述

glob模块

Python模块——glob模块详解
glob模块是python标准库中的一个模块,主要用来查找符合特定规则的目录和文件,支持几个特殊的正则通配符
glob.glob()返回符合匹配条件的所有文件的路径,返回一个列表,元素是符合匹配条件的所有文件路径(验证演示结果在第一个子函数代码后)
os.path.join() 把目录和文件名合成一个路径

filePath=os.path.split(os.path.abspath(__file__))[0]
pptFiles=glob.glob(os.path.join(filePath,"*.ppt*"))#意思是合成filePath/*.ppt* 的文件名
#内层括号合成路径 具体为该目录下的内容,路径名+文件名+后缀ppt/pptx
#外层glob.glob()将目录下的文件与合成的进行比较,若相符,则为需要找的ppt/pptx文件
第一个子函数

这里就可以写出第一个子函数,用于筛选出当前目录下所有ppt文件
代码如下:

def GetFilePath():
    #obtain the path of all ppt/pptx files in this directory
    filePath=os.path.split(os.path.abspath(__file__))[0]
    pptFiles=glob.glob(os.path.join(filePath,"*.ppt*"))
    return filePath,pptFiles #返回文件路径和文件名的二元组

这里看到GetFilePath() 有两个返回值,这里是以元组的形式返回的

关于python子函数的多个返回值
glob.glob() 函数的返回类型验证
在该函数执行完后添加语句print(pptFiles),其中pptFiles是该函数的返回
在这里插入图片描述

将PPT文件转换为PDF文件

pptToPDF() 函数代码:

def pptToPDF(filename,new_directory):
    #Example Initialize a PowerPoint application instance
    pdfName=os.path.basename(filename).split('.')[0]+'.pdf'
    savePathFile=os.path.join(new_directory,pdfName)
    if os.path.isfile(savePathFile): #judge if the str savePathFile is a file existed
        print(pdfName,"converted already")
        return
    p=gencache.EnsureDispatch("PowerPoint.Application")# guessing that has some connections with open the PowerPoint Application
    try:
        ppt=p.Presentations.Open(filename,False,False,False)#open the PowerPoint file 
    except Exception as e:
        print(os.path.split(filename)[1],"File format conversion failed,because %s" %e)  #throw 
    ppt.ExportAsFixedFormat(savePathFile,2,PrintRange=None)
    print("converted && saved :", savePathFile)
    p.Quit     #close the PowerPoint file                  
先生成.ppt文件对应.pdf文件的文件名

可用于检测该pdf文件是否在目的目录已经存在

pdfName=os.path.basename(filename).split('.')[0]+'.pdf'
#split('.') 用符号"."分隔前面的地址,返回的是元组
#[0] 取元组的第一个元素
#+'.pdf' 在字符串后面加上.pdf
savePath=os.path.join(newdirectory,pdfName)
#把PDF文件的存储路径和文件名合成一个路径

示例程序:

import os
examplePath=os.path.abspath(__file__)
print(examplePath)
print(os.path.basename(__file__))
print(os.path.basename(__file__).split('.'))
print(os.path.basename(__file__).split('.')[0]+'.pdf')
print(os.path.basename(__file__).split('.')[1]+'.pdf')

运行结果:
在这里插入图片描述
之后的if语句是判断该PDF文件在存储路径是否存在,若已经存在则在控制台输出相关信息,跳过该文件;若不存在则继续下面的程序创建PDF文件
os.path.isfile()判断路径是否为文件

创建PowerPoint文件实例
打开PowerPoint应用程序
p=gencache.EnsureDispatch("PowerPoint.Application")

这个链接有参考
另一种实现方法在这篇博文

presentations 对象& ExportAsFixedFormat 方法

在 Microsoft PowerPoint 中的所有 演示文稿 对象的集合。 每个 演示文稿 对象代表当前在 PowerPoint 中打开演示文稿。官方文档
Presentations.Open 方法 (PowerPoint)
ExportAsFixedFormat 方法等效于在 PowerPoint 用户界面 Office 菜单上的 另存为 PDF 或 XPS 命令。 该方法将创建一个包含当前演示文稿的静态视图文件。

ppt=p.Presentations.Open(filename,False,False,False)#open the PowerPoint file 
ppt.ExportAsFixedFormat(savePathFile,2,PrintRange=None)

函数pptToPDF() 中,为了让程序可以顺利执行,引入了异常。若文件格式不能成功转换则进入异常处理,在控制台输出异常原因后继续剩余文件的转换

完整代码

import os
import glob
from win32com.client import gencache
def GetFilePath():
    #obtain the path of all ppt/pptx files in this directory
    filePath=os.path.split(os.path.abspath(__file__))[0]
    pptFiles=glob.glob(os.path.join(filePath,"*.ppt*"))
    #print(pptFiles)
    return filePath,pptFiles 

def pptToPDF(filename,new_directory):
    #Example Initialize a PowerPoint application instance
    pdfName=os.path.basename(filename).split('.ppt')[0]+'.pdf'
    savePathFile=os.path.join(new_directory,pdfName)
    if os.path.isfile(savePathFile): #judge if the str savePathFile is a file existed
        print(pdfName,"converted already")
        return
    p=gencache.EnsureDispatch("PowerPoint.Application")# guessing that has some connections with open the PowerPoint Application
    try:
        ppt=p.Presentations.Open(filename,False,False,False)#open the PowerPoint file 
    except Exception as e:
        print(os.path.split(filename)[1],"File format conversion failed,because %s" %e)  #throw 
    ppt.ExportAsFixedFormat(savePathFile,2,PrintRange=None)
    print("converted && saved :", savePathFile)
    p.Quit     #close the PowerPoint file       

def main():
    filePath,pptFlies=GetFilePath();#PPT文件所在目录和所有ppt文件目录的列表
    NewDirectory=os.path.join(filePath,"converted_directory")
    #生成PDF文件的存储路径
    if not os.path.exists(NewDirectory):
        os.mkdir(os.path.join(NewDirectory))#crate the directory if it not exits
    for each in pptFlies:
        pptToPDF(each,NewDirectory)

if __name__ =="__main__":
    main()            

程序运行结果

在这里插入图片描述
第二次运行程序时,因为目标目录下该pdf文件已存在,不再进行转换,输出该文件已存在的信息
在这里插入图片描述

后续及使用中错误的解决

2022-09-07 20:20:26----------------------------------------------------------------
暂时修复了一个bug–文件名生成异常
pptToPDF() 函数第一行语句
pdfName=os.path.basename(filename).split('.')[0]+'.pdf'改为
pdfName=os.path.basename(filename).split('.ppt')[0]+'.pdf'
之前的情况,某次使用中(cmd窗口上一次运行的输出)及修好后
在这里插入图片描述
2022-09-08 13:04:00----------------------------------------------------------------
解决了一个报错
AttributeError: module 'win32com.gen_py.91493440-5A91-11CF-8700-00AA0060263Bx0x2x12' has no attribute 'CLSIDToClassMap'
在过了一段时间我又需要用脚本转换课件格式时,报了这个错误
在这里插入图片描述
长话短说:
删除C:\Users\15951\AppData\Local\Temp\gen_py\3.10下名字是一堆数字的文件夹,那些是缓存文件
当然也有可能找不到APPdata文件夹,那个文件夹很重要,应该没人删掉吧(
在C://users/username下找不到APPdata,可以看看是不是被隐藏了
在最上面的查看,把隐藏的项目打勾,再看能不能找到APPdata
在这里插入图片描述

详细记录---------------------------
搜索解决方法
解决方法:删除缓存文件91493440-5A91-11CF-8700-00AA0060263Bx0x2x12
然而我在自己的机器上并没有找到那个目录
于是我去找python的安装目录,试图找到gen_py
在这里插入图片描述
选择中间的Repair,一直点next直到可以看到安装路径
在这里插入图片描述
可以看到我的python安装目录是D://python/
进去看看

在这里插入图片描述
应该把上面的搜索设置选成当前文件夹
在这里插入图片描述
发现不在这里面
既然当时是用pip下载的,不妨去找找pip的安装目录
默认的安装路径
在这里插入图片描述

我发现我没这路径,不过也没有关系,python om site查看一下在这里插入图片描述
(啥也没找着)
那直接把缓存文件删掉好了
找到的代码:查找pywin32在运行时产生的cache文件路径,并删除
这个tm还是要找那个路径啊
在经过直接搜索缓存文件名等一系列降秩操作后…
我发现思路出了问题
APPdata是保存系统设置和软件设置的文件夹,一些软件也安装在这里,我肯定不可能给它删了,于是我开始搜APPdata文件夹找不到了怎么办
原来是APPdata文件夹是被隐藏了
在这里插入图片描述
找到了gen_py文件夹
在这里插入图片描述
既然要清缓存不如全清了
再用上面那个链接的代码

 from win32com.client.gencache import EnsureDispatch
 import sys
 
 xl = EnsureDispatch("Word.Application")
 print(sys.modules[xl.__module__].__file__)

C:\Users\15951\AppData\Local\Temp\gen_py\3.10下运行一下,删除所有名字是一堆数字的文件夹
删除后再运行一下文件转换脚本(刚开始以为是脚本出了问题,就用了之前的脚本给原来的删了,发现也不行)
在这里插入图片描述
运行完之后看到这堆东西我心里一紧,不过再次运行一下发现pdf是已经生成了
在这里插入图片描述
用浏览器看一下文件(因为我懒得再去打开文件资源管理器了)
在这里插入图片描述
看文件大小是对的,再打开看一下也没有什么问题
在这里插入图片描述
问题解决

2022-09-23 09:37:00----------------------------------------------------------------

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值