CONTENTS | PREV | NEXT Java 2D API


7.2 Printing a Simple Book

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:

  1. Implement the Printable interface, providing a print method that performs the actual drawing on the pages.
  2. Create a Book.
  3. Call append to add pages to the Book.
  4. Create a PrintJob object by calling getPrintJob on the current GraphicsEnvironment.
  5. Call print on the PrintJob.
In the following example:


7.2.1 NumberPainter

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);
}
}

7.2.2 SimplePrint

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);
}
}


CONTENTS | PREV | NEXT
Copyright © 1997-1998 Sun Microsystems, Inc. All Rights Reserved.