How To: Print A Page

To print a page from a Java application or applet, you must supply a method that draws text and graphics -- like Applet's public void paint(Graphics g), which draws to an on-screen window. The printing method is public int print(Graphics g, PageFormat fmt, int page). The PageFormat object tells the method details about the printer's page size, orientation, and color capabilties. The int is a zero-based page number -- the system calls this method with a page number specified, so the method knows which page of a multi-page document to print.

The printing interface can be improved by adding the Pageable interface, which tells the system how many pages there are in the document. The example below prints a page.


package myStuff;

import java.awt.*;
import java.awt.print.*;

public class PrintTest
{
  public static void main(String[] argv) throws Exception
  {
    // instructions for what to print on each page
    final Printable pr = new Printable()
    {
      public int print(Graphics g, PageFormat fmt, int page)
      {
        if (page != 0) // print page #0 only
          return NO_SUCH_PAGE;

        g.setColor(Color.blue);
        g.drawOval(100, 100, 200, 200);
        g.drawString("Hello, Printer", 150, 200);

        return PAGE_EXISTS;
      }
    };

    // specifies how many pages that there are
    final Pageable pa = new Pageable()
    {
      public int getNumberOfPages(){return 1;} // a one-page document
      public PageFormat getPageFormat(int pageIndex)
        throws IndexOutOfBoundsException
        {return PrinterJob.getPrinterJob().defaultPage();}
      public Printable getPrintable(final int pi)
        throws IndexOutOfBoundsException{return pr;}
    };

    // show printer dialog and print if not cancelled
    PrinterJob pj = PrinterJob.getPrinterJob();
    pj.setPrintable(pr); // tells what to print
    pj.setPageable(pa); // tells #of pages
    if (pj.printDialog())
      pj.print();
    System.exit(0);
  }
}