java.awt.PrintJob
class
PrintJob pj =
Toolkit.getDefaultToolkit().getPrintJob(new Frame(),
"Hello World", null);
This returns a platform specific subclass of the PrintJob
class.
The first thing you'll want to do with this object is determine the characteristics of the printer. There are three methods for this:
public abstract int getPageResolution()
public abstract Dimension getPageDimension()
public abstract boolean lastPageFirst()
The getPageResolution()
method
returns the number of dots per inch of thee printer,
typically 300 or 600 for most laser printers. getPageDimension()
returns a java.awt.Dimension
object giving the size of the printable area of the page in pixels (not inches!). For example, the following code fragment prints the total number of pixels on the page:
PrintJob pj = Toolkit.getPrintJob();
int resolution = pj.getPageResolution();
Dimension d = pg.getPageDimension();
System.out.println("There are " + (resolution * d.width * d.height)
+ " pixels on a page.");
Finally lastPageFirst()
returns true if the last page will be printed first, false otherwise.
You use this information to prepare your image to be drawn on the page.
depending on the size of the page and the type of the image, you may need
to spilt it across multiple pages. Sometimes it's easier to just draw
the entire image on each page, but use clipRect()
to set the fraction
of the image to actually be drawn.
The drawing itself is done with a java.awt.Graphics
object
like the one you use in the paint()
method of an applet. This is returned by getGraphics()
, and has all the usual method of the Graphics
class,
drawLine()
, drawString()
, and so on.
public abstract Graphics getGraphics()
There's one important caveat: Unilke the Graphics objects passed
as arguments to a paint()
method, this object does not
intially have a font set. You'll generally want to set its font
before using it like this:
Font courier = new Font("Courier", Font.PLAIN, 12);
g.setFont(courier);
When you're done with a PrintJob
call its end()
method to perform any necessary flushing and clean up.
public abstract void end()