Search for page number with PDF Expert and Applescript

applescriptpdf

I'm trying to write an Applescript script that will open a pdf agile.pdf with PDF Expert and search for a page number.

I'm getting close with the following script:

do shell script "open agile.pdf"
delay 1.0

tell application "System Events" 
  tell application process "PDF Expert"
    click menu item "Go to Page..."  of menu 1 of menu bar item "Go"  of menu bar 1
    keystroke "42"
    key code 76
  end tell
end tell

The problem is my script as it is will only work if I've already "clicked into" a PDF Expert window.

Is it possible for me to tell Applescript to "click into the PDF Expert window after it opens?

Also, it is possible for me to tell Applescript to "wait until the window exists?

I was reading another answer that makes it look like the following will work but it doesn't:

repeat until window "agile" of process "PDF Expert" exists
end repeat

I've done some poking around with UIElementInspector as recommended in another answer. This is the output of the PDF Expert window:

<AXApplication: “PDF Expert”>
 <AXWindow: “agile”>
  <AXSplitGroup>
   <AXScrollArea>

Attributes:
   AXHorizontalScrollBar:  “<AXScrollBar>”
   AXParent:  “<AXSplitGroup>”
   AXChildren:  “<array of size 5>”
   AXFocused (W):  “1”
   AXSize:  “w=892 h=649”
   AXRole:  “AXScrollArea”
   AXTopLevelUIElement:  “<AXWindow: “agile”>”
   AXHelp:  “(null)”
   AXChildrenInNavigationOrder:  “<array of size 5>”
   AXPosition:  “x=292 y=-803”
   AXWindow:  “<AXWindow: “agile”>”
   AXRoleDescription:  “scroll area”
   AXVerticalScrollBar:  “<AXScrollBar>”
   AXContents:  “<array of size 3>”
   AXFrame:  “x=292 y=-803 w=892 h=649”

Actions:
   AXScrollLeftByPage - scroll left by a page
   AXScrollRightByPage - scroll right by a page
   AXScrollUpByPage - scroll up by a page
   AXScrollDownByPage - scroll down by a page

Best Answer

PDF Exper and keystroke "42" doesn't work for me.

However, using Skim and key code works:

do shell script "open -a Skim agile.pdf"
delay 0.1

tell application "System Events" 
  tell application process "Skim"
    tell application "System Events" to tell process "Skim" to click menu item "Go to Page…" of menu "Go" of menu bar 1
    delay 0.1
    key code {21, 19, 36}
  end tell
end tell