python 批量更换PPT logo 图片_html

做了很多PPT,突然想要更换PPT的logo。由于开始并没有设计好母版,导致现在无法利用PPT的快捷方法更改PPT上的logo。只能手动的修改,想一想几十个PPT......

python 批量更换PPT logo 图片_html_02

马上网上搜索python 如何处理 PPT ,找到一个 ​python-pptx​ 模块可以处理ppt。


安装好开始。


找了一个案例,跟着试了一下,正常对PPT读取,新增,查看都可以,唯独删除PPT上某个元素做不到,找了很多案例都没有解决类似的问题。


最后在 https://stackoverflow.com/ 上找到一个说法,说通过lxml 解析的元素都有通用的方法的。

python 批量更换PPT logo 图片_html_03

重新查找文档,通过type 和 list 查看内部结构,试了几次,最终解决掉这个问题。

# 核心代码
e = list(shape.element)[1]
e.getparent().remove(e)

第二个问题来了,PPT页面上的 logo 位置不统一,最后通过判断文档采用的模板是否一致,从而删除不同位置内容。


最终代码:

from pptx import Presentation
from pptx.util import Inches


prs = Presentation("测试.pptx")
img_path = 'python.png' # 文件路径


for slide in list(prs.slides)[1:]:
if slide.slide_layout.name=="Blank":
for shape in list(slide.shapes)[1:12]:
e = list(shape.element)[1]
e.getparent().remove(e)
left, top, width, height = Inches(1), Inches(
0.2), Inches(3), Inches(1) # 预设位置及大小
else:
for shape in list(slide.shapes)[1:6]:
e = list(shape.element)[1]
e.getparent().remove(e)
left, top, width, height = Inches(10.5), Inches(
0.2), Inches(3), Inches(1) # 预设位置及大小
slide.shapes.add_picture(
img_path, left, top, width, height) # 在指定位置按预设值添加图片


prs.save("测试2.pptx")


结果:

python 批量更换PPT logo 图片_html_04

以上代码没有通用性,需要根据自己的 ppt 结构来。


参考:

  1. 文档:https://python-pptx.readthedocs.io/en/latest/index.html

  2. https://stackoverflow.com/questions/64700638/is-there-a-way-to-delete-a-shape-with-python-pptx


(全文完)


长按二维码,加关注!叶子陪你玩

python 批量更换PPT logo 图片_ide_05


欢迎转载,转载请注明出处!

欢迎关注公众微信号:叶子陪你玩编程