Replace footer text in pdf file using python

Question:

I have a file similar to this.

What I want to do is replace the footer of the page with my own footer. What would be the best way to do this? Can I crop the footer part (fixed size from bottom) and merge my own created footer with every page? Or is there a library available that could automatically extract footer from the page? I don’t have much experience in this regard. I have tried some libraries including pypdf2 and reportlab but I was not able to find any help regarding footer extraction.

Any help will be greatly appreciated.

Asked By: A.Hamza

||

Answers:

This is a bit of hack solution, create an image with required footer text and then run this. Adjust the coordinates as required.

from PyPDF2 import PdfFileWriter, PdfFileReader
import io
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter

packet = io.BytesIO()
# create a new PDF with Reportlab
can = canvas.Canvas(packet, pagesize=letter)
can.drawImage('yourFooterImage.png', 0, 2, 800, 45)
can.save()

# move to the beginning of the StringIO buffer
packet.seek(0)
new_pdf = PdfFileReader(packet)
# read your existing PDF
existing_pdf = PdfFileReader(open("original.pdf", "rb"))
output = PdfFileWriter()
# add the "watermark" (which is the new pdf) on the existing page
page = existing_pdf.getPage(0)
page.mergePage(new_pdf.getPage(0))
output.addPage(page)
# finally, write "output" to a real file
outputStream = open("destination.pdf", "wb")
output.write(outputStream)
outputStream.close()

Code taken from here: Add text to Existing PDF using Python

My output:

enter image description here

Answered By: SubhashR

You can do the following (e.g. with pypdf):

  1. Crop the PDF so that the footer is no longer shown.
  2. Create a PDF that has only the footer.
  3. Merge the cropped page on the page that has only the footer.

Please note that if you only adjust the cropbox in (1), the text will still be there. It will just not be visible.

Answered By: Martin Thoma
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.