Why does saving a presentation to a file-like obje

2019-07-14 01:47发布

问题:

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.



标签: python-pptx