Batch convert pages and numbers files to pdf? Need help with Applescript

Hello!
I’m trying to batch convert Apple docs to pdf. I’m a teacher and my colleagues all have Windows PCs. From time to time I have to share files with them, so I usually convert them to PDF.
Now this is tedious… Open pages, choose file, export, pdf…

I would like to choose a bunch of files, trigger an Applescript with Keyboard Maestro and convert them.
I’ve found a working script but it works differently:

set theFolder to choose folder with prompt "Select folder with original pages files :"
--Do it
tell application "Finder"
	set theNames to name of files of theFolder ¬
		whose name extension is "pages"
end tell

-- How many files to export
set item_count to (get count of items in theNames)

--Get files and export them
repeat with i from 1 to item_count
	
	set current_file to item i of theNames -- get a file
	set lean_file to text 1 thru -7 of current_file & ".pdf" -- change the originalfile (.pages) to a .pdf name
	set out_file to (theFolder as Unicode text) & (lean_file) -- get the fully qualified output name
	set in_file to (theFolder as Unicode text) & (current_file) -- get the fully qualified input file name
	
	tell application "Pages"
		set mydoc to open file in_file -- open input file in Pages
		export mydoc to file out_file as PDF --do the exporting
		close mydoc saving no -- close the original file without saving
	end tell
	
end repeat


display dialog "done" -- Job done

Instead of letting me choose the files I have to choose a folder and it converts every .pages inside. I would rather choose my files myself, either with KM or by Applescript. Is there a way to change my script to do this?

Try this:

-- Get the selected files
tell application "Finder" to set finderSelection to the selection

-- Filter out the non-Pages files
set pagesFiles to {}
repeat with f in finderSelection
	if name extension of f is "pages" then
		set end of pagesFiles to f as text
	end if
end repeat

-- Go through the Pages files and convert them
repeat with currentFile in pagesFiles
	
	-- Set up the full path to the new PDF file
	set pdfFile to (text 1 thru -6 of currentFile) & "pdf"
	
	-- Open the Pages file and export as PDF
	tell application "Pages"
		set pagesDoc to open file currentFile
		export pagesDoc to file pdfFile as PDF
		close pagesDoc saving no
	end tell
	
end repeat

There ought to be a cleaner way of filtering the selection with some kind of whose name extension is "pages" construct, but I couldn’t figure it out, so I used a repeat loop and an if statement to build up the list of Pages files one at a time. It seems to work

3 Likes

Solved. Thank you a lot. It works. Now I can just select a bunch of files in finder, press a shortcut and Keyboard Maestro starts the script on those files. Awesome. :slight_smile: