Search code examples
javascriptmacosautomatormacos-mojavejavascript-automation

How can an image be saved with JavaScript for Automator (JXA) in macOS Preview application?


There is an image open in the Preview application, and it is unsaved.

I have tried this code, by building and running a standalone script in Script Editor:

var preview = Application('Preview')
var preview.documents[0].close({ saving: true, savingIn: '/Volumes/USB Drive/Untitled-Image.png' })

I see this in the logs

app = Application("Preview")
    app.documents.at(0).Symbol.toPrimitive()
        --> Error -1700: Can't convert types.
    app.documents.at(0).Symbol.toPrimitive()
        --> Error -1700: Can't convert types.

However, I'm not sure I'm reading the docs correctly, and I'm not sure how to further debug this code. A satisfactory alternative here would be to send a keystroke to save and click the Save button.

What can I do to persist the image in Preview to a file?


Solution

  • One can declare paths speculatively in JavaScript using Path('...'), and then use the save command to save the image to the file that will be created at that path:

    Preview = Application('com.apple.Preview');
    ImageFilepath = Path('/Users/CK/Pictures/Preview_SavedImage.jpg');
    Preview.documents[0].save({ in: ImageFilepath });