Recipe 13.11 Printing in Java


You need to generate hardcopy.


Use java.awt.print.PrinterJob.


The JDK 1.2 Printing API makes you divide the data into pages. Again, you start by getting a PrinterJob object to control your printing. You'll usually want to let the user pick a printer, which you do by calling the PrinterJob's method printerDialog( ) . This pops up a platform-specific print chooser dialog, and if the user picks a printer, you get back a PrinterJob object (otherwise, again, you get back null). If you don't call printerDialog( ) and there is a default printer, your job is sent to that printer (if there isn't a default printer, I don't know what happens). Unlike the 1.1 Printing API, however, Java is in charge of what to print and in what order, although your program is still responsible for pagination and drawing each page onto a print buffer. You need to provide an object that implements the Printable interface (see Recipe 9.7). In this example, we pass an anonymous inner class (see Recipe 9.6); this is not required, but as usual, it makes the code more succinct by eliminating having to write another class in another file and by keeping the action and the result together. Java calls this object's print( ) method once for each page the user has requested. This is efficient because if the user wants to print only page 57, you get called only once to print that page. Note that the official documentation calls the third argument a pageIndex, but it's really a page number. Trust me. Presumably it's called a pageIndex to remind you that in some printing jobs (such as this book), there are unnumbered pages and pages with those funny little roman numerals at the front (see Recipe 5.11).

The source code is shown in Example 13-6. The screenshots in Figure 13-7 show this program in action.

Example 13-6. PrintDemoGfx
import java.awt.*; import java.awt.event.*; import java.awt.print.*; import javax.swing.*; /** PrintDemoGfx -- Construct and print a GfxDemoCanvas. */ public class PrintDemoGfx {     /** Simple demo main program. */     public static void main(String[] av) throws PrinterException {         final JFrame f = new JFrame("Printing Test Dummy Frame");         // Construct the object we want to print. Contrived:         // this object would already exist in a real program.         final GfxDemoCanvas thing = new GfxDemoCanvas(400, 300);         f.getContentPane( ).add(thing, BorderLayout.CENTER);         JButton printButton = new JButton("Print");         f.getContentPane( ).add(printButton, BorderLayout.SOUTH);         printButton.addActionListener(new ActionListener( ) {             public void actionPerformed(ActionEvent e) {                 try {                     PrinterJob pjob = PrinterJob.getPrinterJob( );                     pjob.setJobName("DemoGfx - Graphics Demo Printout");                     pjob.setCopies(1);                     // Tell the print system how to print our pages.                     pjob.setPrintable(new Printable( ) {                         /** called from the printer system to print each page */                         public int print(Graphics pg, PageFormat pf, int pageNum) {                             if (pageNum>0)        // we only print one page                                 return Printable.NO_SUCH_PAGE;    // ie., end of job                             // Now (drum roll please), ask "thing" to paint itself                             // on the printer, by calling its paint( ) method with                              // a Printjob Graphics instead of a Window Graphics.                             thing.paint(pg);                             // Tell print system that the page is ready to print                             return Printable.PAGE_EXISTS;                         }                     });                     if (pjob.printDialog( ) == false)    // choose printer                         return;                // user cancelled                     pjob.print( );             // Finally, do the printing.                 } catch (PrinterException pe) {                     JOptionPane.showMessageDialog(f,                         "Printer error" + pe, "Printing error",                         JOptionPane.ERROR_MESSAGE);                 }             }         });         f.pack( );         f.setVisible(true);     } }

See Also

The Printing API has other useful methods in the PrinterJob class; see the documentation. Paper , PageFormat, and Book classes describe a physical page, a page by size and orientation, and a collection of pages, respectively.

Both Java printing APIs require you to think in "page mode." That is, you must know where the page breaks are and request the start of each new page. This is optimal for graphically oriented programs, and less optimal for "report writing" applications; handling pagination for yourself can become quite a tedium. See the HardCopyWriter class in O'Reilly's Java Examples in a Nutshell for code that neatly paginates and prints plain text.

Figure 13-7. PrintDemoGfx program in action

Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: