django - pisa : adding images to PDF output
I got the images working. the code is as follows:
from django.http import HttpResponsefrom django.template.loader import render_to_stringfrom django.template import RequestContextfrom django.conf import settingsimport ho.pisa as pisaimport cStringIO as StringIOimport cgiimport osdef 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
I could not get images to appear despite trying every solution I could find on google. But this fudge worked for me as the command line version of pisa displays images ok:
from tempfile import mkstemp # write html to a temporary file # can used NamedTemporaryFile if using python 2.6+ fid, fname = mkstemp(dir='/tmp') f = open(fname, 'w+b') f.write(html) f.close() # now create pdf from the html cmd = 'xhtml2pdf "%s"' % fname os.system(cmd) os.unlink(fname) # get the content of the pdf filename = fname+'.pdf' pdf = open(filename, 'r') content = pdf.read() pdf.close() os.unlink(pdf.name) # return content response = HttpResponse(content, mimetype='application/pdf') response['Content-Disposition'] = 'attachment; filename=draft.pdf'
This worked where the images had either a url or the full path name, eg.
<img src="/home/django/project/site_media/css/output/images/logo.jpg" /><img src="http://www.mysite.com/css/output/images/logo.jpg" />
def render_to_pdf( template_src, context_dict): template = get_template(template_src) context = Context(context_dict) html = template.render(context) result = StringIO.StringIO() if page has an image.something: pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), dest=result, link_callback=fetch_resources) else no image.something : pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")),result) if not pdf.err: return HttpResponse(result.getvalue(), mimetype='examination_report/pdf') return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))def fetch_resources(uri, rel): if os.sep == '\\': # deal with windows and wrong slashes uri2 = os.sep.join(uri.split('/')) else:# else, just add the untouched path. uri2 = uri path = '%s%s' % (settings.SITE_ROOT, uri2) return path