django - pisa : adding images to PDF output
Asked Answered
M

7

35

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?

Madisonmadlen answered 1/2, 2010 at 20:48 Comment(1)
Link dead - this is it: 20seven.org/journal/2008/11/11/…Discontent
M
36

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

Madisonmadlen answered 1/2, 2010 at 20:48 Comment(2)
fyi for non-Django users, MEDIA_ROOT is the directory where the html document you're converting is physically located and MEDIA_URL is the http-friendly version of that location (e.g. for a local html file: MEDIA_URL = 'file:///' + MEDIA_ROOT). Otherwise this is a sound general solution!Bartko
What if I am using S3?Ulema
E
5

Following line of code in HTML and Django version=2.0 works for me.

<img src="{{company.logo.path}}" height="100px">
Eppie answered 19/10, 2018 at 5:57 Comment(1)
I was doing <img src="{{ company.logo.url }}" height="100px"> make sure to change it to .path.Bromoform
K
2

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" />
Klee answered 14/9, 2010 at 10:30 Comment(0)
M
2
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
Mantoman answered 28/9, 2012 at 17:25 Comment(0)
O
2

All the above code did not worked for me. In the end i got it working by putting the get_full_path procedure. So the final code looks like this

def render_to_pdf( template_src, context_dict):
    now = datetime.now()
    filename = now.strftime('%Y-%m-%d') + '.pdf'
    template = get_template(template_src)
    context = Context(context_dict)
    html  = template.render(context)
    result = StringIO.StringIO()

    pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")),result, path=path)

    if not pdf.err:
      response = HttpResponse(result.getvalue(), mimetype='application/pdf')
      response['Content-Disposition'] = 'attachment; filename="'+filename+'"'
      return response
   return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))

def get_full_path_x(request):
    full_path = ('http', ('', 's')[request.is_secure()], '://',
    request.META['HTTP_HOST'], request.path)
    return ''.join(full_path) 
Officer answered 15/4, 2013 at 16:31 Comment(0)
H
1

You can convert the image to base64 too.

http://www.motobit.com/util/base64-decoder-encoder.asp

Converting to base64 you will never have problems with image links.

Hygrograph answered 5/3, 2014 at 16:12 Comment(1)
Yes, images can be converted to base64. Please add anexample on how to put them in the pdf.Zeist
D
0

You could always add the images afterwards with IText/ISharp.

Drumbeat answered 2/2, 2010 at 20:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.