[Django]-Need help to render img in pdf from template using xhtml2pdf

5👍

If your are using xhtmltopdf you also need to provide a link_callback for being abble to display images:

def link_callback(uri, rel):
    """
    Convert HTML URIs to absolute system paths so xhtml2pdf can access those
    resources
    """
    # use short variable names
    sUrl = settings.STATIC_URL     # Typically /static/
    #static Root
    sRoot = settings.STATIC_ROOT    # Typically /home/userX/project_static/
    mUrl = settings.MEDIA_URL       # Typically /static/media/
    mRoot = settings.MEDIA_ROOT     # Typically /home/userX/project_static/media/

    # convert URIs to absolute system paths
    if uri.startswith(mUrl):
        path = os.path.join(mRoot, uri.replace(mUrl, ""))
    elif uri.startswith(sUrl):
        path = os.path.join(sRoot, uri.replace(sUrl, ""))
    else:
        return uri  # handle absolute uri (ie: http://some.tld/foo.png)

    # make sure that file exists
    if not os.path.isfile(path):
            raise Exception(
                'media URI must start with %s or %s' % (sUrl, mUrl)
            )
    return path

AND don’t forget to add the link callback in your render_to_pdf:

def render_to_pdf(template_src, context_dict={}):
    template = get_template(template_src)
    html = template.render(context_dict) 
    result = BytesIO()
    pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result, link_callback=link_callback)
    if not pdf.err:
        return HttpResponse(result.getvalue(), content_type='application/pdf') 
    return None

You also need to specify the height and widht inside the img tag like:

<img src="{% static 'polls/images/image.png'%}" alt="image" width="200" height="150" />

In settings.py don’t forget to define your STATIC_URL AND STATIC_ROOT, MEDIA_URL AND MEDIA_ROOT

Like this for exemple:

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'project_name/static/')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'project_name/media/')

Then don’t forget to run python manage.py collectstatic in the terminal

More info here: https://xhtml2pdf.readthedocs.io/en/latest/usage.html#using-xhtml2pdf-in-django

0👍

in views.py

        from pathlib import Path

        BASE_DIR = Path(__file__).resolve().parent.parent
        path = os.path.join( BASE_DIR , 'static') 
        # send 'path' first in context
        context = {'path':path , 'any':any }

in template

     <img src="{{path}}\img\pic.png"  > 

Leave a comment