Search code examples
pythonpdffpdfpypdf

Removing blank pages from a newly generated pdf file with python


With the code below, I am trying to paste pictures out of a directory into a PDF file. The code is already working and generating my PDF almost as I wish.

The only problem that occurs is that it keeps adding blank pages between the pictures and I just don't know why. If I execute the code, the PDF starts with a blank page, then picture 1, blank page, picture 2 and so on. So I end up with a 50 page PDF file for 25 pictures.

The pictures are inserted correctly though, without any white borders around them. They fit the page size perfectly.

from fpdf import FPDF
from PIL import Image

def CreateList(End):
    _list = []
    for i in range(1, End + 1):
        _list.append(i)        
    return(_list)    

def makePdf(pdfFileName, listPages, dir = ''):
    if (dir):
        dir += "\\"

    cover = Image.open(dir + str(listPages[0]) + ".jpg")
    width, height = cover.size[0], cover.size[1]

    pdf = FPDF(unit = "pt", format = [width, height])

    for page in listPages:
        pdf.set_margins(0,0,0)
        pdf.add_page()
        pdf.image(dir + str(page) + ".jpg")

    pdf.output(dir + pdfFileName + ".pdf", "F")

listPages = CreateList(26)
makePdf('file', listPages, 'dir')

How can I avoid the problem with the added blank pages?

Alternatively, is there a way to search for blank pages in my newly generated PDF file and delete them out of it?


Solution

  • My initial guess would be that you need to disable set_auto_page_break:

    fpdf.set_auto_page_break(0)
    

    See docs here: https://github.com/reingart/pyfpdf/blob/master/docs/reference/set_auto_page_break.md