Automate print to PDF using AppleScript and Pages

Oct 16, '08 07:30:03AM

Contributed by: kd4ttc

There are times that it would be nice to automate the creation of PDF files. For example, one might want a workflow to open a file, change some paragraphs, and print to PDF. This would seem a simple thing, but I haven't found a way to script the Print to PDF functionality. However, the Pages app in the iWork suite will do it for you.

As an example, the following AppleScript will use {ages to print to PDF:

tell application "Pages"
    set product to make new document
    set first paragraph of product to "Hello, I love you, could you tell me your name?"
    save product in "test1.rtf"
    save product in "test2.rtf"
    save product in "test3.pdf"
    save product in "test4.txt"
end tell
Some interesting things to note about the above code. First, the file test3.pdf will be created as a PDF. It seems Pages figures out what you want, and you get a PDF. test2.rtf and test4.txt will be created as RTF and pure text files, which is also useful. However, the file test1.rtf never gets created -- instead, you get a Pages document named test1.rtf.pages. It seems Pages takes the first save as saving the document, then runs the subsequent saves in the proper format. Even if you use the as "rtf" construct in the AppleScript, Pages still saves the file as a Pages document. The workaround here is to have a template document which you open, then do the save into another file:
tell application "Pages"
    open file "test6.pages"
    set product to front document
    set first paragraph of product to "Fee, fii, foo, fum!"
    save product in "test6.pdf"
end tell
Of course, all of the above examples save the files at the root directory level -- full AppleScript paths would be needed to put the files where you want. This method is a valuable way to automate the creation of PDF files with the combination of Pages and AppleScript.

Comments (8)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20081013154417292