The PrintComponent_Class.java file allows an end user to specify setup properties for the page and print the text in the document that is currently open in the Printing application. The PrintComponent_Class file uses the classes of the java.awt.Print package to specify and set the properties of the document to be printed.
Listing 4-5 shows the PrintComponent_Class.java file:
Listing 4-5: The PrintComponent_Class.java File
import java.awt.*; import java.awt.print.*; import java.awt.geom.*; import javax.swing.*; class PrintComponent_Class implements Printable { private Component component; PrinterJob printJob = PrinterJob.getPrinterJob(); PageFormat pageFormat= printJob.defaultPage(); public static void printComponent(Component c) { new PrintComponent_Class(c).print(); } public PrintComponent_Class(Component component) { this.component= component; } /* Set up the page and print. */ public void pageSetupAndPrint() { pageFormat = printJob.pageDialog(pageFormat); printJob.setPrintable(this, pageFormat); if (printJob.printDialog()) { try { printJob.print(); } catch(PrinterException pe) { System.out.println("Error in printing !!! " + pe); } } } /* Print the page. */ public void print() { printJob.setPrintable(this, pageFormat); if (printJob.printDialog()) { try { printJob.print(); } catch(PrinterException pe) { System.out.println("Error in printing !!! " + pe); } } } public int print(Graphics g, PageFormat pf, int pageIndex) throws PrinterException { Graphics2D g2 = (Graphics2D)g; Dimension d = component.getSize(); //get size of document double componentWidth = d.width; //width in pixels double componentHeight = d.height; //height in pixels double pageHeight = pf.getImageableHeight(); //height of printer page double pageWidth = pf.getImageableWidth(); //width of printer page double scale = pageWidth/componentWidth; int pages = (int)Math.ceil(scale * componentHeight / pageHeight); /* Do not print empty pages. */ if(pageIndex >= pages) { return Printable.NO_SUCH_PAGE; } /* Shift Graphic to line up with beginning of print-imageable region */ g2.translate(pf.getImageableX(), pf.getImageableY()); /* shift Graphic to line up with beginning of next page to print. */ g2.translate(0f, -pageIndex*pageHeight); /* Scale the page so that the width fits. */ g2.scale(scale, scale); /* Repaint the page. */ component.paint(g2); return Printable.PAGE_EXISTS; } }
Download this listing.
The above listing invokes the PrintComponent_Class.java file when the end user selects the Page Setup and Print menu option. The PrintComponent_Class.java file defines the print() and pageSetupAndPrint() methods to print and specify the page setup properties of the document to be printed. PrintComponent_Class.java uses the PageFormat and PrinterJob classes of Java to print the text in the document.