Code Examples in Keynote
I use Apple Keynote for my conference presentations (Keynote competes with PowerPoint for those of you stuck running a legacy operating system). I like to think pretty presentations somewhat detract from my horrid speaking abilities. Up until recently, every time I adjusted my presentation theme for the latest conference, I had a hell of a time bringing my code examples along. The code font would get blown away when I applied the new masters. Sometimes I needed to invert the text color. Retaining color highlights within the code examples made the process even more tedious. Not to mention, maintaining code inside of a presentation is a royal pain in and of itself (how do you test code embedded in a document?).
I approached Stu Halloway (another Keynote user) with the issue when we spoke at The Agency last week. Stu confessed that he used the cut & paste method--his code, treated as an image, is black on white and seemingly immune to theme adjustments. Unfortunately, I neglected to inquire about the details of Stu's process and in practice failed to convince Keynote to treat code as a graphic. Plus, I'd still have the problem with testing and updating my examples.
After some toying around, I discovered that Keynote treats PDF files as images; drag the PDF into your presentation from the Finder, and Keynote inserts it as a picture. All I needed was a tool to convert arbitrary text files (my code examples) into PDF files.
I cranked out a BeanShell script that converts all of my source files to PDFs using iText (thanks for the tip, Hani). I embed simple hints in code comments (for example,
//BOLD makes the next line bold), and my script renders the PDF appropriately.
Next, I drag the generated PDF from the Finder into my presentation, and Keynote treats it as a vector image. As is often the case in OS X, a Keynote document is really just a directory. Inside your Keynote document's directory, you will find your generated PDF files intact.
From now on, if I need to change the color scheme or make a change to an example, I simply run my script which regenerates all of the PDF files, and I copy them into my Keynote document's directory. Now I can maintain my example code as plain Java source files, which in turn means I can compile and test from the comfort of my IDE. No more monotonous code formatting marathons.
In the process, I also discovered that Keynote uses a well documented XML format. Oh, the possibilities.