Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
316 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...