How to download images on a pdf file from django model

Submitted 3 years, 5 months ago
Ticket #290
Views 474
Language/Framework Django
Priority Medium
Status Closed

class Photo(models.Model):

image1=models.FileField(blank=True, default="",upload_to="media/images",null=True)

image2=models.FileField(blank=True, default="",upload_to="media/images",null=True)

def __str__(self):

return str(self.image1)

How can i download images from the both field on a pdf file in django rest framework?

Submitted on Nov 11, 20

do you want to download the image into PDF file? - Vengat 3 years, 5 months ago

yes,i want a pdf file of images,and images should be compresses,suppose if the images if of 2mb while uploading,it should compressed to reduce the file size. - ashutoshmishra333 3 years, 5 months ago

Please use this code editor when you submit the ticket in future. Its easy for everyone to grab the code and help you. - scott 3 years, 5 months ago
add a comment

1 Answer

Verified

Option 1

Looks like this packagesatisfy your needs,

django-easy-pdf

Check the above package

Option 2

We can use templatetag filter

Let say you have image url in your html like below,

<!DOCTYPE html>
<html>
<head>
    <title>{{ title|default:"" }}</title>
        <style type="text/css">
            body {
                background: white url("https://www.some.com/some.jpg") ;
            }
        </style>
</head>
<body>
</body>
</html>

Now if we need to add this image into PDF then you can use that package library to handle it.

Create the file as myapp/templatetags/pdf_filters.py:

from django import template
import urllib, cStringIO, base64

register = template.Library()

@register.filter
def get64(url):
    """
    Method returning base64 image data instead of URL
    """
    if url.startswith("http"):
        image = cStringIO.StringIO(urllib.urlopen(url).read())
        return 'data:image/jpg;base64,' + base64.b64encode(image.read())

    return url

Now we can load this filter

{% load pdf_filters %}
<img src="{{ ressource.image.url | get64 }}"/>

Submitted 3 years, 5 months ago

Can you update us the status on this ticket?

- Vengat 3 years, 5 months ago


Latest Blogs