Batch Convert Keynote Files to PDF with AppleScript

I switched from Keynote to just writing presentations in Markdown and using Pandoc to convert them to PDF files with beamer. Markdown lends itself well to version control so I decided to store all my presentations in a git repository.

I already had a couple of years worth of Keynote presentations which I would never touch again. Since Keynote file are almost 8x larger than their PDF counterparts, I wanted to convert all my old presentations to PDF before sticking them under version control as well. Here’s a script which finds every *.key and .pptx recursively under the current directory and converts it to a PDF.

#! /bin/sh

for FILE in `find "${PWD}" -name \*.pptx -or -name \*.key`; do
  DIR=`dirname $FILE`
  echo Converting $FILE to PDF
  osascript << EOF
tell application "System Events"
  tell application "Keynote"
    activate
    open "${FILE}"
  end tell
  tell process "Keynote"
    click menu item "PDF…" of menu of menu bar item "Share" of menu bar 1
    click button "Next…" of sheet 1 of window 1
    keystroke "G" using {command down, shift down}
    keystroke "${DIR}"
    click button "Go" of sheet 1 of sheet 1 of window 1
    click button "Export" of sheet 1 of window 1
  end tell
  do shell script "killall Keynote"
end tell
EOF
done

This is my first go at AppleScript (or a shell script/AppleScript hybrid of some sort) so there may be some better ways to approach the problem. For instance, telling Keynote to quite would result in the script hanging with Keynote asking me if I wanted to save or not. And since tell application "Keynote" to quit didn’t seem to return until Keynote quit, making it impossible to dismiss the save dialog on the next line. I use killall Keynote to get around this problem.