Python实现批量将PPT转换成长图

 更新时间:2023年08月25日 09:04:58   作者:谷雨之际  
这篇文章主要为大家详细介绍了如何利用Python实现批量将PPT转换成长图,并且图片名称与PPT文件名称相同,保存位置相同,感兴趣的小伙伴可以了解下

语言:python 3

用法:点击运行后,弹出窗口,选择文件夹,程序运行会将文件夹内的所有PPT文件全部转换成PPT长图,图片名称与PPT文件名称相同,保存位置相同。

如运行中报错,需要自行根据报错内容按照缺失的库

共分享两种代码,可以尝试运行。

代码1

需安装库

#安装库
pip install pyautogui
#安装库
pip install  pillow
 
import os
import comtypes.client
from tkinter import Tk, filedialog
from PIL import Image
def ppt_to_images(ppt_file):
 try:
    # 导入comtypes.client模块并创建PowerPoint应用程序对象
    powerpoint = comtypes.client.CreateObject("Powerpoint.Application")
    # 设置PowerPoint应用程序为可见状态,便于观察操作过程(可选),修改为0后报错
    #powerpoint.Visible = 1
    # 打开PPT文件,并返回Presentation对象
    presentation = powerpoint.Presentations.Open(ppt_file)
    for i, slide in enumerate(presentation.slides):      #slide是幻灯片序列
        slide.Export(f"slide_{i}.png", "PNG")
    # 关闭PPT文件
    presentation.Close()
    # 退出PowerPoint应用程序
    powerpoint.Quit()
    presentation = None
    print(ppt_file+"分图完成!")
 except Exception as e:
        print("分图时发生错误:", str(e))
def merge_images(directory, png_file):
    try:
        Image.MAX_IMAGE_PIXELS = 2 ** 40
        images = []  # 存储图片对象
        for file in os.listdir(directory):
            file_path = os.path.join(directory, file)
            if os.path.isfile(file_path) and file.lower().endswith(".png"):
                image = Image.open(file_path)
                images.append(image)
        if len(images) == 0:
            print("未找到PNG格式的图片文件")
            return None
        max_width = max(image.size[0] for image in images)  # 获取最大宽度
        total_height = sum(image.size[1] for image in images)  # 计算总高度
        final_image = Image.new("RGBA", (max_width, total_height), (0, 0, 0, 0))  # 创建最终图像
        # 逐个粘贴图片到最终图像中
        y_offset = 0
        for image in images:
            final_image.paste(image, (0, y_offset))
            y_offset += image.size[1]
        final_image.save(png_file)
        print("已生成图片"+png_file)
        if final_image:
            for file in os.listdir(directory):
                file_path = os.path.join(directory, file)
                if os.path.isfile(file_path) and file.lower().endswith(".png") and "slide" in file:
                    os.remove(file_path)
                    print("已删除图片"+file)
    except Exception as e:
        print("合并图片时发生错误:", str(e))
def select_directory():
    try:
        root = Tk()
        root.withdraw()
        directory = filedialog.askdirectory(title="选择目录")
        ppt_files = [f for f in os.listdir(directory) if f.endswith('.pptx')or f.endswith('.ppt')]
        for ppt_file in ppt_files:
          try:
            #print("directory" + directory)
            if ppt_file.lower().endswith(".pptx"):
               png_file = os.path.join(directory, ppt_file[:-5] + ".png")
               ppt_to_images(ppt_file)  # PPT to image
               merge_images(directory, png_file)  # image to images
            elif ppt_file.lower().endswith(".ppt"):
                png_file = os.path.join(directory, ppt_file[:-4] + ".png")
                ppt_to_images(ppt_file)  # PPT to image
                merge_images(directory, png_file)  # image to images
          except Exception as e:
           print("处理PPT文件时发生错误,跳过该文件:", str(e))
        print("转换完成!")
    except Exception as e:
        print("选择目录并转换PPT文件时发生错误:", str(e))
# 选择目录并转换PPT到PDF格式,再将PDF转换为长图
select_directory()
 

代码2

import os
import comtypes.client
from tkinter import Tk, filedialog
from pptx import Presentation
from PIL import Image
#PPT转换成图片
def ppt_to_images(ppt_file, png_file):
    #presentation = powerpoint.Presentations.Open(ppt_file)
    presentation = Presentation(os.path.join(png_file, ppt_file))
    for i, slide in enumerate(presentation.slides):      #slide是幻灯片序列
        slide.export(f"{png_file}/slide_{i}.png")     #将PPT转换成图片并保存到目录下
    print("PPT转换为图像完成!")
