Skip to content

Instantly share code, notes, and snippets.

@fenilgandhi
Created August 12, 2024 19:00
Show Gist options
  • Save fenilgandhi/b1002dfd358c4243768cff783d58088a to your computer and use it in GitHub Desktop.
Save fenilgandhi/b1002dfd358c4243768cff783d58088a to your computer and use it in GitHub Desktop.
Generate pdf from a images folder
import os
import img2pdf
from PIL import Image
def resize_image(img, max_resolution):
"""Resize image to the maximum resolution while maintaining the aspect ratio."""
width, height = img.size
if max(width, height) > max_resolution:
scaling_factor = max_resolution / float(max(width, height))
new_size = (int(width * scaling_factor), int(height * scaling_factor))
img = img.resize(new_size, Image.Resampling.LANCZOS)
return img
def convert_images_to_pdf(image_folder, output_pdf, max_resolution=2000):
# Get all image files from the folder
image_files = [f for f in os.listdir(image_folder) if f.endswith(('png', 'jpg', 'jpeg', 'tiff', 'bmp', 'gif'))]
image_files.sort() # Optional: sort files by name
# Create a list to store paths of resized images
temp_images = []
for image_file in image_files:
img_path = os.path.join(image_folder, image_file)
with Image.open(img_path) as img:
# Resize image
img = resize_image(img, max_resolution)
# Convert the image to RGB if it's in a different mode (like RGBA)
if img.mode in ("RGBA", "P"):
img = img.convert("RGB")
# Save the resized image to a temporary path
temp_img_path = os.path.join(image_folder, f"temp_{image_file}")
img.save(temp_img_path, format="JPEG")
temp_images.append(temp_img_path)
# Convert the resized images to a single PDF file
with open(output_pdf, "wb") as f:
f.write(img2pdf.convert(temp_images))
# Clean up temporary images
for temp_img_path in temp_images:
os.remove(temp_img_path)
# Specify the folder containing images and the output PDF file name
image_folder = input("Enter input folder name :")
output_pdf = input("Enter output filename :")
convert_images_to_pdf(image_folder, output_pdf)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment