Applescript to open all files in a folder and convert to PDF with Preview

applescriptautomatorpdfpreview

I've written an AppleScript to do as the title describes. It is supposed to go to a given folder, open each of the files one at a time in preview, click "file" on the menu bar, then click "Export as PDF…", then click enter to accept the dialog that will open. Repeat until there's no more files left to automate.

tell application "Finder"
    set fl to files of folder POSIX file "/Users/username/Desktop/Folder" as alias list
end tell
repeat with f in fl
    tell application "Preview"
        open f
        tell application "System Events" to tell process "Preview"
            click menu item "Export as PDF..." of menu 1 of menu bar item "File" of menu bar 1
        end tell
        keystroke return
    end tell
end repeat

I get the following error when it runs, it opens the file in Preview and stops.
Any ideas?

The error isn't very descriptive.

enter image description here

Best Answer

It needs to be "Export as PDF…" not "Export as PDF...", note that the first example has an actual ellipsis, not like in your code, the second example, three dots after PDF.

Also, as an example in Preview under macOS 10.12.5 Sierra that I tested this under, you can also use:

tell application "System Events" to tell process "Preview"
    click menu item 14 of of menu 1 of menu bar item "File" of menu bar 1
end tell

Note: Obviously under different versions of OS X/macOS "Export as PDF…" may be a different menu item number or that command may not exist in that form.


To address the comment, I'd use the following instead of what you currently have:

tell application "System Events"
    click menu item "Export as PDF…" of menu 1 of menu bar item "File" of menu bar 1 of application process "Preview"
    delay 0.2
    click button "Save" of sheet 1 of window 1 of application process "Preview"
end tell

Leaving out keystroke return from the code.

Note: The value of the delay command may need to be adjusted for your system.