#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""Image_folder_to_PDF.py: Converts a folder of images into a single compact pdf file

To use, just 
    - change image_folder path to folder containing your images,
    - change pdf_filename to your desired output file name,
    - run script.
    - if pdf pages not oriented correctly, rerun with appropriate rotation_angle

The images files are inserted in alphabetical order based on their file names.

May take a while for a large number of images.
"""

__author__ = "David Bailey"
__email__ = "dbailey@physics.utoronto.ca"
__copyright__ = "Copyright 2020-21, University of Toronto"
__license__ = "MIT"
__version__ = "1.1"
__date__ = " 2021-02-04"


import os
from PIL import Image
from pprint import pprint

# Path to folder containing images
image_folder = "Notebook"  # Here "Notebook" folder and JPEG_to_PDF.py are both local
# Name of output pdf file that will contain combined images
pdf_filename = "Notebook.pdf"
# Counter-clockwise rotation angle in degrees (if output has incorrectly oriented images)
rotation_angle = 0  # Allowed values are 0, 90, 180,270

# Gather list of image files in image_folder
image_files=[]
for file in sorted(os.listdir(image_folder)) :
    try :
        Image.open(image_folder+"/"+file)
        image_files.append(file)
    # Ignore, but warn about, any files PIL does not recognize as an image
    except :
        print("Non-image file ignored :  "+file)

# Sort files in natural human order
#   see https://stackoverflow.com/questions/4623446
image_files.sort(key=str)
# Print list of images to be included
pprint(image_files)

# Open images in list (with optional rotation)
#   Note: transpose is used to avoid black borders from simple rotation
if rotation_angle == 270 :
    opened_images = [Image.open(image_folder+"/"
        +image_file).convert('RGB').transpose(method=Image.ROTATE_270) for image_file in image_files]
elif rotation_angle == 180 :
    opened_images = [Image.open(image_folder+"/"
        +image_file).convert('RGB').transpose(method=Image.ROTATE_180) for image_file in image_files]
elif rotation_angle == 90 :
    opened_images = [Image.open(image_folder+"/"
        +image_file).convert('RGB').transpose(method=Image.ROTATE_90)  for image_file in image_files]
else :
    opened_images = [Image.open(image_folder+"/"
        +image_file).convert('RGB')                                    for image_file in image_files]


# Create pdf_file by copying first image in opened_images
pdf_file = opened_images[0].copy()
# Append rest of images and save as pdf
pdf_file.save(pdf_filename, "PDF" , save_all=True, append_images=opened_images[1:])

print("Image_folder_to_PDF.py DONE: "+pdf_filename+" file created")