How to add total page count in PDF using reportlab

最后都变了- 提交于 2020-01-04 02:42:26

问题


   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)

I above code i can bale to display the page number, but my question is how can i display "Page X of Y" where Y is page count and X is current page.

I followed this http://code.activestate.com/recipes/546511-page-x-of-y-with-reportlab/, but they explained using canvasmaker, where as i'm using OnlaterPages argument in build.

How can i achieve the above thing using canvasmaker or is there any solution using OnLaterPages ?


回答1:


Here is the improved recipe http://code.activestate.com/recipes/576832/ which should work with images.




回答2:


Another possible workaround would be to use pyPDF (or any other pdf-lib with the funcionality) to read the total number of pages after doc.build() and then rebuild the story with the gathered information by exchanging the corresponding Paragraph()'s. This approach might be more hackish, but does the trick with no subclassing.

Example:

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)


来源:https://stackoverflow.com/questions/12233787/how-to-add-total-page-count-in-pdf-using-reportlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!