【python 第三方库】python-pptx

2024-01-25 00:00:00

目录:

python-pptx 模块介绍

python-pptx 提供 API 允许开发者以编程方式操作PPT的各个元素。

  • 创建与编辑:既可以创建全新的PPT文件,也可以加载并修改现有的PPT文件;
  • 内容管理:能够动态地添加、删除幻灯片,并在幻灯片中插入和修改文本、图片、表格、图表等多种元素;
  • 样式与布局控制:支持对 PPT 的布局、背景、主题以及文本的字体、颜色、大小等样式进行一定程度的自定义;
  • 批量自动化:特别适用于需要根据数据源(如数据库、Excel 表格)批量生成报告或个性化讲义的场景。

安装依赖包:

$ pip install python-pptx

导入依赖包,需要注意的是,安装的库名是 python-pptx,但导入时使用的是 pptx。

from pptx import Presentation

PPT 布局

PPT 有很多布局,prs.slide_layouts[索引号] 应用对应布局。

比如:

  • prs.slide_layouts[0] 是 Title Slide 布局,包含标题和副标题;
  • prs.slide_layouts[1] 是 Title and Content 布局,包含标题和内容;
from pptx import Presentation
from pptx.util import Inches

prs = Presentation()

for i, layout in enumerate(prs.slide_layouts): 
  print(f'布局索引 {i}: {layout.name}')

# 布局索引 0: Title Slide
# 布局索引 1: Title and Content
# 布局索引 2: Section Header
# 布局索引 3: Two Content
# 布局索引 4: Comparison
# 布局索引 5: Title Only
# 布局索引 6: Blank
# 布局索引 7: Content with Caption
# 布局索引 8: Picture with Caption
# 布局索引 9: Title and Vertical Text
# 布局索引 10: Vertical Title and Text

创建新 PPT 并添加标题页

from pptx import Presentation

# 1. 创建一个空的演示文稿对象
prs = Presentation()

# 2. 选择幻灯片布局(0 通常代表标题幻灯片布局)
slide_layout = prs.slide_layouts[0]
# 3. 使用选定的布局添加一张新幻灯片
slide = prs.slides.add_slide(slide_layout)

# 4. 获取标题和副标题占位符并填充内容
title = slide.shapes.title
subtitle = slide.placeholders[1]  # 索引 1 通常为副标题
title.text = "Python-pptx 演示"
subtitle.text = "这是我的第一个自动化PPT"

# 5. 保存文件
prs.save('test.pptx')

添加文本框与图片

from pptx import Presentation
from pptx.util import Inches  # 用于英寸单位换算

prs = Presentation()
# 选择一个带标题和内容的布局(例如索引 1)
slide_layout = prs.slide_layouts[1]
slide = prs.slides.add_slide(slide_layout)

# 设置幻灯片标题
slide.shapes.title.text = "图文示例页"

# 添加一个文本框
left = Inches(1.5)   # 距离左边距
top = Inches(2)      # 距离顶边距
width = Inches(4)    # 文本框宽度
height = Inches(1)   # 文本框高度
textbox = slide.shapes.add_textbox(left, top, width, height)
text_frame = textbox.text_frame
text_frame.text = "这是一个通过代码添加的文本框。"

# 添加一张图片
img_path = 'bg.png'  # 图片文件路径
left = Inches(3)
top = Inches(3.5)
# 添加图片,并指定宽度和高度
slide.shapes.add_picture(img_path, left, top, width=Inches(3), height=Inches(2))

prs.save('test.pptx')

添加表格

from pptx import Presentation
from pptx.util import Inches

prs = Presentation()
# 选择一个空白布局以便自由放置表格
slide_layout = prs.slide_layouts[6]
slide = prs.slides.add_slide(slide_layout)

# 定义表格维度(2行3列)
rows, cols = 2, 3
left = Inches(1)
top = Inches(1)
width = Inches(6)
height = Inches(1.5)

# 添加表格并获取表格对象
table = slide.shapes.add_table(rows, cols, left, top, width, height).table

# 填充表头和数据
table.cell(0, 0).text = '姓名'
table.cell(0, 1).text = '部门'
table.cell(0, 2).text = '销售额(万)'
table.cell(1, 0).text = '张三'
table.cell(1, 1).text = '销售部'
table.cell(1, 2).text = '150'

prs.save('test.pptx')

批量插入多张全屏图片

场景: 将 PDF 转换为 PPT,可以先通过 PyMuPDF 将 PDF 转换为 Image,再通过如下示例,将 Images 依次插入到 PPT 中。

from pathlib import Path
from pptx import Presentation
from pptx.util import Inches

def create_image_slideshow(image_folder, output_path):
    """
    创建图片幻灯片,每张图片占满一页
    
    Args:
        image_folder: 图片文件夹路径
        output_path: 输出PPT路径
    """
    # 获取所有图片文件
    image_files = [ x for x in Path(image_folder).iterdir() ]
    image_files = sorted(image_files)
    
    if not image_files:
        print("未找到图片文件")
        return
    
    # 创建演示文稿
    prs = Presentation()
    slide_width = prs.slide_width
    slide_height = prs.slide_height
    
    # 为每张图片创建一页幻灯片
    for img_path in image_files:
        # 索引 6 使用空白布局 
        blank_slide_layout = prs.slide_layouts[6]
        slide = prs.slides.add_slide(blank_slide_layout)
        
        # 插入全屏图片
        slide.shapes.add_picture(
            str(img_path),
            Inches(0),
            Inches(0),
            width=slide_width,
            height=slide_height
        )
    
    # 保存
    prs.save(output_path)
    print(f"已创建 {len(image_files)} 页幻灯片,保存到: {output_path}")

# 使用示例
create_image_slideshow("./images", "image_slideshow.pptx")

返回首页

本文总阅读量  次
皖ICP备17026209号-3
总访问量: 
总访客量: