from pptx import Presentation
from pptx.util import Inches
from pptx.enum.shapes import MSO_SHAPE_TYPE
def insert_image_to_PPT(img_path,presentation_path):
# 创建或打开一个演示文稿对象
prs = Presentation(presentation_path)
# 确保有第一张幻灯片
slide = prs.slides[0]
# 清除幻灯片上的所有图片
shapes_to_remove = [shape for shape in slide.shapes if shape.shape_type == MSO_SHAPE_TYPE.PICTURE]
for shape in shapes_to_remove:
slide.shapes._spTree.remove(shape.element)
print("Removed shape:", shape.name)
# 假设你想在文本框的位置添加图片,但是我们直接将图片添加到幻灯片上
# 假设文本框的位置和尺寸如下:
left = Inches(0.34) # 文本框左边界
top = Inches(1) # 文本框顶边界
width = Inches(12.5) # 文本框宽度
height = Inches(1.2) # 文本框高度
# 将图片添加到与文本框相同的位置
slide.shapes.add_picture(img_path, left, top, width=width, height=height)
# 保存演示文稿
prs.save(presentation_path)
# 指定图片文件路径
img_path = "D:\\desktop\\sha.jpg"
presentation_path = 'D:\\desktop\\测试.pptx'
if __name__ == '__main__':
insert_image_to_PPT(img_path,presentation_path)
python_往第一张幻灯片中插入图片
于 2024-08-01 17:00:37 首次发布