Printing: Java 2

Problem

You need to generate hardcopy, and you’re using Java 2.

Solution

Use java.awt.print.PrinterJob.

Discussion

Like its predecessor, the Java 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 will be sent to that printer (if there isn’t a default printer, I don’t know what happens). Unlike the 1.1 API, however, Java is in charge of what to print and in what order, though 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 Section 8.8). In this example, we pass an anonymous inner class (see Section 8.7); this is not required but as usual 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 more efficient than the 1.1 method, since if the user wants to print only page 57, you only get called once to print that page (in 1.1, you’d have to generate the intervening 56 pages and have the print system discard them). 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 Section 5.11).

The screen shots in Figure 12-6 apply equally to this version of the program. And the source code is similar; see Example 12-6.

Example 12-6. PrintDemoGfx (Java 2 version)

import java.awt.*;
import java.awt.event.*;
import java.awt.print.*;
import javax.swing.*;

/** PrintDemoGfx -- Construct and print a GfxDemoCanvas. Java 2 VERSION. */
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 Java 2 API has other useful methods in the PrinterJob class; see the documentation. There are also Paper , PageFormat, and Book classes that 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.

Another means of printing is to directly generate PostScript files or Acrobat PDF files. See Recipes Section 9.21 and Section 18.6 for these alternate paths to printing.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.212.160