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
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With