Adding Printing Capability

We’ve made our way through a lot in this chapter, and now it’s time for a quick dessert. We haven’t done anything with printing so far. One of Cocoa’s most powerful programming features is that printing is extremely easy. Mac OS X’s Quartz, which is used to display things on the screen, is also used to send images to the printer. If your program can display itself on the screen, it can print. It’s that simple.

As we’ll see in Chapter 15, when an NSView object receives a drawRect: message, the view responds by drawing itself in the current graphics context. Normally, the current graphics context is the screen, and the drawRect: message results in the view’s drawing itself on the computer’s display. But if the current graphics context is the printer, the drawRect: method causes the view to generate instructions that cause itself to be printed. Under normal circumstances, you never send the drawRect: message directly to a view. This message is sent for you by the AppKit when the view needs to display itself. You can force a view to display itself by sending it a display message.

Printing is very similar. To have a view print itself, you just send the view a print: message. This causes the AppKit to display a Print panel (dialog), ask the user which printer he wishes to use, and then create a printer context. The view is then sent a sequence of drawRect: messages, one for each page. The result of the drawing operations is captured and then sent to the printer. ...

Get Building Cocoa Applications: A Step by Step Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.