【python_拷贝PPT中的一张幻灯片到另一个PPT中】

python_拷贝PPT中的一张幻灯片到另一个PPT中

可以指定位置

from pptx import Presentation
import copy
from contextlib import redirect_stderr
import os


#pres_loc1_index是第一个PPT对应的索引值,如果是“all”,则表示所有
#pres_loc2_index是第二个PPT对应的索引值,如果是“all”,则表示所有
#目标是将第二个PPT中的指定幻灯片,拷贝到第一个PPT中的指定位置,结果保存到新的PPT中。
#不能复制图片,图片的话需要用单独的插入图片的函数
#一次只能从第二个PPT中复制一张幻灯片过去,因为多了会被覆盖,也就是如果pres_loc1_index不为“all”的情况下,pres_loc2_index不能为“all”


def remove_title_and_subtitle(slide):
    # 遍历幻灯片上的形状(即元素)
    for shape in slide.shapes:
        if shape.has_text_frame:
            # 如果形状是标题或副标题,则删除它
            if "title" in shape.name.lower():
                slide.shapes._spTree.remove(shape.element)
            elif "subtitle" in shape.name.lower():
                slide.shapes._spTree.remove(shape.element)

def clear_slide(slide):

    # 清除形状
    for shape in slide.shapes:
        slide.shapes._spTree.remove(shape._element)

    # 清除占位符
    for placeholder in slide.placeholders:
        slide.placeholders._spTree.remove(placeholder._element)

def merge_powerpoint_ppts(pres_loc1, pres_loc2, output_loc,pres_loc1_index,pres_loc2_index):
    # Load the first presentation
    pres1 = Presentation(pres_loc1)
    # Load the second presentation
    pres2 = Presentation(pres_loc2)

    def copy_slide(slide):
        if pres_loc1_index=="all":
            slide_layout = slide.slide_layout
            new_slide = pres1.slides.add_slide(slide_layout)
        else:
            clear_slide(pres1.slides[pres_loc1_index])
            new_slide=pres1.slides[pres_loc1_index]
        
        for shape in slide.shapes:
            # Create a deep copy of the shape element
            new_element = copy.deepcopy(shape.element)
            # Insert the copied element into the new slide
            new_slide.shapes._spTree.append(new_element)

        # 移除标题和副标题
        remove_title_and_subtitle(new_slide)

    # Loop through each slide in the second presentation
    if pres_loc2_index=="all":
        for slide in pres2.slides:
            copy_slide(slide)
    else:
        slide=pres2.slides[pres_loc2_index]
        copy_slide(slide)

    # Save the merged presentation
    with open(os.devnull, 'w') as devnull:
        with redirect_stderr(devnull):
            pres1.save(output_loc)  # Use the provided output location without adding extra characters

# Example usage:
merge_powerpoint_ppts('D:\\desktop\\测试.pptx', 'D:\\desktop\\测试 - 副本.pptx', 'D:\\desktop\\测试 - 副本1.pptx',"all",1)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值