python-docx:从网络添加图片
我正在用python-docx和django来生成Word文档。
请问有没有办法用add_picture
从网上添加图片,而不是从本地文件系统添加呢?
在Word里,当我选择添加图片时,我只需要提供一个网址就可以了。我试着这样做,写了:
document.add_picture("http://icdn4.digitaltrends.com/image/microsoft_xp_bliss_desktop_image-650x0.jpg")
结果出现了错误:
IOError: [Errno 22] invalid mode ('rb') or filename: 'http://icdn4.digitaltrends.com/image/microsoft_xp_bliss_desktop_image-650x0.jpg'
3 个回答
1
下面是一个适用于Python 3的新实现:
from io import BytesIO
import requests
from docx import Document
from docx.shared import Inches
response = requests.get(your_image_url) # no need to add stream=True
# Access the response body as bytes
# then convert it to in-memory binary stream using `BytesIO`
binary_img = BytesIO(response.content)
document = Document()
# `add_picture` supports image path or stream, we use stream
document.add_picture(binary_img, width=Inches(2))
document.save('demo.docx')
1
如果你使用 docxtemplater
这个命令行工具,
你可以自己创建模板,并且可以通过网址来插入图片。
可以查看这个链接了解更多信息: https://github.com/edi9999/docxtemplater
还有这个链接可以了解 如何替换图片
4
虽然这个方法不是特别优雅,但我找到了解决办法,灵感来自于这个问题
我的代码现在是这样的:
import urllib2, StringIO
image_from_url = urllib2.urlopen(url_value)
io_url = StringIO.StringIO()
io_url.write(image_from_url.read())
io_url.seek(0)
try:
document.add_picture(io_url ,width=Px(150))
这样运行得很好。