Reputation: 1991
I am getting a list of images from a directory and I am trying to convert a list of images to PDF. I am getting their width and height and using Image module. When the program runs and I open the PDF file, the picture look very big and only a corner of the pic.
from fpdf import FPDF
from PIL import Image
import glob
import os
image_directory = '/Users/myuser/pics/'
extensions = ('*.jpg','*.png','*.gif')
pdf = FPDF()
imagelist=[]
for ext in extensions:
imagelist.extend(glob.glob(os.path.join(image_directory,ext)))
for imageFile in imagelist:
cover = Image.open(imageFile)
width, height = cover.size
pdf.add_page()
# 1 px = 0.264583 mm (FPDF default is mm)
pdf.image(imageFile, 0, 0, float(width * 0.264583), float(height * 0.264583))
pdf.output(image_directory + "file.pdf", "F")
The image is the left one and the right is the PDF
Upvotes: 5
Views: 15861
Reputation: 338
pdf = FPDF(unit='mm')
for imageFile in selected_list:
cover = Image.open(imageFile)
width, height = cover.size
width, height = float(width * 0.264583), float(height * 0.264583)
pdf.add_page(format=(width, height))
pdf.image(imageFile, 0, 0, width, height)
name = "output.pdf"
pdf.output(name)
Upvotes: 0
Reputation: 136
I think the issue is with the image size exceeding the pdf size ( A4 by default) which is 210mm x 297 mm in portrait and inverse in landscape. You should check and resize according. You could also set page orientation according to the height and width of the page.
from fpdf import FPDF
from PIL import Image
import glob
import os
image_directory = '/Users/myuser/pics/'
extensions = ('*.jpg','*.png','*.gif')
pdf = FPDF()
imagelist=[]
for ext in extensions:
imagelist.extend(glob.glob(os.path.join(image_directory,ext)))
for imageFile in imagelist:
cover = Image.open(imageFile)
width, height = cover.size
# convert pixel in mm with 1px=0.264583 mm
width, height = float(width * 0.264583), float(height * 0.264583)
# given we are working with A4 format size
pdf_size = {'P': {'w': 210, 'h': 297}, 'L': {'w': 297, 'h': 210}}
# get page orientation from image size
orientation = 'P' if width < height else 'L'
# make sure image size is not greater than the pdf format size
width = width if width < pdf_size[orientation]['w'] else pdf_size[orientation]['w']
height = height if height < pdf_size[orientation]['h'] else pdf_size[orientation]['h']
pdf.add_page(orientation=orientation)
pdf.image(imageFile, 0, 0, width, height)
pdf.output(image_directory + "file.pdf", "F")
Upvotes: 8