import java.awt.event. ActionEvent;
import java.awt.event. ActionListener;
import java.awt.print. Book;
import java.awt.       Graphics;
import java.awt.       Graphics2D;
import javax.swing.    JEditorPane;  
import java.awt.print. PageFormat;
import java.awt.print. Printable;
import java.awt.print. PrinterException;
import java.awt.print. PrinterJob;
import java.awt.       Rectangle;
public class JEditorPanePrinter implements Printable, ActionListener
{
   private JEditorPane iJEditorPane;
   private Rectangle iRectangle;
   private double iScale;
   public JEditorPanePrinter(final JEditorPane pJEditorPane)
   {
      iJEditorPane = pJEditorPane;
   }
   public int print(final Graphics pGraphics, final PageFormat pPageFormat,
                    final int pPageIndex) throws PrinterException
   {
      final Graphics2D tGraphics2D = (Graphics2D)pGraphics;
      tGraphics2D.translate(pPageFormat.getImageableX(),
                            pPageFormat.getImageableY());
      tGraphics2D.scale(iScale, iScale);
      tGraphics2D.translate(-iRectangle.x, -iRectangle.y);
      iJEditorPane.paint(tGraphics2D);
      return Printable.PAGE_EXISTS;
   }
   public void actionPerformed(final ActionEvent pActionEvent)
   {
      final PrinterJob tPrinterJob = PrinterJob.getPrinterJob();
      final PageFormat tPageFormat =
                          tPrinterJob.pageDialog(tPrinterJob.defaultPage());
      iRectangle = new Rectangle(iJEditorPane.getWidth(),
                                 iJEditorPane.getHeight());
      final double tX = tPageFormat.getImageableWidth()/iRectangle.width;
      final double tY = tPageFormat.getImageableHeight()/iRectangle.height;
      iScale = Math.min(tX, tY);
      // Use the next three lines of code because:
      //    tPrinterJob.setPrintable((Printable)this, tPageFormat);
      // does not seem to work.
      final Book tBook = new Book();
      tBook.append((Printable)this, tPageFormat);
      tPrinterJob.setPageable(tBook);
      if(tPrinterJob.printDialog())
      {
         try
         {
            tPrinterJob.print();
         }
         catch (Exception pException)
         {
         }
      }
   }
}
