简体   繁体   English

使用Django 1.9生成PDF

[英]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 . 我想使用在Django 1.9 docs上找到的以下方法生成PDF: 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. 我正在尝试使用get方法。 This prompts for a pdf output when I hit /pdf, but doesn't contain any data - just a blank page. 当我打/ pdf时,它提示输入pdf输出,但不包含任何数据-只是一个空白页。 How do I get data that exists at this url /attendance/ to show on the pdf page when you hit the /attendance/pdf url? 当您点击/ attendance / pdf网址时,如何获取该网址/ attendance /上存在的数据以显示在pdf页面上?

I think you need to: 我认为您需要:

  1. render html 渲染HTML
  2. convert it to pdf 转换成PDF
  3. set pdf content to response body 将pdf内容设置为响应主体
  4. return response 返回响应

Now your code renders template as html, adds 'application/pdf' content type to headers and returns normal html page. 现在,您的代码将模板呈现为html,将“ application / pdf”内容类型添加到标题中并返回正常的html页面。

You need something like PDFTemplateView. 您需要类似PDFTemplateView的东西。 There are ready to use packages django-easy-pdf or django-wkhtmltopdf . 现在可以使用django-easy-pdfdjango-wkhtmltopdf软件包

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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