Printing in Java, Part 1

Acquaint yourself with the Java printing model

1 2 Page 2
Page 2 of 2

Rendering models

There are two printing models in Java: Printable jobs and Pageable jobs.

Printables

Printable jobs are the simpler of the two printing models. This model only uses one PagePainter for the entire document. Pages are rendered in sequence, starting with page zero. When the last page prints, your PagePainter must return the NO_SUCH_PAGE value. The print subsystem will always request that the application render the pages in sequence. As an example, if your application is asked to render pages five through seven, the print subsystem will ask for all pages up to the seventh page, but will only print pages five, six, and seven. If your application displays a print dialog box, the total number of pages to be printed will not be displayed since it's impossible to know in advance the number of pages in the document using this model.

Pageables

Pageable jobs offer more flexibility than Printable jobs, as each page in a Pageable job can feature a different layout. Pageable jobs are most often used with Books, a collection of pages that can have different formats. I will explain the Book class in a moment.

A Pageable job has the following characteristics:

  • Each page can have its own painter. For example, you could have a painter implemented to print the cover page, another painter to print the table of contents, and a third to print the entire document.
  • You can set a different page format for each page in the book. In a Pageable job, you can mix portrait and landscape pages.
  • The print subsystem might ask your application to print pages out of sequence, and some pages may be skipped if necessary. Again, you don't have to worry about this as long as you can supply any page in your document on demand.
  • The Pageable job doesn't need to know how many pages are in the document.

Books

Also new since version 1.2 is the Book class. This class allows you to create multiple-page documents. Each page can have its own format and its own painter, giving you the flexibility to create sophisticated documents. Since the Book class implements the Pageable interface, you could implement your own Book class when the provided Book class lacks the features that you require.

A Book class represents a collection of pages. When first created, the Book object is empty. To add pages, you simply use one of the two append() methods (see my explanation of this class in the API section for more details). This method's parameters are the PageFormat object, which defines the physical characteristics of the page, and a PagePainter object, which implements the Printable interface. If you don't know the number of pages in your document, simply pass the UNKNOWN_NUMBER_OF_PAGES value to the append() method. The printer system will automatically find the number of pages by calling all the page painters in the book until it receives a NO_SUCH_PAGE value.

API definition

Theory and practice will meet in this section. In the previous sections, we learned about page structure, units of measurement, and rendering models. In this section, we will look at the Java printing API.

All of the classes required to print are located in the java.awt.print package, which is composed of three interfaces and four classes. The following tables define the classes and interfaces of the print package.

NameTypeDescription
PaperClassThis class defines the page's physical characteristics.
PageFormatClassPageFormat defines the page's size and orientation. It also defines which Paper to use when rendering a page.
PrinterJobClass

This class manages the print job. Its responsibilities include creating a print job, displaying a print dialog box when necessary, and printing the document.

BookClass

Book represents a document. A Book object acts as a collection of pages. Pages included in the Book can have identical or differing formats and can use different painters.

PageableInterfaceA Pageable implementation represents a set of pages to be printed. The Pageable object returns the total number of pages in the set as well as the PageFormat and Printable for a specified page. The Book class implements this interface.
PrintableInterfaceA page painter must implement the Printable interface. There is only one method in this interface, print().
PrinterGraphicsInterfaceThe Graphics object implements this interface. PrinterGraphics provides the getPrinterJob() method to obtain the printer job that instantiated the print process.

Pageable interface

The Pageable interface includes three methods:

Method nameDescription
int getNumberOfPages()Returns the number of pages in the document.
PageFormat getPageFormat(int pageIndex)Returns the page's PageFormat as specified by pageIndex.
Printable getPrintable(int pageIndex)Returns the Printable instance responsible for rendering the page specified by pageIndex.

Printable interface

The Printable interface features one method and two values:

NameTypeDescription
int print(Graphics graphics, PageFormat pageFormat, int pageIndex)Method

Requests that the graphics handle using the given page format render the specified page.

NO_SUCH_PAGEValueThis is a constant. Return this value to indicate that there are no more pages to print.
PAGE_EXISTSValueThe print() method returns PAGE_EXISTS. It indicates that the page passed as a parameter to print() has been rendered and does exists.

Every page painter must implement the Printable interface. Since there is only one method to implement, creating page painters may seem easy. However, remember that your code must be able to render any page in or out of sequence.

There are three parameters to print(), including Graphics, which is the same class used to draw on the screen. Since the Graphics class implements the PrinterGraphic interface, you can obtain the PrinterJob that instantiated this print job. If your page layout is complex and requires some advanced drawing features, you can cast the Graphics parameter to a Graphics2D object. You will then have access to the full Java 2D API.

Before you start using the Graphics object, note that the coordinates are not translated to the top left corner of the printable area. Refer to Figure 3 to find the location of the default origin.

Figure 3. Printable area origins

(0, 0) appears at the top left corner of the printer margins. To print a 1-by-1-inch rectangle, 1 inch from both top and left margins, you would use the following code:

