2024-07-07|閱讀時間 ‧ 約 25 分鐘

python pptx note [kurt]


    from win32com.client import Dispatch

    path = "D:\PROGRAMMING\PythonCode\pypptx\image1.png"

    # 启动PowerPoint应用程序
    ppt = Dispatch('PowerPoint.Application')
    #ppt.DisplayAlerts = False

    # 新建一个演示文稿
    #slide = ppt.Presentations.Add()
    slide = ppt.Presentations.Open('D:\PROGRAMMING\PythonCode\pypptx\example.pptx')
    # 添加一张幻灯片并添加标题和内容文本框
    slide.Slides.Add(1, 1)
    slide.Slides(1).Shapes(1).TextFrame.TextRange.Text = 'Hello, World!'
    slide.Slides(1).Shapes(2).TextFrame.TextRange.Text = 'This is a PowerPoint presentation.'
    slide.Slides.Add(2, 1)
    slide.Slides(2).Shapes(1).TextFrame.TextRange.Text = 'hrerted!'
    slide.Slides.Add(3, 1)
    slide.Slides(3).Shapes.AddPicture(FileName=path, LinkToFile=False, SaveWithDocument=True, Left=100, Top=100, Width=-1, Height=-1)
    # 保存并关闭演示文稿
    slide.Save()
    #save_as = slide.SaveAs('D:\PROGRAMMING\PythonCode\pypptx\example.pptx')
    slide.Close()
    # 退出PowerPoint应用程序
    ppt.Quit()


    from pptx import Presentationfrom pptx.util import Inches

    # 打開已存在的 PPTX 文件
    pptx_path = "D:\PROGRAMMING\PythonCode\pypptx\example.pptx"
    presentation = Presentation(pptx_path)

    # 插入圖片到第一個幻燈片
    slide = presentation.slides[-1]

    # 圖片路徑
    image_path = "D:\PROGRAMMING\PythonCode\pypptx\image1.png"

    # 插入圖片
    left = Inches(1)  # 水平位置
    top = Inches(1)  # 垂直位置
    width = Inches(5) # 圖片寬度
    height = Inches(3) # 圖片高度

    slide.shapes.add_picture(image_path, left, top, width, height)

    # 保存修改後的 PPTX 文件
    output_path = "D:\PROGRAMMING\PythonCode\pypptx\example.pptx"
    presentation.save(output_path)

    print("圖片已插入並保存簡報。")



    分享至
    成為作者繼續創作的動力吧!
    © 2024 vocus All rights reserved.