Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
321 views
in Technique[技术] by (71.8m points)

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")
question from:https://stackoverflow.com/questions/65917718/python-portrait-and-landscape-page-in-pdf

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...