[AppleScript] Batch saving to PDF

I had to re-print a batch of bills that are saved in (sorry) xls format.

Now my problem is, I need to send the PDFs, obviously. Exporting xls files to pdf is not exactly built-in Office X and 2004, so I had to go with AppleScript.

I have been a long time fan of that technology. The language itself might be weird, but the concept of something that can glue any piece of software together is a pretty smart one. Problem is, most of the applications or standard functions are not really “applescriptable”, meaning they don’t respond to precise functions. So that leaves UI scripting.

UI scripting is phenomenal, if a little hard to use. Basically, what it does is simulate keystrokes and clicks. That allows you to do anything a user would be able to do.

Without further ado, the AppleScript to batch sve to pdf a bunch of excel files using the print dialog!

on open some_items
    repeat with this_item in some_items
            tell application "Microsoft Excel"
                open this_item
                tell application "System Events" to tell process "Microsoft Excel"
                    --Bring up print window
                    keystroke "p" using command down
                    --Choose "PDF" > "Save as PDF"
                    click (menu button "PDF" of window 1)
                    click (menu item 1 of menu of menu button "PDF" of window 1)
                    delay 2
                    -- Choose the desktop as save locaton (Command-D)
                    keystroke "d" using command down
                    keystroke "s" using command down
                    keystroke return
                    -- wait and close
                    delay 3
                    keystroke "w" using command down
                end tell
            end tell
        end try
    end repeat
    tell application "Finder"
        open desktop
    end tell
end open

Leave a Reply

%d bloggers like this: