image - 复制带有图像的幻灯片 python pptx
问题描述
我的最终目标是更改演示文稿的主题。为此,我创建了一个源模板和新模板(具有正确的主题)。我遍历源模板中的每张幻灯片,然后使用以下代码向新模板添加一张新幻灯片,其中包含源的内容 -源代码。如果有更好的方法来做到这一点,我很想听听。
这适用于文本和文本框,但是测试图像无法在新的 powerpoint 中显示(如下图所示):
代码
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)
推荐阅读
- typescript - 是否可以在 VSCode(或其他地方)中显示打字稿类型/接口的完整计算类型
- javascript - 使用 Sinon 对单个导出函数进行存根
- java - 确定季度边界日期的更好方法
- javascript - 将数据表导出按钮移动到表格底部
- java - Spring - 将传入日期视为 UTC
- python - 如何在openpyxl中设置或更改表格的默认高度
- google-apps-script - 找不到 getMonth 函数
- reactjs - 使用内容 cms 时定义数组索引时无法显示数据
- java - Docker 没有捕获环境变量
- javascript - 使用相关文档 - 人口和模型