Why does saving a presentation to a file-like object produce a blank presentation?

ε祈祈猫儿з 提交于 2019-12-10 14:23:05

问题


As a response to this answer to a previous question of mine, I wrote the following short program to try and reproduce the problem.

from pptx import Presentation
from io import BytesIO

p = Presentation()
slide = p.slides.add_slide(p.slide_layouts[0])
slide.shapes[0].text = 'asdf'

p.save('test.pptx')

out = BytesIO()
p.save(out)

out_file = open('bytes_test.pptx', 'wb', buffering=0)
out_file.write(out.read())
out_file.close()

This produced two pptx files.

The first, test.pptx, contained a single slide with the "Title Slide" layout and containing the string "asdf". The file size was 28 KB.

The second, bytes_test.pptx, when opened in PowerPoint, showed only a large grey box that said "Click to add first slide". The file size was 0.

Running on Windows 10 with Anaconda Python 3.6.1 and python-pptx 0.6.6

Why does this happen?


回答1:


Well, a couple things I can think of, this might take some back-and-forth.

First, I would try using out.getvalue() instead of out.read(). That's how I've always done it and its documented behavior is to get the entire contents of the stream.

If that doesn't work, I would add out.flush() and out.seek(0) before the out.read() call. BytesIO is a buffered output stream, and its possible some buffered data isn't getting written to the stream before the read() call. Also, I expect read() works from the current cursor position, which the seek(0) call would reset to the beginning of the file.

Let us know how you go with that and we'll take it from there.



来源:https://stackoverflow.com/questions/46981529/why-does-saving-a-presentation-to-a-file-like-object-produce-a-blank-presentatio

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!