Sample program to print Hello World to printer using java swing and java.awt.print.PrinterJob
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import
java.awt.print.PageFormat;
import
java.awt.print.Printable;
import
java.awt.print.PrinterException;
import
java.awt.print.PrinterJob;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class PrinterJob {static public void main(String args[]){
JPanel panel = new JPanel();
JLabel label = new JLabel();
label.setFont(new Font("Serif",Font.PLAIN,14));
label.setText("Hello World");
panel.add(label);
panel.setPreferredSize(new Dimension(200,75));
JFrame frame = new JFrame("Panel Printer test");
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
printComponenet(panel);
System.exit(0);
}
public static void printComponenet(final Component component){
PrinterJob pj = PrinterJob.getPrinterJob();
pj.setJobName(" Print Component ");
pj.setPrintable (new Printable() {
public int print(Graphics pg, PageFormat pf, int pageNum){
if (pageNum > 0){
return Printable.NO_SUCH_PAGE;
}
Graphics2D g2 = (Graphics2D) pg;
g2.translate(pf.getImageableX(), pf.getImageableY());
component.paint(g2);
return Printable.PAGE_EXISTS;
}
});
if (pj.printDialog() == false)
return;
try {
pj.print();
} catch (PrinterException ex) {
ex.printStackTrace();
}
System.out.println("Printing
done.");
}
}