Output image to pdf with xhtml2pdf

2019-04-13 01:52发布

问题:

I followed this post : django - pisa : adding images to PDF output and using fetch_resources. The PDF file can be generated normally except the image is missing.

This is my code:

def fetch_resources(uri, rel):
    path = os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, ""))
    return path

def render_to_pdf(template_src, context_dict, filename):
    template = get_template(template_src)
    context = Context(context_dict)
    html  = template.render(context)
    result = StringIO.StringIO()

    pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), 
                            dest=result, 
                            link_callback=fetch_resources )
    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))

This is my template:

<p><img src="{{ copyright.digital_signature.url }}"></p>

I'm sure that "copyright.digital_signature.url" is correct because it can show an image on browser properly. And that means PIL had been installed?

Can anybody help me what the problem is? Thank you very much!