3

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

2

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.

  • This is correct, thank you. However, my keystroke return gives the error: "Preview got an error: Can’t get keystroke " "." – JamesDonnelly Sep 27 '17 at 21:24
  • @JamesDonnelly you said 'However, my keystroke return gives the error: "Preview got an error: Can’t get keystroke " "."', ... well that's really a different question altogether. I'd suggest you ask another separate question, and if appropriate you can reference back to the original question if you feel it's pertinent. – user3439894 Sep 27 '17 at 21:31
  • @JamesDonnelly, I've updated my answer to address your comment. – user3439894 Sep 27 '17 at 21:46
  • Thank you for answering my question and my further comment. You’ve been very helpful. – JamesDonnelly Sep 28 '17 at 5:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .