ajd018
ajd018

Reputation: 171

Page Orientation when converting images to pdf using FPDF (python)

I am trying to convert a folder of images(jpg) into PDFs using FPDF. This code works great for the images in portrait format. For the images in landscape though it puts them on the portrait format. Is there a way to detect orientation and assign that to the pdf?

enter image description here

updated code for fix

from fpdf import FPDF
from PIL import Image
import glob
import os

image_directory = r'C:\coolbro\test\yay\test'

extensions = ('*.jpg','*.png','*.gif')

imagelist=[]
for ext in extensions:
    imagelist.extend(glob.glob(os.path.join(image_directory,ext)))

for imagePath in imagelist:


    cover = Image.open(imagePath)
    width, height = cover.size

    if height > width:

        pdf = FPDF(unit = "pt", format = "legal")

        pdf.add_page()

        pdf.image(imagePath, 0, 0, 600)

        destination = os.path.splitext(imagePath)[0]
        pdf.output(destination + ".pdf", "F")

    if width > height:

        pdf = FPDF("L", unit = "pt", format = "legal")

        pdf.add_page()

        pdf.image(imagePath, 0, 0, 0, 600)

        destination = os.path.splitext(imagePath)[0]
        pdf.output(destination + ".pdf", "F")

Upvotes: 1

Views: 5746

Answers (1)

stovfl
stovfl

Reputation: 15533

Comment: I was trying to find a way to read the orientation

if Y > X:
    # portrait
else:
    # landscape

Add orientation = 'L', for instance:

fpdf = FPDF(orientation = 'L', unit = 'mm', format='A4')

Upvotes: 4

Related Questions