Search code examples
python-3.xpdfpdf-generationpymupdf

PyMuPDF insert image at bottom


I'm trying to read a PDF and insert an image at bottom(Footer) of each page in PDF. I've tried with PyMuPDF library.

Problem: Whatever the Rect (height, width) I give, it doesn't appear in the bottom, image keeps appearing only on the top half of the page (PDF page).

My code:

from fitz import fitz, Rect

doc = fitz.open("test_pdf2.pdf")

def add_footer(pdf):
    img = open("footer4.jpg", "rb").read()
    rect = Rect(0, 0, 570, 1230)

    for i in range(0, pdf.pageCount):
        page = pdf[i]
        if not page._isWrapped:
            page._wrapContents()
        page.insertImage(rect, stream=img)

add_footer(doc)
doc.save('test_pdf5.pdf')

Processed_image with footer image in the middle of the page: https://i.sstatic.net/HK9mm.png

Footer image: https://i.sstatic.net/FRQYE.jpg

Please help!

Please let me know if this can be achieved by using any other library.


Solution

  • After doing little trial and error I was able to figure out the problem. I was missing out on proper dimensions of Rect, I had to give 0.85*h in second parameter. below is the code:

    from fitz import fitz, Rect
    
    doc = fitz.open("test_pdf2.pdf")
    w = 595
    h = 842
    
    def add_footer(pdf):
        img = open("footer4.jpg", "rb").read()
        rect = fitz.Rect(0, 0.85*h, w, h)
    
        for i in range(0, pdf.pageCount):
            page = pdf[i]
            if not page._isWrapped:
                page._wrapContents()
            page.insertImage(rect, stream=img)
    
    add_footer(doc)
    doc.save('test_pdf5.pdf')