批量将ppt格式转为pptx格式

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

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

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

我们可以通过python来调用本地的powerpoint来另存,代替我们手工保存。
在github上找了一个工具,可以支持pptpptxpptxppt 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 

静静等待程序自动转化即可。

相关文章
|
12月前
|
自然语言处理 数据处理 Python
python操作和解析ppt文件 | python小知识
本文将带你从零开始,了解PPT解析的工具、工作原理以及常用的基本操作,并提供具体的代码示例和必要的说明【10月更文挑战第4天】
1854 60
|
C++ Python Perl
终于解决VScode中python/C++打印中文全是乱码的问题了
终于解决VScode中python/C++打印中文全是乱码的问题了
1162 0
终于解决VScode中python/C++打印中文全是乱码的问题了
|
并行计算 PyTorch 算法框架/工具
Importing the numpy C-extensions failed.
Importing the numpy C-extensions failed.
1867 0
Importing the numpy C-extensions failed.
Python实现PowerPoint演示文稿到图片的批量转换
PowerPoint演示文稿作为展示创意、分享知识和表达观点的重要工具,被广泛应用于教育、商务汇报及个人项目展示等领域。然而,面对不同的分享场景与接收者需求,有时需要我们将PPT内容以图片形式保存与传播。 这样能够避免软件兼容性的限制,确保信息接收者无需安装特定软件即可查看内容,还便于在网络社交平台、博客、电子邮件中快速分享与嵌入。而用Python代码可以高效地实现PowerPoint演示文稿到图片的批量转换,从而提升工作效率。
|
12月前
|
存储 自然语言处理 文字识别
纯前端RAG:使用Transformers.js实现纯网页版RAG(一)
本文将分两部分教大家如何在网页中实现一个RAG系统,本文聚焦于深度搜索功能。通过浏览器端本地执行模型,可实现文本相似度计算和问答匹配,无需依赖服务器。RAG搜索基于高维向量空间,即使不完全匹配也能找到意义相近的结果。文中详细介绍了如何构建知识库、初始化配置、向量存储及相似度计算,并展示了实际应用效果。适用于列表搜索、功能导航、文档查询及表单填写等多种场景。
1355 0
|
Java Spring Maven
gradle 配置指南
在`build.gradle`中配置Gradle仓库,首先添加阿里云公共仓库
|
搜索推荐 开发工具 数据安全/隐私保护
注册Github账号详细教程
一、GitHub的简介 1、大概介绍 GitHub是一个面向开源及私有软件项目的托管平台,因为只支持Git作为唯一的版本库格式进行托管,故名GitHub。 2、详细介绍 https://baike.baidu.com/item/github/10145341 二、如何注册自己的GitHub账户 1、进入github的官网 https://github.com/https://github.com/ 2、点击右上角注册按钮sign up,来到注册页面
1072 0
|
前端开发 API 开发工具
阿里云oss开发实践:大文件分片、断点续传、实时进度 React+Node+Socket.IO
阿里云oss开发实践:大文件分片、断点续传、实时进度 React+Node+Socket.IO
2429 2
|
数据采集 数据可视化 物联网
电子班牌系统源码——全功能智慧管理平台系统
通过智慧班牌,一方面呈现了班级文化的丰富多彩,同时,也成为了学校和班级,教师和学生,以及家长和学生之间的互动媒介之一。 电子班牌系统是全功能智慧管理平台系统,电子班牌系统是以出勤管理和班级信息展示为主体,为学校教育行业量身设计的一款集云平台、网络数据实时通信技术、物联网技术、智能控制技术、信息发布管理技术为一体的智慧平台系统。
411 0
电子班牌系统源码——全功能智慧管理平台系统
|
C++ 计算机视觉 Windows
Visual Studio 安装OpenCV及问题总结
1、VS安装OpenCV基本步骤   1)安装Visual Studio     下载网址https://opencv.org/releases.html#   2)安装OpenCV      下载网址https://www.
3769 0