import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.ServiceUI;
import javax.print.SimpleDoc;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.event.PrintJobAdapter;
import javax.print.event.PrintJobEvent;
import javax.print.event.PrintJobListener;
public class PrintExample
{
public static void main(String args[]) throws Exception
{
DocFlavor flavor = DocFlavor.BYTE_ARRAY.JPEG;
PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
DocPrintJob job = printService.createPrintJob();
PrintJobListener listener = new PrintJobAdapter()
{
public void printDataTransferCompleted(PrintJobEvent e)
{
System.out.println("Druck beendet");
System.exit(0);
}
};
job.addPrintJobListener(listener);
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
DocAttributeSet das = new HashDocAttributeSet();
ServiceUI.printDialog(null, 300, 300, new PrintService[]{printService}, printService, flavor, pras);
Doc doc = new SimpleDoc(createPrintImage(), flavor, das);
job.print(doc, pras);
Thread.sleep(5000);
}
private static byte[] createPrintImage()
{
BufferedImage p = new BufferedImage(300, 300, BufferedImage.TYPE_INT_RGB);
Graphics2D g = p.createGraphics();
g.setColor(Color.white);
g.fillRect(0, 0, 300, 300);
g.setColor(Color.BLACK);
g.drawString("Hallo ich bins der Test!", 50, 50);
g.drawOval(90, 90, 100, 100);
ByteArrayOutputStream bous = new ByteArrayOutputStream();
try
{
ImageIO.write(p, "jpeg", bous);
bous.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return bous.toByteArray();
}
}