[reportlab-users] Drawing a remote Image from a URL without writing to disk

Damian Moore damian at epixstudios.co.uk
Wed May 30 10:45:01 EDT 2012


Hi Robin,

> ..try creating a PIL Image from your data source and try assigning

> that to the shapes.Image instance path attribute.

>

> That will work for renderPDF, but perhaps you want to use this for

> another renderer.


Thanks for the insight. Unfortunately it seems a PIL Image doesn't work
either. I get 'TypeError: coercing to Unicode: need string or buffer,
instance found.'. I've cut it down to the relevant code. Any ideas?


from cStringIO import StringIO
import urllib2 as urllib
from reportlab.pdfgen import canvas
from reportlab.graphics import renderPDF
from reportlab.lib.pagesizes import A4
from reportlab.platypus import Frame
from reportlab.graphics.shapes import Drawing, Image
from PIL import Image as PILImage

def map_image(lat, lon):
url =
'http://maps.googleapis.com/maps/api/staticmap?center=%s,%s&zoom=16&size=400x300&maptype=roadmap&markers=%s,%s&sensor=false'
% (lat, lon, lat, lon)
img_file = urllib.urlopen(url)
im = StringIO(img_file.read())
return PILImage.open(im)

c = canvas.Canvas('map.pdf', pagesize=A4)

story = []
drawing = Drawing(400, 300)
drawing.add(Image(0, 0, 200, 150, map_image(40.711614, -74.012318)))
story.append(drawing)

margin = 72
f = Frame(margin, margin, A4[0]-(margin*2), A4[1]-(margin*2))
f.addFromList(story, c)

c.showPage()
c.save()



More information about the reportlab-users mailing list