[SOLVED] In django how to generate a pdf file from django template maintaining the css style?


This Content is from Stack Overflow. Question asked by Manoj Kamble

I have created a pdf file with the Django template. In the template whatever CSS is applied is not showing in generated pdf.

Here is the code I have used :

from io import BytesIO
from xhtml2pdf import pisa
from django.template.loader import get_template
from django.http import HttpResponse
from django.shortcuts import render

def home(request):
    pdf = render_to_pdf("abc.html")
    return HttpResponse(pdf, content_type='application/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)
    if not pdf.err:
        return HttpResponse(result.getvalue(), content_type='application/pdf')
        return None


from django.core.files import ContentFile

If you already have the webp file, read the webp file, put it into the ContentFile() with a buffer (something like io.BytesIO). Then you can proceed to save the ContentFile() object to a model. Do not forget to update the model field, and save the model!



“django-webp-converter is a Django app which straightforwardly converts static images to WebP images, falling back to the original static image for unsupported browsers.”

It might have some save capabilities too.


The cause

You are also saving in the wrong order, the correct order to call the super().save() is at the end.

Edited, and tested solution:
from django.core.files import ContentFile
from io import BytesIO

def save(self, *args, **kwargs):
    #if not self.pk: #Assuming you don't want to do this literally every time an object is saved.
    img_io = BytesIO()
    im = Image.open(self.image).convert('RGB')
    im.save(img_io, format='WEBP')
    self.image = ContentFile(img_io.getvalue(), name)
    super(Banner, self).save(*args, **kwargs) #Not at start  anymore

Answered by nigel239

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 4.0.

people found this article helpful. What about you?