Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add page numbers to PDF file using python and matplotlib?

I'm using PdfPages from matplotlib and I can loop through each figure object and save each one as a separate page in the same PDF:

from matplotlib.backends.backend_pdf import PdfPages
pp = PdfPages('output.pdf')
for fig in figs:
    pp.savefig(fig)
pp.close()

This works great. But is there a way for me to add a page number for each page in the PDF?

Thanks.

like image 758
mortada Avatar asked Aug 06 '14 15:08

mortada


1 Answers

A nice solution using reportlib and PyPDF (base on this):

from reportlab.lib.units import mm
from reportlab.pdfgen import canvas
import os
from PyPDF4.pdf import PdfFileReader, PdfFileWriter


def createPagePdf(num, tmp):
    c = canvas.Canvas(tmp)
    for i in range(1, num + 1):
        c.drawString((210 // 2) * mm, (4) * mm, str(i))
        c.showPage()
    c.save()


def add_page_numgers(pdf_path):
    """
    Add page numbers to a pdf, save the result as a new pdf
    @param pdf_path: path to pdf
    """
    tmp = "__tmp.pdf"

    output = PdfFileWriter()
    with open(pdf_path, 'rb') as f:
        pdf = PdfFileReader(f, strict=False)
        n = pdf.getNumPages()

        # create new PDF with page numbers
        createPagePdf(n, tmp)

        with open(tmp, 'rb') as ftmp:
            numberPdf = PdfFileReader(ftmp)
            # iterarte pages
            for p in range(n):
                page = pdf.getPage(p)
                numberLayer = numberPdf.getPage(p)
                # merge number page with actual page
                page.mergePage(numberLayer)
                output.addPage(page)

            # write result
            if output.getNumPages():
                newpath = pdf_path[:-4] + "_numbered.pdf"
                with open(newpath, 'wb') as f:
                    output.write(f)
        os.remove(tmp)
like image 62
ofir dubi Avatar answered Oct 04 '22 16:10

ofir dubi