【问题标题】:How to add total page count in PDF using reportlab如何使用reportlab在PDF中添加总页数
【发布时间】:2014-02-24 20:05:32
【问题描述】:
   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 的解决方案?

【问题讨论】:

  • 我认为您误解了链接文章提供的解决方案。他们的方式覆盖了画布的保存功能。如果你想用鸭嘴兽来做这件事(我假设这是因为你引用了onlaterpages),这里至少提到了另一种方法stackoverflow.com/questions/637800/…

标签: python django reportlab


【解决方案1】:

这是改进的配方http://code.activestate.com/recipes/576832/,它应该适用于图像。

【讨论】:

    【解决方案2】:

    另一种可能的解决方法是使用 pyPDF(或任何其他具有该功能的 pdf-lib)读取 doc.build() 之后的总页数,然后通过交换相应的 Paragraph() 来使用收集的信息重建故事s。这种方法可能更hackish,但是没有子类化就可以了。

    例子:

    from pyPdf import PdfFileReader
    [...]
    story.append(Paragraph('temp paragraph. this will be exchanged with the total page number'))
    post_story = story[:] #copy the story because build consumes it
    doc.build(story) #build the pdf with name temp.pdf
    temp_pdf = PdfFileReader(file("temp.pdf", "rb"))
    total_pages = cert_temp.getNumPages()
    post_story[-1] = Paragraph('total pages: ' + str(total_pages))
    doc.build(post_story)
    

    【讨论】:

      猜你喜欢
      • 2019-01-01
      • 2015-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-05
      • 2011-02-12
      相关资源
      最近更新 更多