简体   繁体   中英

How to add total page count in PDF using reportlab

   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 ?

这是改进的食谱http://code.activestate.com/recipes/576832/ ,它应该与图像一起使用。

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)

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