AppleScript 可促进在 Safari 浏览器中打印为 PDF

问题描述 投票:0回答:2

我编写了一个 AppleScript,其目的是触发 Safari 的“打印到 pdf”功能。当尝试从菜单按钮“PDF”中选择“另存为 PDF”时,脚本在第 14 行失败

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

关于如何从“PDF”菜单按钮选择菜单项有什么想法吗?

pdf safari applescript
2个回答
0
投票

试试这个:

delay 1
perform action "AXShowMenu" of menu button "PDF" of sheet 1 of window 1
perform action "AXPress" of menu item "Save as PDF…" of menu "PDF" of menu button "PDF" of sheet 1 of window 1

三件事......我在这里添加了延迟,因为有时填充工作表需要一些时间。它正在构建一个不是即时的预览,特别是对于大型或复杂的页面。其次,

Save as PDF…
要求包含省略号。第三,你必须用菜单项来运行
of
字符串。这意味着包括
of sheet 1 of window 1

最后,您可以使用

click
,但我对每个项目使用了关联的
action
,我发现这更可靠(因为它们不太含糊)。


0
投票

对于任何其他在这里找到方法的人:在 MacOS 14.5 上,有 2 个组属于拆分器组。您想要选择的是第 2 组。其次,即使我意识到必须选择哪个组,按名称选择菜单项似乎不起作用,但按索引选择却可以。顺便说一句,这也允许此菜单中的其他选项(“在预览中打开”、“另存为 Postscript”等)。下面的脚本将打开该线程并将其保存为 pdf。

tell application "Safari" to activate
tell application "System Events"
    tell process "Safari"
        activate
        open location "https://stackoverflow.com/questions/75768516/applescript-to-facilitate-print-to-pdf-in-safari-browser"
        delay 2
        keystroke "p" using {command down} --print
        repeat until exists sheet 1 of window 1
            delay 0.2
        end repeat
        perform action "AXShowMenu" of menu button 1 of group 2 of splitter group 1 of sheet 1 of window 1
        -- menu item 1 = Open in Preview
        -- menu item 3 = Save as Postscript
        click menu item 2 of menu 1 of menu button 1 of group 2 of splitter group 1 of sheet 1 of window 1
        delay 1
        key code 36 --specific to this question. Obviously this would change when selecting one of the other menu options.
    end tell
end tell
© www.soinside.com 2019 - 2024. All rights reserved.