Search code examples
pythonpdfglobfpdfimg2pdf

python Portrait and landscape page in pdf


I am new to python. I want to generate a pdf with 3 images, 1 image is a portrait, the second image is a landscape and the third image is a portrait again. But it seems the code below cannot handle this situation, am I missing anything?

images = []
images = glob.glob(Outpath + "/IMG/*.jpg" ,recursive=False)

pdf = FPDF()

for x in range(len(images)):
    print(images[x] + ' at x = ' + str(x))

    #pdf.add_page()
    if width > height:
        pdf.add_page(orientation='L')
        pdf.image(images[x],x=0,y=0,h=210,w=297)
    elif width < height:
        pdf.add_page(orientation='P')
        pdf.image(images[x],x=0,y=0,h=297,w=210)

pdf.output(Outpath + "/IMG/IO.pdf", "F")

Solution

  • You are creating a new object in each iteration.

    Create a single variable once and use that in future iterations as below:

    import glob
    from fpdf import FPDF
    
    images = []
    images = glob.glob(Outpath + "/IMG/*.jpg" ,recursive=False)
    
    pdf = FPDF()
    
    for x in range(len(images)):
    
        im_int = Image.open(images[x])
        width = im_int.width
        height = im_int.height
        if width > height:
            pdf.add_page(orientation='L')
            pdf.image(images[x],x=0,y=0,h=210,w=297)
        else:
            pdf.add_page()
            pdf.image(images[x],x=0,y=0,h=297,w=210)
    
    pdf.output(Outpath + "/IMG/IO.pdf", "F")