首页 > 解决方案 > 打开非法 pptx 文件后 AppleScript Keynote 挂断

问题描述

首先,我是一名 AppleScript 开发人员。我已经搜索了这个问题很长时间,但没有找到结果。我有一个 AppleScript 可以将 ppt 文件转换为 pdf 格式。但是脚本会在匹配错误的 ppt 文件后挂断。

脚本/主题演讲将弹出一个对话框,显示“xxx.ppt 现在无法打开”“文件格式无效”。

有什么方法可以防止主题演讲弹出这种对话框?

下面是示例代码,文件是图像文件,但我将扩展名更改为 pptx 以模拟 illegle 文件:

set thefile to POSIX file "/Users/dazhangluo/Downloads/brain-storming.pptx"
tell application "Keynote"
    activate
    try
        set thedoc to open thefile

        --display dialog class of thedoc
    on error errMessage
        --display dialog errMessage
        log errorMessage
    end try
end tell

标签: applescriptkeynote

解决方案


有一个名为的命令行工具exiftool可以检查文件并获取它们的元数据,包括“文件类型”标签(使用-filetype)。有多种安装方式†。与“mdls”不同,它不容易被文件扩展名欺骗。如果您在 pptx 文件上运行它,它将在结果中包含以下内容:

File Type                       : PPTX

然后,您可以抓住最后一个单词进行测试。此脚本将遍历指定文件夹中的文件,使用 exiftool 提取其文件类型,然后将任何匹配文件的别名复制到新列表中。然后它会在 keynote 中打开每个文件。我的 keynote (v8) 版本不允许我使用 powerpoint 文档编写任何脚本,因此此时您只能靠自己了。

set srcFol to (path to desktop as text) & "presentations" as alias
-- or if you prefer…
-- set srcFol to choose folder 

tell application "Finder"
    
    set fList to files of srcFol as alias list
    set cleanList to {}
    repeat with f in fList
        set ppFile to POSIX path of f
        set qfFile to quoted form of ppFile
        tell me to set exifData to do shell script "/usr/local/bin/exiftool -filetype " & qfFile
        if last word of exifData is "PPTX" then
            set end of cleanList to contents of f
            --> alias "Mac:Users:username:Desktop:presentations:powerpoint1.pptx"
        end if
    end repeat
end tell

tell application "Keynote"
    activate
    repeat with pptxFile in cleanList
        open pptxFile
        -- do whatever
    end repeat
end tell

注意 † 根据 exiftool 的安装位置,您可能需要更改路径,您可以使用which exiftool.


推荐阅读