django-easy-pdf
django-easy-pdf copied to clipboard
How can render images on pdf??
I have an issue, I can't render images on pdf.
Are you referencing the correct static path? Images are working for me
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!
''
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 }}">
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.