批量将ppt格式转为pptx格式

批量将ppt格式转为pptx格式

点点

2021-03-25 09:06 阅读 480 喜欢 0

如何将大量的ppt格式的文件批量转化为pptx格式的文件呢。

如果只有一两个,可以通过高版本的powerpoint软件直接打开ppt然后另存为pptx格式即可,但是如果是几百上千个文件,估计大部分人都会来找工具了。

可以通过python来调用本地的powerpoint来另存,代替我们手工保存。 在github上找了一个工具,可以支持ppt转pptx 或 pptx转ppt pdf png 等格式。

app.py

安装reportlab模块

pip3 install reportlab 将以下内容复制,保存在app.py文件中,当然,前提需要安装python环境,我本地安装的3.x .

-- coding: utf-8 --

""" @author: liuzhiwei @Date: 2020/11/15 """

import os import logging

from reportlab.lib.pagesizes import A4, landscape from reportlab.pdfgen import canvas import win32com.client

logger = logging.getLogger('Sun') logging.basicConfig(level=20, # format="[%(name)s][%(levelname)s][%(asctime)s] %(message)s", format="[%(levelname)s][%(asctime)s] %(message)s", datefmt='%Y-%m-%d %H:%M:%S' # 注意月份和天数不要搞乱了,这里的格式化符与time模块相同 )

def getFiles(dir, suffix, ifsubDir=True): # 查找根目录,文件后缀 res = [] for root, directory, files in os.walk(dir): # =>当前根,根下目录,目录下的文件 for filename in files: name, suf = os.path.splitext(filename) # =>文件名,文件后缀 if suf.upper() == suffix.upper(): res.append(os.path.join(root, filename)) # =>吧一串字符串组合成路径 if False is ifsubDir: break return res

class pptTrans: def init(self, infoDict, filePath): self.infoDict = infoDict self.filePath = filePath self.powerpoint = None

    self.init_powerpoint()
    self.convert_files_in_folder(self.filePath)
    self.quit()
    os.system('pause')

def quit(self):
    if None is not self.powerpoint:
        self.powerpoint.Quit()

def init_powerpoint(self):
    try:
        self.powerpoint = win32com.client.DispatchEx("Powerpoint.Application")
        self.powerpoint.Visible = 2
    except Exception as e:
        logger.error(str(e))

def ppt_trans(self, inputFileName):
    # https://docs.microsoft.com/en-us/office/vba/api/powerpoint.ppsaveasfiletype

    infoDict = self.infoDict
    formatType = infoDict['formatType']
    outputFileName = self.getNewFileName(infoDict['name'], inputFileName)

    if '' == outputFileName:
        return
    inputFileName = inputFileName.replace('/', '\\')
    outputFileName = outputFileName.replace('/', '\\')
    if '' == outputFileName:
        return
    if None is self.powerpoint:
        return
    powerpoint = self.powerpoint
    logger.info('开始转换:[{0}]'.format(inputFileName))
    deck = powerpoint.Presentations.Open(inputFileName)

    try:
        deck.SaveAs(outputFileName, formatType)  # formatType = 32 for ppt to pdf
        logger.info('转换完成:[{0}]'.format(outputFileName))
    except Exception as e:
        logger.error(str(e))
    deck.Close()

def convert_files_in_folder(self, filePath):
    if True is os.path.isdir(filePath):
        dirPath = filePath
        files = os.listdir(dirPath)
        pptfiles = [f for f in files if f.endswith((".ppt", ".pptx"))]
    elif True is os.path.isfile(filePath):
        pptfiles = [filePath]
    else:
        self.logError('不是文件夹,也不是文件')
        return

    for pptfile in pptfiles:
        fullpath = os.path.join(filePath, pptfile)
        self.ppt_trans(fullpath)

def getNewFileName(self, newType, filePath):
    try:
        dirPath = os.path.dirname(filePath)
        baseName = os.path.basename(filePath)
        fileName = baseName.rsplit('.', 1)[0]
        suffix = baseName.rsplit('.', 1)[1]
        if newType == suffix:
            logger.warning('文档[{filePath}]类型和需要转换的类型[{newType}]相同'.format(filePath=filePath, newType=newType))
            return ''
        newFileName = '{dir}/{fileName}.{suffix}'.format(dir=dirPath, fileName=fileName, suffix=newType)
        if os.path.exists(newFileName):
            newFileName = '{dir}/{fileName}_new.{suffix}'.format(dir=dirPath, fileName=fileName, suffix=newType)
        return newFileName
    except Exception as e:
        logger.error(str(e))
        return ''

class pngstoPdf: def init(self, infoDict, filePath): self.infoDict = infoDict self.powerpoint = None

    self.init_powerpoint()
    self.convert_files_in_folder(filePath)
    self.quit()
    os.system('pause')

def quit(self):
    if None is not self.powerpoint:
        self.powerpoint.Quit()

def init_powerpoint(self):
    try:
        self.powerpoint = win32com.client.DispatchEx("Powerpoint.Application")
        self.powerpoint.Visible = 2
    except Exception as e:
        logger.error(str(e))

def ppt_trans(self, inputFileName):
    # https://docs.microsoft.com/en-us/office/vba/api/powerpoint.ppsaveasfiletype
    infoDict = self.infoDict
    formatType = infoDict['formatType']
    outputFileName = self.getNewFolderName(inputFileName)

    if '' == outputFileName:
        return ''
    inputFileName = inputFileName.replace('/', '\\')
    outputFileName = outputFileName.replace('/', '\\')
    if '' == outputFileName:
        return ''
    if None is self.powerpoint:
        return ''
    powerpoint = self.powerpoint
    logger.info('开始转换:[{0}]'.format(inputFileName))
    deck = powerpoint.Presentations.Open(inputFileName)

    try:
        deck.SaveAs(outputFileName, formatType)
        logger.info('转换完成:[{0}]'.format(outputFileName))
    except Exception as e:
        logger.error(str(e))
        return ''
    deck.Close()
    return outputFileName

def convert_files_in_folder(self, filePath):
    if True is os.path.isdir(filePath):
        dirPath = filePath
        files = os.listdir(dirPath)
        pptfiles = [f for f in files if f.endswith((".ppt", ".pptx"))]
    elif True is os.path.isfile(filePath):
        pptfiles = [filePath]
    else:
        self.logError('不是文件夹,也不是文件')
        return

    for pptfile in pptfiles:
        fullpath = os.path.join(filePath, pptfile)
        folderName = self.ppt_trans(fullpath)
        try:
            self.png_to_pdf(folderName)
        except Exception as e:
            logger.error(str(e))
        for file in os.listdir(folderName):
            os.remove('{0}\\{1}'.format(folderName, file))
        os.rmdir(folderName)

def png_to_pdf(self, folderName):
    picFiles = getFiles(folderName, '.png')
    pdfName = self.getFileName(folderName)

    '''多个图片合成一个pdf文件'''
    (w, h) = landscape(A4)  #
    cv = canvas.Canvas(pdfName, pagesize=landscape(A4))
    for imagePath in picFiles:
        cv.drawImage(imagePath, 0, 0, w, h)
        cv.showPage()
    cv.save()

def getFileName(self, folderName):
    dirName = os.path.dirname(folderName)
    folder = os.path.basename(folderName)
    return '{0}\\{1}.pdf'.format(dirName, folder)

def getNewFolderName(self, filePath):
    index = 0
    try:
        dirPath = os.path.dirname(filePath)
        baseName = os.path.basename(filePath)
        fileName = baseName.rsplit('.', 1)[0]

        newFileName = '{dir}/{fileName}'.format(dir=dirPath, fileName=fileName)
        while True:
            if os.path.exists(newFileName):
                newFileName = '{dir}/{fileName}({index})'.format(dir=dirPath, fileName=fileName, index=index)
                index = index + 1
            else:
                break
        return newFileName
    except Exception as e:
        logger.error(str(e))
        return ''

if name == "main": transDict = {} transDict.update({1: {'name': 'pptx', 'formatType': 11}}) transDict.update({2: {'name': 'ppt', 'formatType': 1}}) transDict.update({3: {'name': 'pdf', 'formatType': 32}}) transDict.update({4: {'name': 'png', 'formatType': 18}}) transDict.update({5: {'name': 'pdf(不可编辑)', 'formatType': 18}})

hintStr = ''
for key in transDict:
    hintStr = '{src}{key}:->{type}\n'.format(src=hintStr, key=key, type=transDict[key]['name'])

while True:
    print(hintStr)
    transFerType = int(input("转换类型:"))
    if None is transDict.get(transFerType):
        logger.error('未知类型')
    else:
        infoDict = transDict[transFerType]
        path = input("文件路径:")
        if 5 == transFerType:
            pngstoPdf(infoDict, path)
        else:
            op = pptTrans(infoDict, path)

然后执行命令,选择序号,输入文件夹路径即可。

python app.py 静静等待程序自动转化即可。

转载请注明出处: http://sdxlp.cn/article/批量转换.html


如果对你有用的话,请赏给作者一个馒头吧 ...或帮点下页面底部的广告,感谢!!

赞赏支持
提交评论
评论信息(请文明评论)
暂无评论,快来快来写想法...
推荐
U盘使用过程中,莫名其妙的问题还是有很多的,其中最奇怪的就是出现U盘拒绝访问的问题,然后就无法打开U盘了,里面的资料也拷贝不出来,不用花钱,一招搞定。一招让u盘重获新生,千万不要拿去换新。u盘无法访问如何解决?
对于初级用户来说,可能还没有认识到无线加密的重要性,在不加密的无线网络里,不仅你的网络带宽会被侵占,而且你的个人网络信息也可能遭受泄露,因此一定要使用正确的加密方式来保障无线网络安全,降低风险。那么路由器如何安全设置?下面小编就为小伙伴们介绍路由器安全设置方法,这样设置路由99.9%的黑客都攻不破,一起来看看吧!
当小伙伴给电脑设置了密码,因为各种原因小伙伴们可能会忘记自己的电脑开机密码,在最新的windows10系统中忘记密码怎么办呢?这里为各位小伙伴带来分享,看一下开机密码忘记之后的解决办法,如何强制重置。
手机是我们生活中必备的生活用品,几乎人人都有一部手机,如今手机越来越智能化,也下载了越来越多的智能软件及娱乐软件,比如微信的内存异常的大,如果内存比较的小的手机,垃圾软件及垃圾文件占了内存后,手机就会变得很卡,这里点点把清内存的方式分享给小伙伴们。
生活中,小伙伴们肯定也遇到了这样的问题。点点给小伙伴们解惑来了。好多天没开电脑啦!正好用到电脑,刚打开就傻眼啦。结果开机进不了系统,蓝屏显示自动修复失败,立马选了启动修复,但可想而知不起作用。主要是不想花钱,嘻嘻。经过几天的折腾,终于,柳暗花明,进入系统。下面给点点分享这几天所查到并使用的方法,以及最后是用什么方法解决的。
随着网络普及,视频、语音聊天成了小伙伴们又一种不可或缺的通讯方式,但是很多的时候,会出现这样或者那样的问题,用QQ语音聊天时对方听不到我的声音,而我能听到对方的声音。针对这个问题,作如下详细解答,帮助小伙伴们轻松解决这个难题。
通讯软件有很多,但我们常用的就是微信,微信中的游戏小程序是很多的,可是如果我们不玩的话,就可以选择关闭其入口,今天小编就告诉小伙伴们手机微信怎么关闭发现页中的游戏入口。
微信现在是当下常用的社交软件,当我们遇到朋友时候,该怎样添加其联络方式哪?怎样关注公众号?怎样删除微信好友?怎样取消关注公众号哪?重点来了,跟我来。