Printing Playground Documents #swiftlang

Damian Esteban (@estebanrules) writes: In relation to Swift and PDFs, is it possible to “print” a Playground with markup rendered to a PDF or Postscript file? I could have sworn it used to work fine for me, but lately when I’ve done it, the markup doesn’t show in the PDF.

Xcode’s ability to create and present multi-page rich-text playground documents is one of its stand-out features for Swift development. These playgrounds enable you to document APIs, teach algorithms, and more, all within the scope of a standard Xcode window.

Unfortunately, in Xcode’s current state, you cannot print a playground. A playground that looks like this:

Screen Shot 2015-10-31 at 3.13.34 PM

Prints output that looks like this:

Screen Shot 2015-10-31 at 3.14.13 PM

All the nice formatting and text disappears and you’re left with raw code.

There is a way around this although it’s not particularly nice. Simply put, you can write an Xcode plug-in that renders the fully expressed playground timeline scroll view instead of code. Here’s what that looks like:

Screen Shot 2015-10-31 at 3.15.48 PM

And here’s the code that I used to build the plug-in. The rest of the work is left as an exercise for the reader but it basically goes like this: find an Xcode plugin template on github, add a menu item, add its implementation, add the Xcode UUID, install, run.

- (void) printTimeline
  NSWindow *window = [NSApp mainWindow];
  NSArray *subviews = 
    // recursive descent

  for (NSView *view in subviews) {
    if ([NSStringFromClass([view class]) 
      NSScrollView *scrollView = 
        (NSScrollView *) view;
      NSPrintOperation *printOperation = 
        [NSPrintOperation printOperationWithView:
      NSPrintInfo *printInfo = 
        [printOperation printInfo];
      printInfo.horizontalPagination = 
     [printOperation runOperation];

One Comment

  • Thank you, I appreciate it. Maybe not the nicest way to do it but it’s easy enough. I’ve found marked up Playgrounds to be excellent cheatsheets and I’m going to keep a small arsenal of them as PDFs ready to go.