Search code examples
pythondjangoxhtml2pdf

django xhtml2pdf not getting image


I am trying to render html to pdf, it really works great ! only there is an issue and that is the template getting image:

I am using python xhtml2pdf library for pdf render

this is my method for render pdf:

def render_pdf(template_src, context_dict):
    template = get_template(template_src)
    html  = template.render(context_dict)
    result = BytesIO()
    pdf = pisa.pisaDocument(BytesIO(html.encode("utf-8")), result)
    if not pdf.err:
        return HttpResponse(result.getvalue(), content_type='application/pdf')
    return HttpResponse('Unable to process the request, We had some errors<pre>%s</pre>' % escape(html))

and this is my views.py below:

def test_view(request):
    context = {
        'test': 'a test string'
    }
    return render_pdf('test.html', context)

and this my test.html

{% load static %}
<p>hello test </p>
 <img src="{% static 'ok.jpg' %}">

It gets image if i render with django default render method But the image not getting when i render for pdf.

I heard of this solution with link_callback method with this documatin: https://xhtml2pdf.readthedocs.io/en/latest/usage.html

I am not getting where to include this or how can i achive this.

Can anyone help me in this case?


Solution

  • I suggest modifying your html template, and use the absolute / relative path (directory path in your hard drive) of the image file instead of using {% static %} tag. static tag is only good for rendering the HTMl, but pisa cant read the image from that.

    I have this code from a project that generates a PDF from html, and my images are done like this:

    <img src="{{ STATIC_ROOT }}/report/logo.png" >
    

    where STATIC_ROOT is a variable passed from render context.