OritK
OritK

Reputation: 544

python-docx: add picture from the web

I am using python-docx with django to generate word documents.

Is there a way to use add_picture to add an image from the web rather then from the file system?

In word, when I select to add a picture, I can just give the URL. I tried to simply so the same and write:

document.add_picture("http://icdn4.digitaltrends.com/image/microsoft_xp_bliss_desktop_image-650x0.jpg")

and got error:

IOError: [Errno 22] invalid mode ('rb') or filename: 'http://icdn4.digitaltrends.com/image/microsoft_xp_bliss_desktop_image-650x0.jpg'

Upvotes: 1

Views: 5262

Answers (3)

Max
Max

Reputation: 1805

Below is a fresh implementation for 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')

Upvotes: 1

edi9999
edi9999

Reputation: 20554

If you use docxtemplater (command line interface),

you can create your own templates and embed images with a URL.

See : https://github.com/edi9999/docxtemplater

docxtemplater command line interface

docxtemplater image replacing

Upvotes: 1

OritK
OritK

Reputation: 544

Not very elegant, but i found a solution, based on the question in here

my code now looks like that:

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

and this works fine.

Upvotes: 4

Related Questions