Using AppleScript to batch convert .pages to pdf

I am needing to convert about 100 .pages documents to either pdf or docx. With the AppleScript script below, I am able to open .pages documents from the folder that I select. However I receive the following error when trying to export.

Question: What is causing the error and how do I fix it?

Error Message with personal information replaced:

error "Pages got an error: Can’t make alias \"Macintosh HD:Users:Path:To:File:foo.pages\" into type document." number -1700 from alias "Macintosh HD:Users:Path:To:File:foo.pages." to document

Line of code producing the error:

export this_file to exportFileName as PDF

Script:

set exportFileExtension to "pdf"
set this_folder to (choose folder with prompt "Pick the folder containing the files to process:") as string
tell application "System Events"
    set these_files to every file of folder this_folder
end tell
repeat with i from 1 to the count of these_files
    set this_file to (item i of these_files as alias)
    set this_info to info for this_file
    tell application "Finder"
        set {fType, nExt} to ({file type, name extension} of file this_file)
        set documentName to the name of this_file
        set exportFileName to documentName & "." & exportFileExtension
    end tell
    if nExt contains "pages" then
        tell application "Pages"
            open this_file
            export this_file to exportFileName as PDF
            close saving no
        end tell
    end if
end repeat

###Update###: I have added this script to github with the hopes of it benefiting others as it continues to be improved. Contributions appreciated.


Replace the line of code producing the error with the following:

export front document to file (this_folder & exportFileName) as PDF

There were two issues here:

  • export takes a document, so you need to pass it the document as opened by Pages.
  • You gave the file name, but not a containing folder to put the file with this name, so concatenate this with the containing folder path so Pages knows where to export to.