[Fixed]-Generating PDFs with Django 1.9

1👍

I think you need to:

  1. render html
  2. convert it to pdf
  3. set pdf content to response body
  4. return response

Now your code renders template as html, adds ‘application/pdf’ content type to headers and returns normal html page.

You need something like PDFTemplateView. There are ready to use packages django-easy-pdf or django-wkhtmltopdf.

UPD:

  def some_view(request):
      response = HttpResponse(content_type='application/pdf')
      response['Content-Disposition'] = 'attachment; filename="example.pdf"'
      p = canvas.Canvas(response)

      // simple but visual result is not pretty at all
      for i, obj in enumerate(People.objects.all()):
          p.drawString(100, 50*(i+1), str(obj))

      p.showPage()
      p.save()

      def get(self, request, *args, **kwargs):
          context = locals()
          context['response'] = self.response
          context['p'] = self.p
          return render_to_response(self.response_template, context, context_instance=RequestContext(request))

Leave a comment