1 package com.explosion.utilities;
2
3 import java.awt.Component;
4 import java.awt.Graphics;
5 import java.awt.Graphics2D;
6 import java.awt.print.PageFormat;
7 import java.awt.print.Printable;
8 import java.awt.print.PrinterException;
9 import java.awt.print.PrinterJob;
10
11 import javax.swing.RepaintManager;
12
13 import org.apache.log4j.LogManager;
14 import org.apache.log4j.Logger;
15
16 /***
17 * A simple utility class that lets you very simply print an arbitrary
18 * component. Just pass the component to the PrintUtilities.printComponent. The
19 * component you want to print doesn't need a print method and doesn't have to
20 * implement any interface or do anything special at all.
21 * <P>
22 * If you are going to be printing many times, it is marginally more efficient
23 * to first do the following:
24 *
25 * <PRE>
26 *
27 * PrintUtilities printHelper = new PrintUtilities(theComponent);
28 *
29 * </PRE>
30 *
31 * then later do printHelper.print(). But this is a very tiny difference, so in
32 * most cases just do the simpler
33 * PrintUtilities.printComponent(componentToBePrinted).
34 *
35 * 7/99 Marty Hall, http://www.apl.jhu.edu/~hall/java/ May be freely used or
36 * adapted.
37 */
38
39 public class PrintUtilities implements Printable
40 {
41
42 private static Logger log = LogManager.getLogger(PrintUtilities.class);
43
44 private Component componentToBePrinted;
45
46 public static void printComponent(Component c)
47 {
48 new PrintUtilities(c).print();
49 }
50
51 public PrintUtilities(Component componentToBePrinted)
52 {
53 this.componentToBePrinted = componentToBePrinted;
54 }
55
56 public void print()
57 {
58 PrinterJob printJob = PrinterJob.getPrinterJob();
59 printJob.setPrintable(this);
60 if (printJob.printDialog()) try
61 {
62 printJob.print();
63 } catch (PrinterException pe)
64 {
65 log.debug("Error printing: " + pe);
66 }
67 }
68
69 public int print(Graphics g, PageFormat pageFormat, int pageIndex)
70 {
71 if (pageIndex > 0)
72 {
73 return (NO_SUCH_PAGE);
74 } else
75 {
76 Graphics2D g2d = (Graphics2D) g;
77 g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
78 disableDoubleBuffering(componentToBePrinted);
79 componentToBePrinted.paint(g2d);
80 enableDoubleBuffering(componentToBePrinted);
81 return (PAGE_EXISTS);
82 }
83 }
84
85 /***
86 * The speed and quality of printing suffers dramatically if any of the
87 * containers have double buffering turned on. So this turns if off
88 * globally.
89 *
90 * @see enableDoubleBuffering
91 */
92 public static void disableDoubleBuffering(Component c)
93 {
94 RepaintManager currentManager = RepaintManager.currentManager(c);
95 currentManager.setDoubleBufferingEnabled(false);
96 }
97
98 /*** Re-enables double buffering globally. */
99
100 public static void enableDoubleBuffering(Component c)
101 {
102 RepaintManager currentManager = RepaintManager.currentManager(c);
103 currentManager.setDoubleBufferingEnabled(true);
104 }
105 }