I wrote an AppleScript whose purpose is to trigger Safari’s “print to pdf” functionality. The script fails at line 14 when attempting to select the “Save as PDF” from the menu button “PDF”
`-- Found some reusable code snippets here
--https://www.macscripter.net/t/gui-scripting-of-print-dialog/45378/3
tell application "Safari" to activate
tell application "System Events"
tell process "Safari"
click menu item "Print…" of menu "File" of menu bar 1
repeat until exists sheet 1 of window 1
delay 1
end repeat
click menu button "PDF" of splitter group 1 of sheet 1 of window 1
repeat until exists menu 1 of menu button "PDF"
delay 1
end repeat
click menu item "Save as PDF" of menu 1 of menu button "PDF"
end tell
end tell`
It seems like “menu 1” is not a child of the “PDF” menu button.
Any ideas on how to select menu items from the “PDF” menu button?
Thank you for your assistance! @Fredrik71
I came up with this, latest Safari:
tell application "System Events" to tell application process "Safari"
set frontmost to true
# window 1
tell window 1
# PRINT - using keystrokes is faster
keystroke "p" using {command down}
# check for PRINT sheet
repeat until exists sheet 1
delay 0.2
end repeat
# PRINT sheet
tell sheet 1
# > PDF > Save as PDF (in a splitter group)
tell splitter group 1
click menu button "PDF"
repeat until exists menu 1 of menu button "PDF"
delay 0.2
end repeat
click menu item "Save as PDF" of menu 1 of menu button "PDF"
end tell -- splitter group 1
# check for "Save as PDF" sheet
repeat until exists sheet 1
delay 0.2
end repeat
# "Save as PDF" sheet
tell sheet 1
# change the filename of the PDF
set value of text field 1 to "test.pdf"
delay 0.2
# return keystroke is faster
# saves the file into the last used directory
keystroke return
# if the file esists, replace it
# check if "Repace Existing" sheet appears
delay 0.2
if exists sheet 1 then
log "replace"
tell sheet 1 to click button "Replace"
else
log "save"
end if
end tell -- "Save as PDF" sheet
end tell -- # PRINT sheet
end tell -- window 1
end tell -- application "System Events" > application process "Safari"
EDIT: I am looking for a way to wait for the PDF processing to end, any idea or tip would be appreciated
First, determine what is a reference to this Processing page:3… dialog. Then you can use repeat loop with WHILE condition
For example, the reference is sheet 1 of window 1. Then, a way to wait for the PDF processing to end is simple:
repeat while sheet 1 of window 1 exists
delay 0.2
end repeat