import sys, os, subprocess, shutil, glob, time
import numpy as np
import PIL
from PIL import Image

ref = sys.argv[1]
pdf_name = sys.argv[2]
pdf_dir = sys.argv[3]

# pdf_dir = "e:/webroot/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
image_name = os.path.splitext(pdf_name) [0]
shutil.copy(pdf_dir+"/"+pdf_name, ref+"cpy.pdf")
page = ""
# convert PDF to jpg
if (len(sys.argv)>4):
    page = sys.argv[3]
    subprocess.Popen('"e:/poppler/Library/bin/pdftoppm.exe" -singlefile -f '+str(page)+' -jpeg %s out' %(ref+"cpy.pdf"))
    time.sleep(1)
    fileList = glob.glob(pdf_dir+'out.jpg')
else:
    subprocess.Popen('"e:/poppler/Library/bin/pdftoppm.exe" -jpeg %s out' %(ref+"cpy.pdf"))
    time.sleep(2)
    fileList = glob.glob(pdf_dir+'out*.jpg')
    
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]
# 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+image_name+page+'.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)

fileList = glob.glob(pdf_dir+ref+'*cpy.pdf')
# Iterate over the list of filepaths & remove each file.
for filePath in fileList:
    try:
        os.remove(filePath)
    except:
        print("Error while deleting file : ", filePath)
        
print(pdf_dir+image_name+page+'.jpg')


        