Put Header, Footer and page number for pdf with pdfpages matplotlib

834 views Asked by At

I created PDF file of figures with pdfpages in matplotlib.

Now I want to add headers (contains text and line), footer (contains text and line) and page number. How can I do that?

1

There are 1 answers

0
Jorj McKie On

Use PyMuPDF:

Decide the header and footer rectangle coordinates, then the text of each with the constant and variable parts.

Example:

Footer: One line, bottom of rectangle 0.5 inches (36 points) above bottom of page, 11 points font size, font Helvetica, text centered "Page n of m".

Header: One line, rectangle top 36 points below top of page, 20 points rect height, font Helvetica bold, text "My Matplotlib File" centered. 11 points font size, color blue.

import fitz
doc = fitz.open("matplotlib.pdf")
numpages = doc.page_count  # number of pages
footer_text = "Page %i of %i"
header_text = "My Matplotlib File"
blue = fitz.pdfcolor["blue"]

for page in doc:
    prect = page.rect
    header_rect = fitz.Rect(0, 36, prect.width, 56)  # height 20 points
    page.insert_textbox(header_rect, header_text,
                        fontname="hebo", color=blue,
                        align=fitz.TEXT_ALIGN_CENTER)

    ftext = footer_text % (page.number + 1, numpages)
    y1 = prect.height - 36  # bottom of footer rect
    y0 = y1 - 20  # top of footer rect
    footer_rect = fitz.Rect(0, y0, prect.width, y1)  # rect has full page width
    page.insert_textbox(footer_rect, text, align=fitz.TEXT_ALIGN_CENTER)

doc.save("matplotlib-numbered.pdf")