django-easy-pdf icon indicating copy to clipboard operation
django-easy-pdf copied to clipboard

How can render images on pdf??

Open brayan15 opened this issue 7 years ago • 4 comments

I have an issue, I can't render images on pdf.

brayan15 avatar Oct 31 '17 01:10 brayan15

Are you referencing the correct static path? Images are working for me

nickatnight avatar Jan 10 '18 20:01 nickatnight

Same issue here. No images in pdf either via path on my fs or url. Image is not rendered, throwing exception instead:

easy_pdf.exceptions.UnsupportedMediaPathException: media urls must start with or /static/ Need a valid file name! ''

kaliif avatar Apr 24 '18 16:04 kaliif

Previously, I have a same problem. I suggest you to add this templatetag below:

import os
import base64
import requests

from django import template

register = template.Library()


@register.filter
def read_image_as_base64(image_url):
    """
    :param `image_url` for the complete path of image.
    :return string base64 of image

    >>> from yourapp.templatetags.image_tags import *
    >>>
    >>> read_image_as_base64('http://127.0.0.1:8000/static/images/watermark.png')
    'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgxxxxxxx'
    >>>
    """
    if not image_url:
        return image_url

    try:
        response = requests.get(image_url)
        if response.status_code == 200:
            image_data = response.content
            image_format = os.path.splitext(image_url)[-1].replace('.', '').lower()
            encoded_string = base64.b64encode(image_data).decode('utf-8')

            if image_format in ['jpg', 'jpeg', 'png', 'gif']:
                return 'data:image/%s;base64,%s' % (image_format, encoded_string)

    except Exception as error:
        pass

    return image_url

Usage example:

<img src="{{ profile.photo.url|read_image_as_base64 }}">

agusmakmun avatar Jan 29 '20 03:01 agusmakmun

I'm not sure if it should, but at least with the new django easy pdf version (https://github.com/olksndrdevhub/django-easy-pdf3) this isn't working anymore.

gdvalderrama avatar Mar 17 '22 11:03 gdvalderrama