使用Python(win32com.client)向PowerPoint幻灯片插入图片

3 投票
4 回答
8420 浏览
提问于 2025-04-17 01:14

我被分配了一个任务,要把几百张图片插入到一个PowerPoint文件里,并且调整它们的大小。需要使用一种特定的格式,这种格式跟我们公司其他的PowerPoint文件很相似。

我在尝试使用ActivePython的win32com API,已经搞明白了怎么打开文件和创建一个空白的幻灯片。

我想知道怎么插入一张图片,并把它调整到我需要的大小(每一页上只放图片)。另外,我还想用我们公司的主题作为背景和标题页,不过这不是最重要的,最重要的是把图片放上去并调整好大小。

任何帮助都非常感谢,谢谢!

4 个回答

1

首先,我会在插入之前先调整图片的大小,使用的是 PIL 这个Python图像处理库。总的来说,我在处理任何办公软件的图像时都觉得很糟糕,所以我不太推荐这样做。

其次,在PowerPoint的帮助文档或者网上找到的 VBA 对象模型示例,通常就足够你用很长一段时间了。

我记得插入图片的过程其实挺简单的 -

ppt.slide.ImageFromFile("path")

不过关于精确定位的部分我不太记得了,而且我现在没有PowerPoint可以试。如果有机会的话,我会再发一些参考资料。

祝你在文档处理上好运!

2

你应该使用Shapes.AddPicture,具体的说明可以在这里找到(这是这个坏链接的存档版本):

from tkinter import *
import tkinter.filedialog as tkFileDialog
import win32com.client # middleman/translator/messanger between windows and python
import win32com.gen_py.MSO as MSO # contains constants refering to Microsoft Office Objects
import win32com.gen_py.MSPPT as MSPPT # contains constants refering to Microsoft Office Power Point Objects
g = globals() # a dictonary of global vlaues, that will be the constants of the two previous imports
for c in dir(MSO.constants): g[c] = getattr(MSO.constants, c) # globally define these
for c in dir(MSPPT.constants): g[c] = getattr(MSPPT.constants, c)
Application = win32com.client.Dispatch("PowerPoint.Application")
Application.Visible = True # shows what's happening, not required, but helpful for now
Presentation = Application.Presentations.Add() # adds a new presentation
Slide1 = Presentation.Slides.Add(1, ppLayoutBlank) # new slide, at beginning
TenptStr = Slide1.Shapes.AddShape(msoShape10pointStar, 100, 100, 200, 200)
pictName = tkFileDialog.askopenfilename(title="Please Select the Image you wish to load")
print(pictName)
Pict1 = Slide1.Shapes.AddPicture(FileName=pictName, LinkToFile=False, SaveWithDocument=True, Left=100, Top=100, Width=200, Height=200)

请注意,"选择文件"的选项会生成一个文件路径,其中包含'/'而不是'',你可能需要把前者替换成后者。

2

我从Xavier提到的页面上得到了这个:

Pict1 = Slide1.Shapes.AddPicture(FileName=pictName, LinkToFile=False, SaveWithDocument=True, Left=100, Top=100, Width=200, Height=200)

如果你的原始图片是正方形的,这样做是可以的;但如果不是,就会让图片变形。

最好把宽度和高度都设为-1。这样PPT会按照图片的“自然”大小插入它们(PPT怎么定义这个大小就不重要了)。然后你可以查看形状的大小,来确定它的长宽比,并确保在你改变大小时这个比例保持不变。或者你可以把形状的.LockAspectRatio属性设为true,这样调整高度或宽度时,另一个会自动调整,以保持长宽比。

撰写回答