views:

12

answers:

1

Related to: http://stackoverflow.com/questions/2179958/django-pisa-adding-images-to-pdf-output

I've got a site that uses the Google Chart API to display a bunch of reports to the user, and I'm trying to implement a PDF version. I'm using the link_callback parameter in pisa.pisaDocument which works great for local media (css/images), but I'm wondering if it would work with remote images (using a google charts URL).

From the documentation on the pisa website, they imply this is possible, but they don't show how:

Normaly pisa expects these files to be found on the local drive. They may also be referenced relative to the original document. But the programmer might want to load form different kind of sources like the Internet via HTTP requests or from a database or anything else.

This is in a Django project, but that's pretty irrelevant. Here's what I'm using for rendering:

html = render_to_string('reporting/pdf.html', keys,
                        context_instance=RequestContext(request))
result = StringIO.StringIO()
pdf = pisa.pisaDocument(
        StringIO.StringIO(html.encode('ascii', 'xmlcharrefreplace')),
        result, link_callback=link_callback)
return HttpResponse(result.getvalue(), mimetype='application/pdf')

I tried having the link_callback return a urllib request object, but it does not seem to work:

def link_callback(uri, rel):
    if uri.find('chxt') != -1:
        url = "%s?%s" % (settings.GOOGLE_CHART_URL, uri)
        return urllib2.urlopen(url)
    return os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, ""))

The PDF it generates comes out perfectly except that the google charts images are not there.

A: 

Well this was a whole lot easier than I expected. In your link_callback method, if the uri is a remote image, simply return that value.

def link_callback(uri, rel):
    if uri.find('chart.apis.google.com') != -1:
        return uri
    return os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, ""))

The browser is a lot less picky about the image URL, so make sure the uri is properly quoted for pisa. I had space characters in mine which is why it was failing at first (replacing w/ '+' fixed it).

Dan Breen