我的最终目标是改变演示文稿的主题。为此,我创建了一个源模板和一个新模板(具有正确的主题)。我迭代源模板中的每张幻灯片,然后使用以下代码将包含源内容的新幻灯片添加到新模板中https://stackoverflow.com/a/56074651/3206926 https://stackoverflow.com/a/56074651/3206926。如果有更好的方法来做到这一点,我很想听听。
这对于文本和文本框非常有用,但是测试图像无法在新的 powerpoint 中显示(如下图所示):
Code
def copy_slide_from_external_prs(self, 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
slide_layout = newPrs.slide_layouts[2]
# create now slide, to copy contents to
curr_slide = newPrs.slides.add_slide(slide_layout)
# remove placeholders
for p in [s.element for s in curr_slide.shapes if 'Text Placeholder' in s.name or 'Title' in s.name]:
p.getparent().remove(p)
# 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:
el = shp.element
newel = copy.deepcopy(el)
curr_slide.shapes._spTree.insert_element_before(newel, 'p:extLst')
return newPrs
我尝试了许多不同的解决方案,并尝试使用创建新图片image.blob
源图像中的属性。然而,该图像没有元素。我是否需要将 blob 转换为 PNG 并保存,然后使用保存的 PNG 创建新图像?
必须有更好的方法来做到这一点。再说一次,我只是想改变主题。
这是我开发的解决方法。我首先检查形状是否是图像,如果是,我将图像写入本地目录。然后我使用保存的图像将图片添加到幻灯片中。最后,我删除本地保存的图像。
现在这个 copy_slide 函数适用于图像:
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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)