The Quintessential Printing Program

Note that (0, 0) of the Graphics object is at the top-left of the actual page, outside the printable area. In this example, the Graphics object is translated so that (0, 0) becomes the top-left corner of the printable area.
import java.awt.*; import java.awt.print.*; public class BasicPrint extends JComponent implements Printable { public int print(Graphics g, PageFormat pf, int pageIndex) { if (pageIndex > 0) { return Printable.NO_SUCH_PAGE; } Graphics2D g2d = (Graphics2D)g; g2d.translate(pf.getImageableX(), pf.getImageableY()); drawGraphics(g2d, pf); return Printable.PAGE_EXISTS; } public static void main(String[] args) { PrinterJob pjob = PrinterJob.getPrinterJob(); PageFormat pf = pjob.defaultPage(); pjob.setPrintable(new BasicPrint(), pf); try { pjob.print(); } catch (PrinterException e) { } } }

Comments

7 Feb 2010 - 9:42am by Anonymous (not verified)

I got the best examples which I needed. Thank you very much.

17 Mar 2010 - 6:36am by henry (not verified)

i really enjoyed your tutorial on printdialog please help me with cut,paste and copy in java thanks.

26 Apr 2010 - 12:04am by TotiBayudan (not verified)

I have a java program that print rows in a mysql table. My problem is after printing the first page, the succeeding pages won't print anymore. I would appreciate if someone could help me on this. Thanks.

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.