CONTENTS | PREV | NEXT | Java 2D API |
In the simplest case, a document can be printed without allowing the user to specify any page setup or printing parameters. To do this, you:
In the following example:
- A separate class, NumberPainter, implements the Printable interface and provides the code for drawing a page number on each page. The page number is painted with a red-white gradient.
- In SimplePrint, main is implemented to create a Book and append two pages to the Book, using the default page format. A PrintJob is then obtained from the from the GraphicsEnvironment and PrintJob.print is called to print the Book.
import Java.awt.*
import Java.awt.geom.*;
import Java.awt.print.*;
class NumberPainter implements Printable {
private static final int INCH = 72;
private static Font times = new Font("SansSerif", Font.BOLD,
INCH * 3);
private Paint redToWhitePaint = new GradientPaint(0.0f, 0.0f,
Color.red, INCH/2, INCH/2, Color.white,true);
public void print(Graphics graphics) {
PageContext pageContext = (PageContext) graphics;
int number = pageContext.getPageIndex() + 1;
graphics.setPaint(redToWhitePaint);
graphics.setFont(times);
graphics.drawString(Integer.toString(number),
(float)INCH * 4, (float)INCH * 4);
}
}
import Java.lang.*;
import Java.awt.*;
import Java.awt.print.*;
public class SimplePrint {
public static void main(String[] args) {
/* Create a new book with two pages all using
* the same PageFormat and Printable instance.
*/
Book book = new Book();
book.append(new PageFormat(), new NumberPainter(), 2);
/* Get a print job from the graphics environment and
* tell it to print our book of two pages.
*/
PrintJob job = GraphicsEnvironment.getLocalGraphicsEnvironment().getPrintJob();
job.print(book);
System.exit(0);
}
}