django - pisa : adding images to PDF output

2020-01-25 06:04发布

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?

7条回答
Viruses.
2楼-- · 2020-01-25 06:34

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) 
查看更多
登录 后发表回答