pythondocx:从web添加图片

2024-09-21 00:50:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用pythondocx和django来生成word文档。在

有没有一种方法可以使用add_picture从web而不是从文件系统添加图像?在

在word中,当我选择添加图片时,我可以只给出URL。 我试着同样的方式写下:

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'


Tags: djangoimagecomaddhttpxpmicrosoftword
3条回答

如果使用docxtemplater(命令行界面)

您可以创建自己的模板,并使用URL嵌入图像。在

参见:https://github.com/edi9999/docxtemplater

docxtemplater command line interface

docxtemplater image replacing

下面是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')

不是很优雅,但我根据here中的问题找到了一个解决方案

我的代码现在是这样的:

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))

这个很好用。在

相关问题 更多 >

    热门问题