Printing Multipage Text Documents

The printing examples we’ve seen so far print GUI components on a single page. Printing multipage documents is more interesting, but also trickier, because we have to decide where to place the page breaks. Example 13-4 shows how this can be done. This HardcopyWriter class is a custom stream that uses the Java 1.1 Printing API to print the characters sent through it, inserting line breaks and page breaks as necessary.

The HardcopyWriter class includes two demonstration programs as inner classes. The first, PrintFile, reads a specified text file and prints it by sending its contents to a HardcopyWriter stream. The second, Demo, prints a demonstration page that shows off the font and tabbing capabilities of the class, as shown in Figure 13-4.

Demonstration page printed by HardcopyWriter

Figure 13-4. Demonstration page printed by HardcopyWriter

Example 13-4 is long but worth studying. In addition to demonstrating the Java 1.1 Printing API again, it shows an approach to paginating a text document. It is also a useful example of a custom Writer stream.

Example 13-4.

package je3.print; import java.awt.*; import java.awt.event.*; import*; import java.text.*; import java.util.*; /** * A character output stream that sends output to a printer. **/ public class HardcopyWriter extends Writer { // These are the instance variables for the class protected PrintJob ...

Get Java Examples in a Nutshell, 3rd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.