AppleScript – Pages export to PDF fails due to Sandbox permissions

applescriptautomatorpagespdfpermission

I'm trying to create an Automator workflow to export selected Pages documents to PDF. So far, everything goes well, except for the final export step.

on run {input, parameters}
    repeat with _document in input

        tell application "Finder"
            set _directory to get container of file _document

            set _documentName to name of _document
            if _documentName ends with ".pages" then ¬
                set _documentName to text 1 thru -7 of _documentName

            set _PDFName to _documentName & ".pdf"
            set _incrementIndex to 1
            repeat until not (exists file _PDFName of _directory)
                set _PDFName to ¬
                    _documentName & "-" & (_incrementIndex as string) & ".pdf"
                set _incrementIndex to _incrementIndex + 1
            end repeat

            set _location to (_directory as string) & _PDFName
        end tell

        --set _location to (POSIX file of _location)

        tell application "Pages"

            activate
            open _document

            with timeout of 1200 seconds
                export front document to file _location as PDF
            end timeout

            close front document

        end tell

    end repeat
    return input
end run

This gives me a Sandbox permissions error.

error   17:49:38.117966 +0100   sandboxd    SandboxViolation: Pages(3846) deny file-write-create /Users/brunoscheele/Desktop/Test.pdf
Violation:       deny file-write-create 

After reading up on it here, it looked like I could fix this by changing _location to a POSIX file.

So I added;

--set _location to (POSIX file _location)

However, that then gives me the error:

Pages got an error: "macOS:Users:brunoscheele:Desktop:Test.pdf" could not be interpreted as a file URL.

Using export front document to (POSIX file _location) as PDF gives me the same error.

Does anyone know how to set the _location properly, so you don't run into permission issues?

Best Answer

Try adding this line before your exporting step:

open for access file _location

I'm guessing you're using macOS Sierra. This is a known issue. I could only make my code work by using the above step before my export started. Make sure you don't put that line inside a tell block.