Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can render images on pdf?? #53

Open
brayan15 opened this issue Oct 31, 2017 · 4 comments
Open

How can render images on pdf?? #53

brayan15 opened this issue Oct 31, 2017 · 4 comments

Comments

@brayan15
Copy link

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

@nickatnight
Copy link

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

@kaliif
Copy link

kaliif commented Apr 24, 2018

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!
''

@agusmakmun
Copy link

agusmakmun commented Jan 29, 2020

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 }}">

@gdvalderrama
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants