简体   繁体   中英

Generating PDFs with Django 1.9

I want to generate a PDF using the following approach found on the Django 1.9 docs: https://docs.djangoproject.com/ja/1.9/howto/outputting-pdf .

Here is my url pattern (I don't need anything special, just a different url name like so

urlpatterns = [
   url(r'^people/$', PeopleTemplate.as_view(), name='people'),
   url(r'^people/pdf/$', some_view),
 ]

  def some_view(request):
      response = HttpResponse(content_type='application/pdf')
      response['Content-Disposition'] = 'attachment; filename="example.pdf"'
      p = canvas.Canvas(response)
      p.drawString(100, 100, "Hello world.")
      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))

I'm trying to use a get method. This prompts for a pdf output when I hit /pdf, but doesn't contain any data - just a blank page. How do I get data that exists at this url /attendance/ to show on the pdf page when you hit the /attendance/pdf url?

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM