import sys, os, subprocess, shutil, glob, time
import numpy as np
import PIL
from PIL import Image

pdf_dir = "c:/web/veldb/vimsreports/"

os.chdir(pdf_dir)
# delete work files
fileList = glob.glob(pdf_dir+'out*.jpg')
# Iterate over the list of filepaths & remove each file.
for filePath in fileList:
    try:
        os.remove(filePath)
    except:
        print("Error while deleting file : ", filePath)
# copy pdf file
pdf_name = sys.argv[1]
shutil.copy(pdf_name, "pdf.pdf")
# convert PDF to jpg
subprocess.Popen('"c:/poppler/Library/bin/pdftoppm.exe" -jpeg %s out' %("pdf.pdf"))
# fileList = ['out-1.jpg', 'out-2.jpg', 'out-3.jpg', 'out-4.jpg', 'out-5.jpg']
time.sleep(5)
fileList = glob.glob(pdf_dir+'out*.jpg')
# print(fileList)

imgs    = [PIL.Image.open(i) for i in fileList]
# pick the image which is the smallest, and resize the others to match it (can be arbitrary image shape here)
min_shape = sorted( [(np.sum(i.size), i.size ) for i in imgs])[0][1]
imgs_comb = np.hstack( (np.asarray( i.resize(min_shape) ) for i in imgs ) )
# for a vertical stacking it is simple: use vstack
imgs_comb = np.vstack( (np.asarray( i.resize(min_shape) ) for i in imgs ) )
imgs_comb = PIL.Image.fromarray( imgs_comb)
imgs_comb.save( pdf_dir+'out.jpg' )
# delete work files
fileList = glob.glob(pdf_dir+'out-*.jpg')
# Iterate over the list of filepaths & remove each file.
for filePath in fileList:
    try:
        os.remove(filePath)
    except:
        print("Error while deleting file : ", filePath)


        