python-pptx将现有ppt的每张幻灯片另存为图片

问题描述 投票:3回答:1

我使用Powerpoint作为网页的用户界面来制作简单的图片。我今天要做的是在ppt中创建幻灯片,然后将每张幻灯片另存为图片,然后我的网络会下载图片并显示出来。我想尽可能地使此过程自动化,以摆脱这种手动保存的方式。

我已经查看了python-pptx包,但是找不到该函数,该函数使我可以将每张幻灯片另存为图片。您能帮我吗?

image save-as python-pptx
1个回答
0
投票

python-pptx不是此任务的正确工具,因为它根本不与PowerPoint交互(在没有安装PowerPoint版本的情况下,它可以工作)。如果您的系统上安装了PowerPoint,则可以使用例如comtypes模块以从python控制它。如何执行此操作的示例可在python-pptx-interface模块中找到:

 from comtypes.client import Constants, CreateObject

# ...

def save_pptx_as_png(png_foldername: str, pptx_filename: str, overwrite_folder: bool = False):
    if os.path.isdir(png_foldername) and not overwrite_folder:
        print(f"Folder {png_foldername} already exists. "
              f"Set overwrite_folder=True, if you want to overwrite folder content.")
        return

    powerpoint = CreateObject("Powerpoint.Application")
    pp_constants = Constants(powerpoint)

    pres = powerpoint.Presentations.Open(pptx_filename)
    pres.SaveAs(png_foldername, pp_constants.ppSaveAsPNG)
    pres.close()
    if powerpoint.Presentations.Count == 0:  # only close, when no other Presentations are open!
        powerpoint.quit()

这应该给您一个想法,如何编写自己的save_as_png函数。

或者您直接使用python-pptx-interface:

from pptx_tools import utils  # needs python-pptx-interface installed
# you should use full paths, to make sure PowerPoint can handle the paths
png_folder = ...
pptx_file = ... 

utils.save_pptx_as_png(png_folder, pptx_file)  # additional optional parameter overwrite_folder
© www.soinside.com 2019 - 2024. All rights reserved.