    001    package com.hammurapi.bnf2emf;
    002
    003    import java.awt.Component;
    004    import java.awt.Graphics;
    005    import java.awt.Graphics2D;
    006    import java.awt.print.PageFormat;
    007    import java.awt.print.Printable;
    008    import java.awt.print.PrinterException;
    009    import java.awt.print.PrinterJob;
    010
    011    import javax.swing.RepaintManager;
    012
    013    public class ComponentPrinter implements Printable {
    014            private Component componentToBePrinted;
    015
    016            public static void printComponent(Component c) {
    017                    new ComponentPrinter(c).print();
    018            }
    019
    020            public ComponentPrinter(Component componentToBePrinted) {
    021                    this.componentToBePrinted = componentToBePrinted;
    022            }
    023
    024            public void print() {
    025                    PrinterJob printJob = PrinterJob.getPrinterJob();
    026                    printJob.setPrintable(this);
    027                    if (printJob.printDialog())
    028                            try {
    029                                    printJob.print();
    030                            } catch (PrinterException pe) {
    031                                    System.out.println("Error printing: " + pe);
    032                            }
    033            }
    034
    035            public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
    036                    if (pageIndex > 0) {
    037                            return (NO_SUCH_PAGE);
    038                    }
    039
    040                    Graphics2D g2d = (Graphics2D) g;
    041                    g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
    042                    disableDoubleBuffering(componentToBePrinted);
    043                    componentToBePrinted.paint(g2d);
    044                    enableDoubleBuffering(componentToBePrinted);
    045                    return (PAGE_EXISTS);
    046            }
    047
    048            public static void disableDoubleBuffering(Component c) {
    049                    RepaintManager currentManager = RepaintManager.currentManager(c);
    050                    currentManager.setDoubleBufferingEnabled(false);
    051            }
    052
    053            public static void enableDoubleBuffering(Component c) {
    054                    RepaintManager currentManager = RepaintManager.currentManager(c);
    055                    currentManager.setDoubleBufferingEnabled(true);
    056            }
    057    }