Batch Convert Numbers Files to PDFs

Greetings everyone!

I am new here so I’d first like to introduce myself. My name is Bill. I am a 54 year old College Professor from Canada who teaches Graphic Design. I am looking to learn AppleScript as a way to streamline my workflow. I am in no way a programmer and am in the very early stages of learning AppleScript. I am presently reading AppleScript 1-2-3 which is a big help.

There are a couple of tasks that I would really love to automate to speed up my grading so I can get back to the book.

The first one is I’d like to batch convert a folder of Numbers Files to PDF. (I set up my grading rubrics in Numbers, it works great!)

The second one is a bit more involved which is starting with a Numbers “Classlist” file, I want to automate creating a single Numbers file for each student based on a specific User Template for the current project (the rubric). The script would drop in the student’s name (Lastname first, then Firstname) into the “Name” cell" on the rubric, then save it as a Numbers file. i.e.) Smith_Steven.numbers . The goal is to create a unique Numbers file for each student so they are ready to go when I grade their projects. I like to set these all up ahead of time so I am ready when my grading workload gets extremely heavy. Presently, I am doing this task manually and it takes entirely too long.

I am really excited to learn AppleScript, but presently I am swamped with end-of-term grading. UGH. If I can automate these tasks it will help me out immensely.

Thanks in advance and I look forward to getting my AppleScript knowledge to the point where I can be a contributing member here in the forums!

I picked up the below code from iWork Automation website as a starting point for the exporting PDFs as a starting point but is not set up for Batch converting. Any help would be appreciated!

property exportFileExtension : “pdf”
property useEncryptionDefaultValue : true

– THE DESTINATION FOLDER
– (see the “path” to command in the Standard Additions dictionary for other locations, such as movies folder, pictures folder, desktop folder)
set the defaultDestinationFolder to (path to documents folder)

set usePDFEncryption to useEncryptionDefaultValue
tell application “Numbers”
activate
try
if not (exists document 1) then error number -128

	if usePDFEncryption is true then
		-- PROMPT FOR PASSWORD (OPTIONAL)
		repeat
			display dialog "Enter a password for the PDF file:" default answer ¬
				"" buttons {"Cancel", "No Password", "OK"} ¬
				default button 3 with hidden answer
			copy the result to ¬
				{button returned:buttonPressed, text returned:firstPassword}
			if buttonPressed is "No Password" then
				set usePDFEncryption to false
				exit repeat
			else
				display dialog "Enter the password again:" default answer ¬
					"" buttons {"Cancel", "No Password", "OK"} ¬
					default button 3 with hidden answer
				copy the result to ¬
					{button returned:buttonPressed, text returned:secondPassword}
				if buttonPressed is "No Password" then
					set usePDFEncryption to false
					exit repeat
				else
					if firstPassword is not secondPassword then
						display dialog "Passwords do no match." buttons ¬
							{"Cancel", "Try Again"} default button 2
					else
						set providedPassword to the firstPassword
						set usePDFEncryption to true
						exit repeat
					end if
				end if
			end if
		end repeat
	end if
	
	-- DERIVE NAME AND FILE PATH FOR NEW EXPORT FILE
	set documentName to the name of the front document
	if documentName ends with ".numbers" then ¬
		set documentName to text 1 thru -9 of documentName
	
	tell application "Finder"
		set exportItemFileName to documentName & "." & exportFileExtension
		set incrementIndex to 1
		repeat until not (exists document file exportItemFileName of defaultDestinationFolder)
			set exportItemFileName to ¬
				documentName & "-" & (incrementIndex as string) & "." & exportFileExtension
			set incrementIndex to incrementIndex + 1
		end repeat
	end tell
	set the targetFileHFSPath to (defaultDestinationFolder as string) & exportItemFileName
	
	-- EXPORT THE DOCUMENT
	with timeout of 1200 seconds
		if usePDFEncryption is true then
			export front document to file targetFileHFSPath ¬
				as PDF with properties {password:providedPassword}
		else
			export front document to file targetFileHFSPath as PDF
		end if
	end timeout
	
on error errorMessage number errorNumber
	if errorNumber is not -128 then
		display alert "EXPORT PROBLEM" message errorMessage
	end if
	error number -128
end try

end tell

