In this third part of a five-part series on printing in Java, I will explain the design of the print framework. This framework will work on top of the API to ease the burden of creating printed output. With it, you will be able to create pages with running headers/footers, and insert paragraphs, images, and tables. The coding phase will begin in Part 4 and continue into Part 5. We have a lot of ground to cover, so let's start.
Printing in Java: Read the whole series!
Goals of the print framework
In Parts 1 and 2, you had the opportunity to examine in detail the Java Print API. With this knowledge, you are now able to evaluate its strengths and weaknesses and build a framework on top of it. That framework will compensate for the lack of high-level features in the Java Print API.
The print framework will:
- Be easy to use.
- Provide the high-level functionality required to efficiently render pages.
- Loosely couple with the Print API. Because the framework has no direct ties to the Java Print API, it will allow greater support for other output formats, such as PDF or HTML.
- Provide a structure that clearly defines each component involved in creating documents (document, page, paragraph, and so on).
- Use an abstract measurement system. Developers will thus be able work with the measurement system of their choice or even create their own. The framework will provide three default units of measurements: inches, centimeters, and points.
- Provide a print-preview facility. The Java Print API has no support for previewing the output before you print.
- Support a standard and portable page-setup dialog. As mentioned in Part 2, even though Java has been categorized as a WORA (Write Once, Run Anywhere) language, its functionality varies from platform to platform. The print framework will provide one page-setup dialog that will be uniform across all platforms.
- Offer export features. Although the framework will support several output formats (PDF, HTML, Postscript), their implementation is beyond the scope of this series. I leave the implementation up to you.
- Offer text handling, which is of primary importance. The framework will provide all the functionality needed to effectively render text, including right justification, left justification, full justification, and support for the
- Support graphics primitives such as rectangles, circles, and lines.
- Support GIF and JPEG image types.
- Support headers and footers. These can be set at the document or the page level, and the first page can feature a different header/footer.
- Support sticky position, which easily sticks a component to a specific location. As an example, let's assume that you want to center an object in a page. Instead of doing all the math yourself, you can set the vertical and horizontal sticky value to a
CENTERvalue; the framework centers the object within its parent container -- in this case, the page. Since all print objects are containers, the sticky values would be applied within the boundaries of the parent object.
- Support sticky dimensions, with which you can set a component's width and/or height to the parent container's width and/or height.
- Support tables, though their implementation will be limited.
In addition, all print objects are containers in the print framework.
A detailed look at the framework
To better understand the design of the framework, select UML Diagram 1 below:
The diagram shows a hierarchical structure. Starting from the top of the hierarchy, you will find a
PFDocument object that contains
PFPage objects that contain any objects that are instances of
PFPrintObject, where each
PFPrintObject can contain other
PFPrintObjects. If you got lost in the above explanation, take a look at Figure 1, which presents a better view of the print framework's structure. A closer look at the print objects reveals that the design is based on the composite pattern. I present more on the composite pattern later.
The following sections will explain in detail the print framework's design; I begin with the universal measurement system.
Universal measurement system
An important feature of the print framework is that it supports conventional measurement units. Most of us prefer working with inches or centimeters, rather than with points or pixels. I created an abstract class called
PFUnit to define the basic functionality required to convert from a given measurement system to points.
I also created three classes that implement the
PFPointUnit. With these classes, you can work with your preferred unit of measurement. You can also create your own measurement system by subclassing
PFUnit. When using these classes, you will use two methods:
setUnit(), to set a value in the measurement system, and
getPoints(), to get the value converted into points.
Using classes to represent numbers, instead of the standard double, float, or integer types, can cause problems when performing calculations. Another drawback to using classes is the lack of operator overloading in the Java language. To alleviate this problem, I added all the basic math operations to the
PFUnit class. In this way, we preserve the encapsulation of data while providing basic math operations. As an example, let's add 2 inches to a
PFInchUnit of 3 inches. You could complete that task in the non-object-oriented way:
PFInchUnit inch = new PFInchUnit (3.0); inch.setUnit (new PFInchUnit (2.0).getUnit () + inch.getUnit ());
Or, by using the built-in math methods, you could do it like so:
PFInchUnit inch = new PFInchUnit (3.0); inch = inch.add (2.0);
I created three other classes to complement the measurement system:
PFPoint, which represents an X,Y point
PFSize, which represents the size of an object
PFRectangle, which represents a rectangle area
All of the above classes use the
The PFDocument class
PFDocument class is located at the top of the hierarchy in the print framework library. The class acts as a page container and provides the necessary functionality to handle the print and export processes. This class also offers some methods related to document-handling.
PFDocument class, you can set headers and footers for a whole document using the
setHeader()/setFooter() methods. You can set a different header/footer for the first page by using the
setFirstPageHeader() and the
PFDocument also includes a print-preview window. By calling the
printPreview() method, a print-preview window will display. I will discuss the preview window in further detail later.
One of the goals of the print framework is to provide functionality for exporting documents to formats other than paper. Since the print framework model is totally independent of the output, it's possible to export to any format. To export your document to such formats as HTML or PDF, use either the
printPDF() or the
printHTML() methods. Note that these methods appear in the design but have not been implemented yet. I leave their implementation to you.
PFDocument offers several other methods to set document properties. For example, with
setDocumentName() you can set a document's name, which will identify your document in the host operating system's print queue. The print-preview window also uses the document name to identify your document in the window's title bar. Finally the
showPageDialog() methods will show the appropriate dialog. Note that the page dialog called by
showPageDialog() does not originate in the Java Print API. I decided to implement my own page dialog after I tried printing on different platforms and discovered that page dialogs vary from platform to platform.
Now that you know about the functionality implemented by the
PFDocument class, let's dive into the print method's details. Take a look at UML Diagram 2 below.
As shown in this diagram, the messages flow between each component when the
PFDocument print() method is called. The
PFDocument will instantiate the print job. It will first create a
Book object and will enter in a loop to add all of the document pages to the
PFDocument completes the loop,
PrinterJob print() is called, and the Java Print API handles the rest of the printing process.
The following sections will elaborate on each object's role in the print framework. I begin these explanations with the
Next in the hierarchy, the
PFPage class defines a page and acts as a container for objects that will be rendered on it. Each page in the print framework can have its own format. There is no limit to the number of objects that you can add to a page.
Each page can either have its own header/footer or use the one defined in the
PFDocument class. How does the print framework decide which header/footer to use? First, the page checks if its own header/footer is
null. If so, it will try to obtain the header/footer from the
PFDocument object. If the header/footer has a non-
null value, the page will use the document header/footer. Note that the document has two methods,
getFooter(), that handle the logistics of supplying the appropriate header/footer. The header/footer value is based on the value of the first page header/footer and whether or not the page under consideration is the first one.
PFPage class also contains two important methods,
getPrintableAreaOrigin() provides the location of the printable area's top left corner, which is determined by the margins, the gutter, and the height of the page header.
getPrintableAreaSize(), on the other hand, returns the printable area's size. Figure 2 illustrates the printable area origin and the printable area size.
PFPage must implement the
Printable interface, which Part 1 explains.
You are now ready to see how the framework handles the print objects.
Understand the PFPrintObject
The design of the print object architecture is based on the composite pattern. I decided to use that pattern after considering the following: Suppose you wish to draw a circle in the middle of a rectangle with a drawing program. You decide to group these two objects together to form one object so that you can move, resize, copy, and delete the objects as a whole. But how does a good object-oriented program handle such a feature?
You could create container object and another object that is a graphics primitive. Your program would have to differentiate between these two distinct objects and treat them accordingly. I've tried this approach before, and the results were buggy and hard to maintain.
Instead, I suggest using a composite pattern. It ensures uniform access to all graphics objects. Because each graphics object also acts as a container, no difference exists between a container object and a graphics primitive object. The same objects handle all functionality. The composite structure will produce a hierarchy of objects.
Figure 3 illustrates how the composite pattern works.
Figure 3 shows that you can create a complex object composition with only one type of object. You can also group objects together with the composite pattern, and even group together several groups of objects. By using the pattern, you simplify the framework's design considerably.
The composite pattern is also easy to expand; you can create your own print objects by extending the
PFPrintObject. Since all the basic functionality is located in one place, expanding the
PFPrintObject gives your extended objects all the container functionality as well as sticky positioning, sticky fill, and the rendering of all child objects.
To see how this pattern would help solve a real-world problem, consider the following example. Let's say you want to build a page header as shown in Figure 4.
To build the header, you could draw everything by hand and work out the math necessary to position each component. Or you could take advantage of the
PFPrintObject's container feature.
By examining the structure of the page header, you see that the master object contains everything. Two paragraph objects are added to the master object. The first paragraph object will print the string
"Printing in Java". That object will have the following properties set:
verticalSticky = CENTER,
horizontalSticky = LEFT. The second paragraph object will contain the string
"Page nn", with the properties
verticalSticky = CENTER and the
horizontalSticky = RIGHT. Finally, we add a line object with the following properties:
verticalSticky = BOTTOM,
horizontalSticky = CENTER, and
horizontalFill = TRUE. Don't forget to set a margin around the main component to ensure that everything centers within the header area. Refer to Figure 5 to see where everything will fit.