pdf中的python纵向和横向页面

问题描述

我是 Python 新手。我想生成一个包含 3 张图像的 pdf,1 张图像是肖像,第二张图像是风景,第三张图像再次是肖像。但似乎下面的代码无法处理这种情况,我错过了什么吗?

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],h=297,w=210)

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

解决方法

您在每次迭代中都创建了一个新对象。

创建一个变量一次并在以后的迭代中使用它,如下所示:

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],h=297,w=210)

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