Applescript: How to open a PDF in Preview and go directly to a page

I’m currently generating my new book on “functional programming in Scala” as a PDF using a combination of Pandoc and LaTeX, and as a result it feels like I’m opening the same PDF file about 100 times a day.

A little while ago I decided it would be really nice if I could go directly to the page I’m interested in when the PDF opens, so I cobbled together a Unix shell script and some Applescript that (a) opens the PDF in the Mac Preview app, and (b) goes directly to the page I’m interested in. It turns out that Preview isn’t very scriptable, so I have to jump through a few hoops to get to the desired page:

#!/bin/sh

FILE="${PWD}/book.pdf"

if [ -z "$1" ]
then
  echo "Dude, I need a page number."
  exit -1
fi

PAGE=$1

# ----------------------
# Applescript below here
# ----------------------

osascript <<EOF

set pageNumber to $PAGE
set fileName to "$FILE"

set posixFile to POSIX file fileName
tell application "Finder" to open posixFile

delay 2
tell application "System Events"
    keystroke "g" using {option down, command down}
    keystroke pageNumber
    delay 1
    keystroke return
end tell

EOF

I named this script preview.sh, and I run it like this to go directly to page 20 in the PDF (which is named book.pdf):

./preview.sh 20

As usual, there are probably other/better ways to do this, but (a) I can confirm that this works, and (b) a lot of other things I tried didn’t work.