macosapplescript

Adding multiple images and text to Pages via Applescript


I need to automate adding multiple images with title text to an Apple Pages document. My assumption is that I need to use AppleScript to do this.

So far I've tried things like the following:

tell application "Pages"
    if the front document exists then
        set aDoc to the front document
    else
        set aDoc to make new document
    end if
    activate
    tell aDoc
        tell front page
            set titleOne to "Title One"
            set body text to titleOne
            set image1Path to POSIX file "/path/to/images/image_0.png"
            make new image with properties {file:image1Path}
            
            set titleTwo to "Title Two"
            set body text to titleTwo
            set image2Path to POSIX file "/path/to/images/image_1.png"
            make new image with properties {file:image2Path}
        end tell
    end tell
end tell

However, this just overwrites the title text and overlays the images instead of putting one after the other. I've also tried using paragraphs, but all my attempts at that result in errors of one form or another.

Does anyone know how I might accomplish this?


Solution

  • There are two problems with the script as given:

    1. Every set body text to… command overwrites the body text property entirely. If you want to use the body text property, you have to concatenate new text into it.

    2. Objects need to have their position property set, otherwise they will all be placed in the center of the page.

    The easiest way to accomplish this is to ignore the body text property and use text item objects instead, then position everything sequentially like so:

    set image1 to POSIX file "/path/to/images/image_0.png"
    set image2 to POSIX file "/path/to/images/image_1.png"
    
    tell application "Pages"
        activate
        
        if the front document exists then
            set aDoc to the front document
        else
            aDoc to make new document
        end if
        
        tell aDoc
            tell front page
                set textItem1 to make new text item with properties {object text:"Title One", position:{10, 10}, height:20}
                set imageItem1 to make new image with properties {file:image1, position:{10, my findVerticalPlacement(textItem1)}}
                set textItem2 to make new text item with properties {object text:"Title Two", position:{10, my findVerticalPlacement(imageItem1)}, height:20}
                set imageItem2 to make new image with properties {file:image2, position:{10, my findVerticalPlacement(textItem2)}}
            end tell
        end tell
    end tell
    
    to findVerticalPlacement(lastObject)
        tell application "Pages"
            return (item 2 of (position of lastObject as point)) + (height of lastObject as integer) + 10
        end tell
    end findVerticalPlacement