– SHOW THE NEW PDF FILE
tell application “Finder”
activate
reveal document file targetFileHFSPath
end tell

Model: Late 2013 iMac with Fusion Drive
AppleScript: 2.9
Browser: Safari 603.1.30
Operating System: Mac OS X (10.10)

You may try to use :

property exportFileExtension : "pdf"
property useEncryptionDefaultValue : true

script o
	# the password will be asked only once during the script execution.
	# It will no be stored on disk.
	property thePassword : ""
	property useEncryption : missing value
end script

set defaultSource to path to desktop # EDITED
set sourceFolder to (choose folder with prompt "Select the folder containing the documents to export" default location defaultSource) as text


-- THE DESTINATION FOLDER 
-- (see the "path" to command in the Standard Additions dictionary for other locations, such as movies folder, pictures folder, desktop folder)
set defaultDestination to path to documents folder
set defaultDestinationFolder to (choose folder with prompt "Select the folder where PDFs must be stored" default location defaultDestination)

copy useEncryptionDefaultValue to o's useEncryption
tell application id "com.apple.iwork.numbers"
	# Close every open documents
	if (count documents) > 0 then close every document
end tell

tell application "System Events"
	set theFiles to files of folder sourceFolder whose (type identifier is "com.apple.iwork.numbers.sffnumbers") or (type identifier is "com.apple.iwork.numbers.numbers")
	
	repeat with aFile in theFiles
		my exportToPDF(aFile, defaultDestinationFolder)
	end repeat
end tell

on exportToPDF(aFile, defaultDestinationFolder)
	tell application id "com.apple.iwork.numbers"
		activate
		try
			
			if o's thePassword = "" then
				# It's the first file. If needed ask for the password.
				if o's useEncryption then
					-- PROMPT FOR PASSWORD (OPTIONAL)
					repeat
						display dialog "Enter a password for the PDF file:" default answer ¬
							"" buttons {"Cancel", "No Password", "OK"} ¬
							default button 3 with hidden answer
						copy the result to ¬
							{button returned:buttonPressed, text returned:firstPassword}
						if buttonPressed is "No Password" then
							set o's useEncryption to false
							exit repeat
						else
							display dialog "Enter the password again:" default answer ¬
								"" buttons {"Cancel", "No Password", "OK"} ¬
								default button 3 with hidden answer
							copy the result to ¬
								{button returned:buttonPressed, text returned:secondPassword}
							if buttonPressed is "No Password" then
								set o's useEncryption to false
								exit repeat
							else
								if firstPassword is not secondPassword then
									display dialog "Passwords do no match." buttons ¬
										{"Cancel", "Try Again"} default button 2
								else
									set providedPassword to the firstPassword
									set o's useEncryption to true
									exit repeat
								end if
							end if
						end if
					end repeat
				end if
				if o's useEncryption then
					copy providedPassword to o's thePassword # store it for next files
				end if
			else
				if o's useEncryption then
					copy o's thePassword to providedPassword
				end if
			end if
			
			
			open aFile
			
			set pass to 0
			set maxPass to 50
			repeat
				set pass to pass + 1
				if pass = maxPass then exit repeat
				delay 0.2 # wait until the document is really open
				if (count documents) = 1 then exit repeat
			end repeat
			if pass = maxPass then error number 999
			
			-- DERIVE NAME AND FILE PATH FOR NEW EXPORT FILE
			set fullDocumentName to name of front document
			set visible of window fullDocumentName to false # ADDED
			copy fullDocumentName to documentName
			if documentName ends with ".numbers" then ¬
				set documentName to text 1 thru -9 of documentName
			
			tell application "Finder"
				set exportItemFileName to documentName & "." & exportFileExtension
				set incrementIndex to 1
				repeat until not (exists document file exportItemFileName of defaultDestinationFolder)
					set exportItemFileName to ¬
						documentName & "-" & incrementIndex & "." & exportFileExtension
					set incrementIndex to incrementIndex + 1
				end repeat
			end tell
			set targetFileHFSPath to (defaultDestinationFolder as string) & exportItemFileName
			
			-- EXPORT THE DOCUMENT
			with timeout of 1200 seconds
				set targetFileHFSPath to targetFileHFSPath as «class furl»
				tell me to close access (open for access targetFileHFSPath) # Required if you run under 10.12 thru 10.12.3. Don't hurt with 10.12.4 or 5
				if o's o's useEncryption then
					export front document to targetFileHFSPath ¬
						as PDF with properties {password:providedPassword}
				else
					export front document to targetFileHFSPath as PDF
				end if
			end timeout
			
		on error errorMessage number errorNumber
			if errorNumber = 999 then
				tell me to display alert "Can't open : " & aFile
			end if
			error number -128
			if errorNumber is not -128 then
				tell me to display alert "EXPORT PROBLEM" message errorMessage
			end if
			error number -128
		end try
		
		close document fullDocumentName
		
		
	end tell # Numbers
	
	-- SHOW THE NEW PDF FILE
	tell application "Finder"
		activate
		reveal document file targetFileHFSPath
	end tell
