python代码——批量将PPT转换成长图

news/2024/7/24 10:14:01 标签: python, 开发语言

语言:python 3

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

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

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

代码1,需安装库

#安装库
pip install pyautogui
#安装库
pip install  pillow

python">
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如下:

python">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()


http://www.niftyadmin.cn/n/4960961.html

相关文章

【面试题】:前端怎么实现权限设计及遇到的bug

一.权限的概念 前端权限分为页面权限、按钮权限、API权限。 二.页面权限的实现过程 ①用户登录进去调用获取用户信息接口,后端会给我们返回一个权限标识符 ②在获取到数据之后,我们就要判断用户能访问到哪些页面,我们可以在vuex中permission模块中的action…

【SpringBoot】SpringBoot项目与Vue对接接口的步骤

下面是SpringBoot项目与Vue对接接口的步骤: 创建SpringBoot项目,在项目中添加依赖,如Spring MVC、MyBatis等框架。 在SpringBoot项目中编写接口方法,使用注解标识请求方式,如GetMapping、PostMapping等,并…

Linux系统常用指令

目录 1.帮助指令 2.文件目录指令* 3.查找指令 4.时间日期指令 5.压缩和解压 1.帮助指令 ctrl c 取消命令,并且换行(清空换行)作用,单独清空为crtl u tab换行键 补全命令和文件名,快速按两下可以显示备选选项 …

Java 注解计算12生肖,java Data中获取年,根据生日日期获取生肖注解,根据输入时间获取生肖,自定义注解的方式获取生肖 根据年份时间获取十二生肖

最近,开发中需要增加生肖,但是不想增加字段,于是通过注解的方式,实现生日与生肖的转换。 话不多说,直接上代码,如下: 实体类中的字段,添加自定义注解(ToChineseZodiacSe…

【Windows 常用工具系列 10 -- linux ssh登录脚本输入密码】

文章目录 脚本输入SSH登录密码scp 脚本免密传输 脚本输入SSH登录密码 sshpass 是一个用于运行时非交互式ssh密码提供的工具,它允许你直接在命令行中为ssh命令提供密码。这就意味着你可以在脚本中使用ssh命令,而不需要用户交互地输入密码。 一般来说&am…

packge.json中的browserlistrc配置有什么用?

theme: smartblue 前端开发中,需要考虑前端开发中,需要考虑CSS及JS的兼容性,browserlistrc指定了需要兼容的浏览器。 数据来源 Browserslist 的数据都是来自caniuse.com的。 使用方法 package.json {"browserslist": ["l…

web基础http与apache

一、http相关概念: http概述: HTTP 是一种用作获取诸如 HTML 文档这类资源的协议。它是 Web 上进行任何数据交换的基础,同时,也是一种客户端—服务器(client-server)协议 为解决"用什么样的网络协…

如何获取当前 JAR 包的存放位置?

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录 前言代码中如何获取打包后的jar包存放的位置? 前言 代码中如何获取打包后的jar包存放的位置? 要获取当前运行的 JAR 包所存放的位置&#…