Combine images into PDF using Preview

A novice, I am trying to write a handler combining image files into one PDF. The handler needs three inputs:

  1. the sorted list of the image files
  2. the folder where to save the output PDF
  3. the file name of the output PDF

I have tried four different approaches scripting:
1) the GUI of "Preview"
2) a UNIX application
3) Adobe Acrobat Pro X
4) Automator

In order to stay focused, I discuss each approach in a different post.

The following handler scripts the GUI of “Preview”. Although it works well enough a few times, when ran dozens of times in a row it always either outpaces itself (despite all the delaying loops) or simply makes “Preview” totally unresponsive to the point of needing to use Force Quit.

My questions are:

  • does the script contain major errors?
  • how could it be improved?

Thanks in advance. W.

on combine_as_pdf(input_list, output_folder, output_file)
	-- input_list:     list of files as an alias_list
	-- output_folder:  reference to a folder
	-- output_file:    string ending in ".pdf"
	
	tell application "Preview"
		open input_list
		activate
	end tell
	
	tell application "System Events" to tell process "Preview"
		
		set output_path to POSIX path of output_folder
		click menu item "Select all" of menu "Edit" of menu bar 1
		click menu item "Print." of menu "File" of menu bar 1
		
		try
			repeat until exists sheet 1 of window 1
				delay
			end repeat
		end try
		click menu button "PDF" of sheet 1 of window 1
		
		repeat until exists menu item "Save as PDF." of menu "PDF" of menu button "PDF" of sheet 1 of window 1
			delay
		end repeat
		click menu item "Save as PDF." of menu "PDF" of menu button "PDF" of sheet 1 of window 1
		
		try
			repeat until exists text field 1 of window 1
				delay
			end repeat
		end try
		set (value of text field 1 of window 1) to output_file
		
		try
			repeat until (value of text field 1 of window 1) = output_file
				delay
			end repeat
		end try
		keystroke "g" using {shift down, command down}
		
		
		try
			repeat until exists text field 1 of sheet 1 of window "Save"
				delay
			end repeat
		end try
		set value of text field 1 of sheet 1 of window "Save" to output_path
		
		try
			repeat until (value of text field 1 of sheet 1 of window "Save") = output_path
				delay
			end repeat
		end try
		click button "Go" of sheet 1 of window "Save"
		
		try
			repeat while exists sheet 1 of window "Save"
				delay
			end repeat
		end try
		click button "Save" of window "Save"
		
		try
			repeat while exists sheet 1 of window 1
				delay
			end repeat
		end try
		click menu item "Close All" of menu 1 of menu bar item "File" of menu bar 1
		
	end tell
end combine_as_pdf