How do I use reportlab's drawImage with an image url?

ysth picture ysth · Sep 30, 2014 · Viewed 18.5k times · Source

When I try the following:

from reportlab.lib.pagesizes import letter
from reportlab.pdfgen.canvas import Canvas
import urllib
import StringIO
import PIL.Image

image_file = urllib.urlopen('https://www.google.com/images/srpr/logo11w.png')
image_string = StringIO.StringIO(image_file.read())
logo = PIL.Image.open(image_string)

canvas = Canvas('output.pdf', pagesize=letter)
canvas.drawImage(logo, 10, 10)
canvas.showPage()
canvas.save()

I get this error:

Traceback (most recent call last):
  File "imagefromurl.py", line 12, in <module>
    canvas.drawImage(logo, 10, 10)
  File "/usr/lib/python2.7/dist-packages/reportlab/pdfgen/canvas.py", line 857, in drawImage
    imgObj = pdfdoc.PDFImageXObject(name, image, mask=mask)
  File "/usr/lib/python2.7/dist-packages/reportlab/pdfbase/pdfdoc.py", line 2090, in __init__
    ext = string.lower(os.path.splitext(source)[1])
  File "/usr/lib/python2.7/posixpath.py", line 96, in splitext
    return genericpath._splitext(p, sep, altsep, extsep)
  File "/usr/lib/python2.7/genericpath.py", line 91, in _splitext
    sepIndex = p.rfind(sep)
  File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 515, in __getattr__
    raise AttributeError(name)

Reportlab is version 2.5.

Answer

ysth picture ysth · Sep 30, 2014

I was doing it the hard way. This works (also added the necessary mask to avoid transparent becoming black):

from reportlab.lib.pagesizes import letter
from reportlab.pdfgen.canvas import Canvas
from reportlab.lib.utils import ImageReader

logo = ImageReader('https://www.google.com/images/srpr/logo11w.png')

canvas = Canvas('output.pdf', pagesize=letter)
canvas.drawImage(logo, 10, 10, mask='auto')
canvas.showPage()
canvas.save()

Though the hard way would have allowed me to detect a failure to fetch the image url and handle it (e.g. substituting a local image), and this doesn't.