python – 如何使用reportlab在PDF中添加总页数

   def analysis_report(request):

       response = HttpResponse(mimetype='application/pdf')
       response['Content-Disposition'] = 'attachment;filename=ANALYSIS_REPORT.pdf'
       buffer = StringIO()
       doc = SimpleDocTemplate(buffer)
       doc.sample_no = 12345
       document = []
       doc.build(document, onLaterPages=header_footer)

   def header_footer(canvas, doc):
       canvas.saveState()

       canvas.setFont("Times-Bold", 11)
       canvas.setFillColor(gray)
       canvas.setStrokeColor('#5B80B2')
       canvas.drawCentredString(310, 800, 'HEADER ONE GOES HERE')
       canvas.drawString(440, 780, 'Sample No: %s' %doc.sample_no)

       canvas.setFont('Times-Roman', 5)
       canvas.drawString(565, 4, "Page %d" % doc.page)

我上面的代码我可以打包显示页码,但我的问题是如何显示“Y页面X”,其中Y是页数,X是当前页.

我跟着这个http://code.activestate.com/recipes/546511-page-x-of-y-with-reportlab/,但他们解释了使用canvasmaker,因为我在构建中使用了OnlaterPages参数.

如何使用canvasmaker实现上述功能,或者使用OnLaterPages是否有任何解决方案?

最佳答案 这是改进的配方
http://code.activestate.com/recipes/576832/,它应该与图像一起使用.

点赞