AWT - SPLessons

AWT Printing

Chapter 19

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

AWT Printing

AWT Printing

shape Introduction

The current chapter gives an overview on AWT Printing concepts. The following topics are covered in AWT Printing chapter:

  • Printing
  • Requisites for printing.

shape Description

AWT Printing gives graphical components of applications as the output. It is followed in two steps.

To perform these actions, classes, interfaces and methods are required.

shape Conceptual
figure

Job Control

shape Description

Initially, a job is created for printer. This creation is done by involving classes that are present in java.awt.print package.

PrinterJob job = PrinterJob.getPrinterJob();

Printable interface

shape Description

The printable interface consists of single method only.

public int print(Graphics graphics,PageFormat pf, int page) throws PrinterException;

Now, attach the content to the Printable interface, which implements the code.

class SplessonsPrinter implements Printable {
...
}
...
job.setPrintable(new SplessonsPrinter());

PrinterJob Class

shape Description

Then, a dialog box appears requesting to adjust as per the requirement like a number of copies, page setup, and printer selection.

boolean doPrint = job.printDialog();

If requested to start the printing, the PrinterJob.print() method is called.

if (doPrint)
{
try
{
job.print();
}
catch (PrinterException e)
{
// The job did not successfully
// complete
}
}

PageFormat Class

shape Description

PageFormat Class class gives the information about size of a page, orientation and imageable area where the content is placed within the borders.

PrintGraphics Interface

shape Description

This interface is used to print the graphical objects. This is done by calling the getGraphics() method of the PrinterJob through Toolkit. Further, printComponents() method is called before the final paint() method is returned. Sometimes paint() is modified, which defines the context.

shape Examples

import java.awt.*;
import java.awt.print.*;
import java.io.*;
import java.util.Vector;

public class Splesson implements Pageable, Printable {
  // Constants for font name, size, style and line spacing
  public static String FONTFAMILY = "Monospaced";
  public static int FONTSIZE = 10;
  public static int FONTSTYLE = Font.PLAIN;
  public static float LINESPACEFACTOR = 1.1f;

  PageFormat format;   // The page size, margins, and orientation
  Vector lines;        // The text to be printed, broken into lines
  Font font;           // The font to print with
  int linespacing;     // How much space between lines
  int linesPerPage;    // How many lines fit on a page
  int numPages;        // How many pages required to print all lines
  int baseline = -1;   // The baseline position of the font

  /** Create a Splesson object for a string of text */
  public Splesson(String text, PageFormat format) throws IOException { 
    this(new StringReader(text), format); 
  }

  /** Create a Splesson object for a file of text */
  public Splesson(File file, PageFormat format) throws IOException { 
    this(new FileReader(file), format); 
  }

  /** Create a Splesson object for a stream of text */
  public Splesson(Reader stream, PageFormat format) throws IOException {
    this.format = format;

    BufferedReader in = new BufferedReader(stream);
    lines = new Vector();
    String line;
    while((line = in.readLine()) != null) 
      lines.addElement(line);

    // Create the font we will use, and compute spacing between lines
    font = new Font(FONTFAMILY, FONTSTYLE, FONTSIZE);
    linespacing = (int) (FONTSIZE * LINESPACEFACTOR);

    // Figure out how many lines per page and how many pages
    linesPerPage = (int)Math.floor(format.getImageableHeight()/linespacing);
    numPages = (lines.size()-1)/linesPerPage + 1;
  }

  // These are the methods of the Pageable interface.
  // Note that the getPrintable() method returns this object, which means
  // that this class must also implement the Printable interface.
  public int getNumberOfPages() { return numPages; }
  public PageFormat getPageFormat(int pagenum) { return format; }
  public Printable getPrintable(int pagenum) { return this; }

  /* This is the print() method of the Printable interface.*/
  public int print(Graphics g, PageFormat format, int pagenum) {
    // Tell the PrinterJob if the page number is not a legal one
    if ((pagenum = numPages)) 
      return NO_SUCH_PAGE;

    // figure out the baseline for our font.
    // We couldn't do this earlier because we needed a Graphics object.
    if (baseline == -1) {
      FontMetrics fm = g.getFontMetrics(font);
      baseline = fm.getAscent();
    }
    g.setColor(Color.white);
    g.fillRect((int)format.getImageableX(), (int)format.getImageableY(),
               (int)format.getImageableWidth(), 
               (int)format.getImageableHeight());

    // Note that you cannot assume that black is the default color!
    g.setFont(font);
    g.setColor(Color.black);

    // Figure out which lines of text we will print on this page
    int startLine = pagenum * linesPerPage;
    int endLine = startLine + linesPerPage - 1;
    if (endLine >= lines.size()) 
      endLine = lines.size()-1;

    // Compute the position on the page of the first line
    int x0 = (int) format.getImageableX();
    int y0 = (int) format.getImageableY() + baseline;

    // Loop through the lines, drawing them all to the page
    for(int i=startLine; i  0) 
        g.drawString(line, x0, y0);

      // Move down the page to the next line
      y0 += linespacing;  
    }

    // Tell the PrinterJob that we have successfully printed the page
    return PAGE_EXISTS;
  }

  /* This is a test program that demonstrates the use of Splesson*/
  public static void main(String[] args) throws IOException, PrinterException {
    // Get the PrinterJob object that coordinates everything
    PrinterJob job = PrinterJob.getPrinterJob();

    // Get the default page format, then ask the user to customize it
    PageFormat format = job.pageDialog(job.defaultPage());

    // Create our Splesson object, and tell the PrinterJob about it
    job.setPageable(new Splesson(new File(args[0]), format));

    // Ask the user to select a printer, and if not canceled, print!
    if (job.printDialog()) 
      job.print();
  }
}

Output

Summary

shape Description

  • Printing gives Graphical components.
  • PageFormat Class gives the information about size of a page, orientation and imageable area.