Skip to content

Instantly share code, notes, and snippets.

@msehnout
Created December 15, 2019 12:09
Show Gist options
  • Save msehnout/39c5abb0ad2df26bb9920ad48619422e to your computer and use it in GitHub Desktop.
Save msehnout/39c5abb0ad2df26bb9920ad48619422e to your computer and use it in GitHub Desktop.
Print a list of images into a PDF file with two images per page.
import os
from fpdf import FPDF
from PIL import Image
input = os.environ["INPUT"]
output = os.environ["OUTPUT"]
images = os.listdir(input)
print(images)
def calc_image_size(image_file: str) -> (int, int):
magic = 14.5
max_width = int(13*magic)
max_height = int(9*magic)
image = Image.open(image_file)
width, height = image.size
print(f"original size: {width}, {height}")
if max_width < width:
height = int(height*(max_width/width))
width = max_width
if max_height < height:
width = int(width*(max_height/height))
height = max_height
print(f"new size: {width}, {height}")
return width, height
iter = 0
pdf = FPDF()
for image in images:
file_name = f"{input}/{image}"
print(f"processing {image}")
width, height = calc_image_size(file_name)
if iter % 2 == 0:
pdf.add_page()
pdf.image(file_name, 15, 5, width, height)
else:
pdf.image(file_name, 15, 155, width, height)
iter += 1
pdf.output(f"{output}/test.pdf", "F")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment