0

I'm attempting to render a PDF and populate the template with specific data from the object that is being viewed.

I'm using xhtml12pdf / pisa. I've successfully rendered a generic (unpopulated) PDF, however when I add logic to populate a specific object's data, my context is being returned however the pdf is no longer being rendered.

views.py

class GeneratePdf(DetailView):

     model = Request
     template_name='request_response/response.html'

     def get(self, request, *args, **kwargs):

          context = super(GeneratePdf,self).get(request,*args,**kwargs)
          return context

          pdf = render_to_pdf('request_response/response.html',context)

          if pdf:
             response = HttpResponse(pdf,content_type='application/pdf')
             filename = "PrivacyRequest_%s.pdf" %("1234")
             content = "inline; filename='%s'" %(filename)
             response['Content-Disposition'] = content
             return response

          return HttpResponse("Not Found")
Mahrus Khomaini
  • 660
  • 1
  • 6
  • 14

1 Answers1

0

Please show your render_to_pdf function. I assume that it like:

from io import BytesIO
from xhtml2pdf import pisa
from django.template.loader import get_template

def render_to_pdf(template, context):
   template = get_template(template)
   html  = template.render(context)
   result = BytesIO()
   pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result)
   if not pdf.err:
       return HttpResponse(result.getvalue(), content_type='application/pdf')
   return None

You can remove context = super(GeneratePdf,self).get(request,*args,**kwargs) and return context. As shown in the error message, context must be a dict. So change it to dictionary, like:

def get(self, request, *args, **kwargs):

   context = {
      'example1': 'This is example 1',
      'some_foo': 'So many of foo function'
   }
   pdf = render_to_pdf('request_response/response.html',context)

   if pdf:
      response = HttpResponse(pdf,content_type='application/pdf')
      filename = "PrivacyRequest_%s.pdf" %("1234")
      content = "inline; filename='%s'" %(filename)
      response['Content-Disposition'] = content
      return response

   return HttpResponse("Not Found")

FYI: This is another similiar question like yours and it has accepted answer.

Mahrus Khomaini
  • 660
  • 1
  • 6
  • 14