This month, we will put into practice what we learned in Part 1 of this five-part series on printing in Java. In Part 1, I
presented the two printing models: the Printable and the Pageable. I also discussed how to use the Book class to create documents. You will start Part 2 by printing your first page; then you will move on to render more complex
documents with Java 2D. In addition, I will explain how to use fonts and all their related classes. And, as promised last
month, I will examine the issues concerning printing on different platforms. Note that all examples were compiled and executed
using Sun Java 1.3 on both Windows 2000 and Linux.
| Printing in Java: Read the whole series! |
|---|
In Part 1, you learned that the print system in Java has two distinct models: the Printable and the Pageable. Though Printable can print simple documents, it features several limitations, the major one being that all pages must share the same format.
The Pageable model, on the other hand, offers much more flexibility. Used in conjunction with the Book class, it can create multipage documents, with each page formatted differently. Listing 1 shows how to print using the Printable model.
Note: All examples, as well as their accompanying source code, can be downloaded from the Resources section below.
Listing 1 will print a half-inch by half-inch grid using the default margin setting, usually one inch for the top, bottom, left, and right margins. Please note that if you try to execute this example with Java 1.2, the margins will not fit; the left margin will be slightly larger than one inch. A bug in Java 1.2's print API causes this glitch.
Now, let's go through the steps required for printing with the Printable model:
PrinterJob object. This object controls the print process by displaying page and print dialogs, and initiating the print action.
Printable interface's print() method.
Graphics parameter.
PAGE_EXISTS value; if the page does not render, return the NO_SUCH_PAGE value.
As you learned from the previous example, printing with Printable is a straightforward process, but doesn't offer much flexibility when it comes to handling more complex documents. For these
types of tasks, the Pageable and the Book classes come in handy. As explained in Part 1 of this series, the Book class allows you to choose whether each Book's page will use a different page painter or the same page painter as other pages. To see the Pageable and the Book at work, let's begin with this example:
Graphics framework for advanced 2D compositionsJava 2D API Graphics, Vincent J. Hardy (Prentice Hall, 1999)Font classFontMetrics classFontRenderContext class