Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pdf in django-rest-framework

I am trying to make pdf in Django

 from xhtml2pdf import pisa
 from django.http import HttpResponse
 from django.template.loader import get_template
 from django.template import Context 
 from rest_framework.views import APIView
 from .models import Brand

 class ABCView(APIView):
   def post(self, request,format=None):
    report = Brand.objects.all()
    template_path = 'profile_brand_report.html'

    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="Report.pdf"'

    context = {'report': report}
    template = get_template(template_path)
    html = template.render(Context(context))
    print (html)

    pisaStatus = pisa.CreatePDF(html, dest=response)

    return response

but I am getting an unexpected error I don't know what I am doing wrong, I am getting this error

argument of type 'Context' is not iterable

or is there any other way to do it .thanks for help in advance

like image 962
Vivek Singh Avatar asked Aug 17 '26 12:08

Vivek Singh


1 Answers

We don't need to use a class based view for it. For simplicity we can use a function based view. Change your code as below.

from django.template.loader import render_to_string

def generate_pdf(request):
    report = Brand.objects.all()
    template_path = 'profile_brand_report.html'

    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="Report.pdf"'

    html = render_to_string(template_path, {'report': report})
    print (html)

    pisaStatus = pisa.CreatePDF(html, dest=response)

    return response 

We can also use wkhtmltopdf to generate PDF's in django.
Read: https://learnbatta.com/blog/django-html-to-pdf-using-pdfkit-and-wkhtmltopdf-5/

like image 99
anjaneyulubatta505 Avatar answered Aug 19 '26 03:08

anjaneyulubatta505