applescriptkeynote

AppleScript Keynote hangup after opening a illegal pptx file


first I am a beginner AppleScript developer. and I have searched this question for a long time but no result found. I have an AppleScript to convert ppt files into pdf format. but the script will hangup after it matches a bad ppt file.

the script/keynote will popup a dialog showing "xxx.ppt can't be opened right now" "the file format is invalid".

is there any way to prevent keynote from popping up this kinds of dialog?

below is the sample code, and file is a image file but I changed extension to pptx to simulate an illegle file:

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

Solution

  • There is a command-line tool called exiftool which can inspect files and get their metadata, including the 'file type' tag (using -filetype). There are a variety of ways to install it†. Unlike 'mdls', it isn't easily fooled by the file extension. If you run it on a pptx file, it will include this in its results:

    File Type                       : PPTX
    

    You can then grab the last word to test. This script will loop through the files in the specified folder, use exiftool to extract their file type, and then copy the alias of any matching file to a new list. It then opens each file in keynote. My version of keynote (v8) doesn't let me script anything with powerpoint documents, so you're on your own at that point.

    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
    

    NB † Depending upon where exiftool is installed, you may need to change the path, which you can get with which exiftool.