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:



if [ -z "$1" ]
  echo "Dude, I need a page number."
  exit -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


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

./ 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.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.