不需要倒带寻找io.Bytes() 对象来包含带有 docx add_picture

问题描述

我想先使用 PIL 旋转图像,然后再使用 docx 将其包含在 Word 文档中。我从一个空文档开始。为了避免将旋转后的图像保存到磁盘,我使用了流。在其他应用程序中,您需要在使用内容之前将流“重置”到起始位置。但是,我发现在使用 run.add_picture() 时这不是必需的,我不明白。为什么在添加图片之前不需要倒带?

from docx import Document
from docx.shared import Inches
from io import BytesIO
from PIL import Image

document = Document('Test.docx')
temporary_storage = BytesIO()

print('Created the stream')
print('Pointer is at position: ' + str(temporary_storage.tell()))


paragraph = document.add_paragraph()
run = paragraph.add_run()
picture = Image.open('cat.png')

picture.rotate(90,expand=True).save(temporary_storage,format="png")
print('Saved picture to the stream')
print('Pointer is at position: ' + str(temporary_storage.tell()))

temporary_storage.seek(500)
print('Set pointer to  position: 500')
print('Pointer is at position: ' + str(temporary_storage.tell()))

run.add_picture(temporary_storage,width=Inches(1.65),height=Inches(2.9))
document.save('Test_with_picture.docx')

输出为:

Created the stream
Pointer is at position: 0
Saved picture to the stream
Pointer is at position: 30828
Set pointer to  position: 500
Pointer is at position: 500

Process finished with exit code 0

它工作正常,图片很好地添加到文档中,无需将指针设置回零或任何其他值。为什么不需要设置回起点?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)