1:
                                       public int print (Graphics graphics, PageFormat pageFormat, int pageIndex) {
                                       2:   Graphics2D graphics2D = (Graphics2D) graphics;
                                       3:   Rectangle2D.Double rectangle = new Rectangle2D.Double ();
                                       4:   rectangle.setRect (pageFormat.getImageableX () + 72,
                                       5:                      pageFormat.getImageableY () + 72,
                                       6:                      72,
                                       7:                      72);
                                       8:   graphics2D.draw (rectangle);
                                       9:   return (PAGE_EXISTS);
                                       }
                                       
                                      

From the previous example, we see that we must manually translate the origin of the rectangle so that it prints at the top of the printable area as in Figure 1. To simplify the code, we could translate the coordinates once and use (0, 0) as the origin of the printable area. By modifying the previous example, we get:

1: public int print (Graphics
                                       graphics, PageFormat pageFormat, int pageIndex) {     
                                       2:   Graphics2D graphics2D = (Graphics2D) graphics;
                                       3:   graphics2D.translate (pageFormat.getImageableX (), pageFormat.getImageableY ()); 
                                       4:   Rectangle2D.Double rectangle = new Rectangle2D.Double ();
                                       5:   rectangle.setRect (72, 72, 72, 72);
                                       6:   graphics2D.draw (rectangle);
                                       7:   return (PAGE_EXISTS);
                                       8: }
                                       
                                      

Using the translate() method in line 3, we can translate the coordinates and set our origin (0, 0) at the top of the printable area. From this point on, our code will be simplified.

PrinterGraphics interface

The PrinterGraphics interface consists of one method:

Method nameDescription
PrinterJob getPrinterJob()Returns the PrinterJob for this rendering request and is implemented by the Graphics class

Paper class

Eight methods make up the Paper class:

Method nameDescription
double getHeight()This method returns the page's physical height in points (1 inch = 72 points). For example, if you are printing on a letter-size page, the return value will be 792 points, or 11 inches.
double getImageableHeight()This method returns the page's imageable height. The imageable height is the height of the print area that you may draw on. See Figure 1 for a graphical view of the imageable area.
double getImageableWidth()This method returns a page's imageable width (the width of the print area that you may draw on). See Figure 1 for a graphical view of the imageable area.
double getImageableX()This method returns the x origin of the imageable area. Since there is no support for margins, the return value represents the left margin.
double getImageableY()This method returns the y origin of the imageable area. The value returned from this method is equivalent to the top margin.
double getWidth()This method returns the page's physical width in points. If you print on a letter-size paper, the width is 8.5 inches, or 612 points.
void setImageableArea(double x, double y, double width, double height)This method sets the imageable area and specifies the margins on the page. Actually, the API provides no method to set the margins explicitly; you have to calculate them yourself.
void setSize(double width, double height)This method sets the physical page size. To define an 8.5-by-11-inch sheet, you would supply 612 and 792 points. Note that the default size is LETTER.

Before we move on to the next section, remember that the Paper class defines the page's physical characteristics. The PageFormat class represents all the page's characteristics, such as page orientation, size, and the paper type. This class is always passed as a parameter to the Printable interface's print() method. Use Paper to obtain the imageable area location, size, and page orientation along with a transformation matrix.

PageFormat class

The PageFormat consists of 12 methods:

Method nameDescription
double getHeight()This method returns the page's physical height in points (1 inch = 72 points). If your page measures 8.5 by 11 inches, then the return value will be 792 points, or 11 inches.
double getImageableHeight()This method returns the page's imageable height, which is the height of the print area on which you may draw. See Figure 1 for a graphical view of the imageable area.
double getImageableWidth()This method returns the page's imageable width -- the width of the print area on which you may draw. Figure 1 illustrates a graphical view of the imageable area.
double getImageableX()This method returns the x origin of the imageable area.
double getImageableY()This method returns the imageable area's y origin.
double getWidth()This method returns the page's physical width in points. If you print on letter-sized paper, the width is 8.5 inches, or 612 points.
double getHeight()This method returns the page's physical height in points. For example, letter-sized paper is 11 inches in height, or 792 points.
double[] getMatrix()This method returns a transformation matrix that translates user space into the requested page orientation. The return value is in the format required by the AffineTransform constructor.
int getOrientation()This method returns the orientation of the page as either PORTRAIT or LANDSCAPE.
void setOrientation(int orientation)This method sets the orientation of the page, using the constants PORTRAIT and LANDSCAPE.
Paper getPaper()This method returns the Paper object associated with the page format. Refer to the previous section for a description of the Paper class.
void setPaper(Paper paper)This method sets the Paper object that will be used by the PageFormat class. PageFormat must have access to the physical page characteristics to complete this task.

This concludes the description of the page classes. The next class that we will study is the PrinterJob.

PrinterJob class

The PrinterJob class controls the printing process. It can both instantiate and control a print job. Below you will find a definition of the class:

Method nameDescription
abstract void cancel()This method cancels the current print job. You can validate the cancellation with the isCancel() method.
abstract boolean isCancelled()This method returns true if the job is cancelled.
PageFormat defaultPage()This method returns the default page format for the PrinterJob.
abstract PageFormat defaultPage(PageFormat page)This method clones the PageFormat passed in parameters and modifies the clone to create the default PageFormat.
abstract int getCopies()This method returns the number of copies that the print job will print.
abstract void setCopies(int copies)This method sets the number of copies that the job will print. Note that if you show a print dialog box, users can alter the number of copies (see the pageDialog method).
abstract String getJobName()This method returns the job name.
static PrinterJob getPrinterJob()This method creates and returns a new PrinterJob.
abstract String getUserName()This method returns the user name associated with the print job.
abstract PageFormat pageDialog(PageFormat page)This method displays a dialog that allows the user to modify the PageFormat. The PageFormat, passed in parameters, sets the fields of the dialog. If the user cancels the dialog, then the original PageFormat will be returned. But if the user accepts the parameters, then a new PageFormat will be created and returned. Since it will not show the same parameters on all operating systems, you must be careful when using the pageDialog.
abstract void setPageable(Pageable document)This method queries the document to obtain the total number of pages. The Pageable will also return the PageFormat and the Printable object for each page. See the definition of the Pageable interface for more information.
abstract void setPrintable(Printable painter)This method sets the Painter object that will render the pages to be printed. A Painter object is an object that implements the Printable class and its print() method.
abstract void setPrintable(Printable painter, PageFormat format)This method completes the same tasks as abstract void setPrintable(Printable painter), except that you supply the PageFormat that the Painter will use. As indicated in the definition of the Printable interface, the print() method passes a PageFormat object as the first parameter.
abstract void print()This method prints the document. It actually calls the print() method of the Painter previously assigned to this print job.
abstract void setJobName(String jobName)This method sets the name of the print job.
abstract boolean printDialog()This method displays a print dialog box that allows the user to change the print parameters. Note that this interaction's result will not be returned to your program. Instead, it will be passed to the peer operating system.
abstract PageFormat validatePage(PageFormat page)This method will validate the PageFormat passed in parameters. If the printer cannot use the PageFormat that you supplied, then a new one that conforms to the printer will be returned.

Book class

Seven methods make up the Book class:

>

Method nameDescription
void append(Printable painter, PageFormat page)This method appends a page to the Book. The painter and the PageFormat for that page are passed in parameters.
void append(Printable painter, PageFormat page, int numPages)This method completes the same tasks as void append(Printable painter, PageFormat page), except that you specify the number of pages.
int getNumberOfPages()This method returns the number of pages currently in the Book.
PageFormat getPageFormat(int pageIndex)This method returns the PageFormat object for a given page.
Printable getPrintable(int pageIndex)This method returns the painter for a given page.
void setPage(int pageIndex, Printable painter, PageFormat page)This method sets the painter and the PageFormat for a given page already in the book.

The printing recipe

The recipe for printing is very simple. First, create a PrinterJob object:

 PrinterJob
                                       printJob = PrinterJob.getPrinterJob
                                                                              ();
                                                                           
                                      

Next, using the setPrintable() method of the PrinterJob, assign the Painter object to the PrinterJob. Note that a Painter object is one that implements the Printable interface.

 printJob.setPrintable (Painter);
                                                                           
                                      

Or you could set the PageFormat along with the Painter :

 printJob.setPrintable
                                                                              (Painter, pageFormat);
                                                                           
                                      

Finally, the Painter object must implement the print() method:

public int
                                                                              print (Graphics g, PageFormat pageFormat, int page)
                                                                           
                                      

Here the first parameter is the graphics handle that you will use to render the page, the pageFormat is the format that will be used for the current page, and the last parameter is the page number that must be rendered.

That's all there is to it -- for simple printing, that is.

Introduction to the framework

The print framework that we will build in this series will be completely independent of the Java printing API. It will allow for greater flexibility in producing different outputs. Its structure will allow you to create documents, pages, and print objects. You will be able to add print objects to a page while adding pages to a document. By using this structure, you will be able to easily implement export features to PDF or HTML files, or print directly to the printer using the print API. But the main goal of the framework is to simplify the creation of printed documents. When you print using the print API, you only end up with a graphic canvas to draw on. It fails to address the concepts of paragraphs, images, drawings, graphics, tables, or running headers and footers. Because you must compute the (x, y) origin, the width and height of the printable area, setting margins is a chore. Our print framework will address all of these weaknesses.

Conclusion

We covered a lot of ground in this first part. We looked at measurement units, the structure of page, the two rendering models (Pageable and Printable), and Books, and we concluded with a detailed explanation of the printing API. Next month, we'll focus primarily on code, as we will be putting everything into practice. We will also look at the issues that arise when printing on multiple platforms. Looking ahead to Part 3, I will explain in detail the design and implementation of the framework.

Jean-Pierre Dube is an independent Java consultant. He founded Infocom in 1988. Since then, Infocom has developed custom applications in fields including manufacturing, document management, and large-scale electrical power line management. Jean-Pierre has extensive programming experience in C, Visual Basic, and Java; the latter is now the primary language for all new projects. He dedicates this series to his mother, who passed away while he was writing this article.

Learn more about this topic

1 2 Page 2
Page 2 of 2