end exportToPDF

Yvan KOENIG running Sierra 10.12.4 in French (VALLAURIS, France) mercredi 12 avril 2017 16:39:25

Hi Yvan,

Big thanks for your help!

The script errors if no PDF password is entered. (Sometimes I require passwords for the PDFs and sometimes I don’t.)

One thing that I neglected to mention… it is preferable if I get the dialogue asking me for the destination folder.

I am chomping at the bit to get back to the book, I just need to pound through all of my grading first!

Thanks again!
Bill

Sorry.

I edited the script in message #2 to fit your needs.

Yvan KOENIG running Sierra 10.12.4 in French (VALLAURIS, France) mercredi 12 avril 2017 17:47:24

Hi Yvan,

No need for a “sorry” my friend, YOU are the guy helping ME and it’s appreciated!

This also generated the following error:

Can’t make “Fusion_iMac:Users:bill:Desktop:” into type alias.

If my knowledge of AppleScript was better, I could probably troubleshoot this myself. I’ll get there. I plan on getting through the AppleScript book on my holidays which begin when I’m finished my marking and posting final grades.

Thanks so much,
Bill

Oops. Son of a b. 8
At the very beginning, edit :

set defaultSource to path to desktop as text

as

set defaultSource to path to desktop

I used a more complicated folder during tests and clean the instruction (wrongly) just in the body of my message.

Yvan KOENIG running Sierra 10.12.4 in French (VALLAURIS, France) mercredi 12 avril 2017 18:41:38

We are very close Yvan,

The script was asking for the source folder and then asking for it a second time. The second time it really wanted the destination folder and I was able to fix that.

It still errors if I choose “No Password”. To be honest, it’s rare that I need to add passwords and would be inconvenient in a batch situation anyway. I tried to remove all references to the password requirements but could not get the script to function properly.

Is it easier to remove the password option or easier to get it to work properly when clicking “No Password”?

Lastly, can this work in the background without seeing Numbers do it’s thing?

From the little that I have learned so far if we don’t tell Numbers to “Activate” we won’t see everything happen…Or am I wrong about that?

Again, thanks very much for your time!
Bill

I edited the script in message #2

It seems that everything is OK.

Removing the activate instruction changes nothing.
When it opens a document, Numbers always make its window visible at front.
I inserted the instruction

set visible of window fullDocumentName to false

so that the window doesn’t remain visible during the export process.
With my 2Mbytes sample files it may make sense. I’m not sure that it does with smaller files.

Yvan KOENIG running Sierra 10.12.4 in French (VALLAURIS, France) mercredi 12 avril 2017 20:45:39

Hi Yvan,

OK, I must have messed up. You are correct, it does seem to work now.

I’ll take your advice and just let the windows show “ it’s not a big deal.

Thanks very much!
Bill

You messed nothing. There was really a problem with “no password” :rolleyes:

Yvan KOENIG running Sierra 10.12.4 in French (VALLAURIS, France) mercredi 12 avril 2017 21:08:17

I’m a designer/Illustrator/teacher and have no programming knowledge, but Learning AppleScript is something that I am really interested in! I hate being inefficient and I hate repetitive “grunt work” when my time is better spent on other tasks. (like relaxing with a rum and watching the NHL Playoffs!)

I am going to take a break from marking for the rest of the day and take a stab at my second script idea and see what kind of a mess I can make. LOL

Thanks again for your help and patience Yvan!

Cheers,
Bill