#将图片拼接成长图
def merge_images(ppt_path, output_file):
    images = [Image.open(f"{ppt_path}/{img}") for img in os.listdir(ppt_path) if img.endswith(".png")]
    widths, heights = zip(*(img.size for img in images))
    total_height = sum(heights)
    max_width = max(widths)
    merged_image = Image.new("RGB", (max_width, total_height))
    y_offset = 0
    for img in images:
        merged_image.paste(img, (0, y_offset))
        y_offset += img.size[1]
    merged_image.save(output_file)
    print("图像拼接完成!")
def ppt_to_pdf(ppt_path, pdf_file):   #ppt路径和pdf的路径
    # 导入comtypes.client模块并创建PowerPoint应用程序对象
    powerpoint = comtypes.client.CreateObject("Powerpoint.Application")
    # 设置PowerPoint应用程序为可见状态,便于观察操作过程(可选),修改为0后报错
    powerpoint.Visible = 1
    # 打开PPT文件,并返回Presentation对象
    presentation = powerpoint.Presentations.Open(ppt_path)
    # 将打开的PPT文件导出为PDF文件(第二个参数2表示导出为PDF格式)
    presentation.ExportAsFixedFormat(pdf_file, 2)
    # 输出转换完成的信息
    print(ppt_path + "转PDF完成!")
def select_directory():
    root = Tk()
    root.withdraw()
    directory = filedialog.askdirectory(title="选择目录")
    ppt_files = [f for f in os.listdir(directory) if f.endswith('.pptx')]
    for ppt_file in ppt_files:
        ppt_path = os.path.join(directory, ppt_file)       #ppt_path ppt的路径,拼接ppt
        pdf_file = os.path.join(directory, ppt_file[:-4] + ".pdf")    #pdf文件
        png_file= os.path.join(directory, ppt_file[:-4] + ".png")
        ppt_to_pdf(ppt_path, pdf_file)
    print("转换完成!")
# 选择目录并转换PPT到PDF格式,再将PDF转换为长图
select_directory()

到此这篇关于Python实现批量将PPT转换成长图的文章就介绍到这了,更多相关Python PPT转长图内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • pandas进行时间数据的转换和计算时间差并提取年月日

    pandas进行时间数据的转换和计算时间差并提取年月日

    这篇文章主要介绍了pandas进行时间数据的转换和计算时间差并提取年月日,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-07-07
  • Python 查找字符在字符串中的位置实例

    Python 查找字符在字符串中的位置实例

    下面小编就为大家分享一篇Python 查找字符在字符串中的位置实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-05-05
  • Python开发中的Nonetype类型详解

    Python开发中的Nonetype类型详解

    这篇文章主要介绍了Python开发中的Nonetype类型详解,None有自己的数据类型NoneType,你可以将None复制给任何变量,但是你不能创建其他NoneType对象,需要的朋友可以参考下
    2023-12-12
  • 简单示例入门了解Python TkInter框架

    简单示例入门了解Python TkInter框架

    这篇文章主要为大家通过简单示的示例带大家入门了解Python TkInter框架,让大家对Python TkInter有一个简单的认知,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步
    2023-11-11
  • python模块restful使用方法实例

    python模块restful使用方法实例

    这篇文章主要介绍了python模块restful使用方法,大家参考使用吧
    2013-12-12
  • Python提取特定时间段内数据的方法实例

    Python提取特定时间段内数据的方法实例

    今天小编就为大家分享一篇关于Python提取特定时间段内数据的方法实例,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-04-04
  • python中eval与int的区别浅析

    python中eval与int的区别浅析

    这篇文章主要给大家介绍了关于python中eval与int的区别,文中通过示例代码介绍的非常详细,对大家学习或者使用python具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-08-08
  • python 除法保留两位小数点的方法

    python 除法保留两位小数点的方法

    今天小编就为大家分享一篇python 除法保留两位小数点的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-07-07
  • matplotlib 三维图表绘制方法简介

    matplotlib 三维图表绘制方法简介

    这篇文章主要介绍了matplotlib 三维图表绘制方法简介,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-09-09
  • python中tab键是什么意思

    python中tab键是什么意思

    在本篇内容里小编给大家整理了关于python中的tab键表示什么意思的相关内容,需要的朋友们可以参考学习下。
    2020-06-06

最新评论