且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

复制带有图像的幻灯片python pptx

更新时间:2023-02-13 23:34:09

这是我开发的解决方法.我首先检查形状是否为图像,如果是,则将图像写入本地目录.然后,我使用保存的图像将照片添加到幻灯片中.最后,我删除了本地保存的图像.

Here is the workaround I developed. I first check if the shape is an image, and if it is, I write the image to a local directory. Then I add a picture to the slide using that saved image. Finally, I delete the locally saved image.

现在,此copy_slide函数适用于图像:

Now this copy_slide function works for images:

def copy_slide_from_external_prs(src, idx, newPrs):

    # specify the slide you want to copy the contents from
    src_slide = src.slides[idx]

    # Define the layout you want to use from your generated pptx
    SLD_LAYOUT = 5
    slide_layout = prs.slide_layouts[SLD_LAYOUT]

    # create now slide, to copy contents to
    curr_slide = newPrs.slides.add_slide(slide_layout)

    # create images dict
    imgDict = {}

    # now copy contents from external slide, but do not copy slide properties
    # e.g. slide layouts, etc., because these would produce errors, as diplicate
    # entries might be generated
    for shp in src_slide.shapes:
        if 'Picture' in shp.name:
            # save image
            with open(shp.name+'.jpg', 'wb') as f:
                f.write(shp.image.blob)

            # add image to dict
            imgDict[shp.name+'.jpg'] = [shp.left, shp.top, shp.width, shp.height]
        else:
            # create copy of elem
            el = shp.element
            newel = copy.deepcopy(el)

            # add elem to shape tree
            curr_slide.shapes._spTree.insert_element_before(newel, 'p:extLst')

    # add pictures
    for k, v in imgDict.items():
        curr_slide.shapes.add_picture(k, v[0], v[1], v[2], v[3])
        os.remove(k)