package SesameGUI;

import java.awt.*;
import javax.swing.*;
import java.awt.print.*;

import javax.print.*;
import java.io.*;

public class PrintUtilities implements Printable {
  private Component componentToBePrinted;
  private String    fileName;

  public static void printComponent(Component c , String fname) {
    new PrintUtilities(c , fname).print();
  }
  
  public PrintUtilities(Component componentToBePrinted , String fname) {
    this.componentToBePrinted = componentToBePrinted;
    this.fileName = fname;
  }
  
  public void print() {
    String psMimeType = DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType();

    PrinterJob pj = PrinterJob.getPrinterJob();
    StreamPrintServiceFactory[] factories =	PrinterJob.lookupStreamPrintServices(psMimeType);
  if (factories.length == 0) 
    {	
    System.err.println("No suitable factories");	
    return;
    }

  try   
    {
    FileOutputStream fos = new FileOutputStream(fileName);	
    StreamPrintService sps = factories[0].getPrintService(fos);	
    pj.setPrintService(sps);	
    PageFormat pf=pj.defaultPage();	
    Paper p=new Paper();	
    p.setSize(210*72d/25, 297*72d/25);	
    p.setImageableArea(10*72d/25,30*72d/25, 190*72d/25,277*72d/25);	
    pf.setPaper(p);
    pj.setPrintable(this , pf);	
    pj.print();
    } 
  catch (Exception x) 
    {
    }
  }

  public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
    if (pageIndex > 0) {
      return(NO_SUCH_PAGE);
    } else {
      Graphics2D g2d = (Graphics2D)g;
      g2d.translate(pageFormat.getImageableX() , pageFormat.getImageableY());

      Rectangle r = componentToBePrinted.getBounds();
      double    sc;

      sc = r.width / (pageFormat.getImageableWidth() + pageFormat.getImageableX());

      if (r.height / (pageFormat.getImageableHeight() + pageFormat.getImageableY()) < sc)
        sc = r.height / (pageFormat.getImageableHeight() + pageFormat.getImageableY());
      
      g2d.scale(sc , sc);
      g2d.clipRect(0 , 0 , r.width , r.height);

      disableDoubleBuffering(componentToBePrinted);
      componentToBePrinted.paint(g2d);
      enableDoubleBuffering(componentToBePrinted);
      return(PAGE_EXISTS);
    }
  }

  public static void disableDoubleBuffering(Component c) {
    RepaintManager currentManager = RepaintManager.currentManager(c);
    currentManager.setDoubleBufferingEnabled(false);
  }

  public static void enableDoubleBuffering(Component c) {
    RepaintManager currentManager = RepaintManager.currentManager(c);
    currentManager.setDoubleBufferingEnabled(true);
  }
}

