13.3. Power Printing
In this section, I'll cover two important printing topics:
Integrating printing into an existing application
I'll show how to add printing support to a simple Swing application. Along the way, I'll develop a simple class that can print any screen component.[4]
[4] Well, it prints any screen component that defines a paint() method. Heavyweight components cannot be printed this way.
Printing more than one page
If you know that all the pages you'll print have the same PageFormat, you can use the Printable interface to print more than one page. If your needs are more sophisticated, the java.awt.print.Pageable interface keeps track of multiple pairs of PageFormats and Printables. It can be used to associate a different PageFormat with each page of a print job. The java.awt.print.Book class is a convenient implementation of the Pageable interface.
13.3.1. Printing User Interface Components
The Printing API makes it easy to add printing capabilities to an existing application. After all, the print() method in the Printable interface can easily call the paint() method of a user interface component.
It's so simple that it can be done in 36 lines of code:
import java.awt.*; import java.awt.print.*; import javax.swing.JComponent; public class ComponentPrintable implements Printable { private Component mComponent; public ComponentPrintable(Component c) { mComponent = c; } public int print(Graphics g, PageFormat pageFormat, int pageIndex) { if (pageIndex > 0) return ...
Get Java 2D Graphics 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.