djangopdfimagepdf-generationpisa

django - pisa : adding images to PDF output


I'm using a standard example from the web (http://www.20seven.org/journal/2008/11/pdf-generation-with-pisa-in-django.html) to convert a django view / template into a PDF.

Is there an "easy" way to include images (either from a url or a reference on the server) in the template so they will show on the PDF?


Solution

  • I got the images working. the code is as follows:

    from django.http import HttpResponse
    from django.template.loader import render_to_string
    from django.template import RequestContext
    from django.conf import settings
    import ho.pisa as pisa
    import cStringIO as StringIO
    import cgi
    import os
    
    def dm_monthly(request, year, month):
        html  = render_to_string('reports/dmmonthly.html', { 'pagesize' : 'A4', }, context_instance=RequestContext(request))
        result = StringIO.StringIO()
        pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), dest=result, link_callback=fetch_resources )
        if not pdf.err:
            return HttpResponse(result.getvalue(), mimetype='application/pdf')
        return HttpResponse('Gremlins ate your pdf! %s' % cgi.escape(html))
    
    def fetch_resources(uri, rel):
        path = os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, ""))
    
        return path
    

    This was taken liberally from http://groups.google.com/group/xhtml2pdf/browse_thread/thread/4cf4e5e0f4c99f55