Saturday, February 4, 2012

Printing in Java

Printing in Java is something I have not done previously. In order to print using Java, I would have to implement the Printable and ActionListener class.

The code and examples for printing in java can be found in the Oracle website.

Printing has to be done using the Graphics class

Steps to printing in Java

There are basically two tasks that must be done for printing
1) The first task is for creating the jobs that must be printed. What items needs to be printed and the number of copies and associations with a printer
2) Drawing the content of the page must be done as the second step in order to print


1) Importation of a Print class must be done.  PrintJob is what is going to be used to print the items In Java

import java.awt.print.*;

That must be done in order for the print functions to work

PrinterJob pj = PrinterJob.getPrinterJob();

Now the statement above will return a PrinterJob that is associated with the default printer. As it is an abstract class, PrinterJob will not be able to initialized. Hence, the statement above is a way to get  PrinterJob object.

The printable class is an interface that is implemented by the print methods.
It will be used by using Printable.print(..)


TIP: Ensure that Graphics g and PageFormat pf has the correct syntax and capitalization. As Pageformat is obviously different than PageFormat but its easy to miss sometimes.


When using the Printable, the PageFormat object must be used as well. This class is used for the page orientation, size, imaginable units.


  public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
     
        /* We want to only print the first page so anything above zero
         * is not required
         */
        if (pageIndex > 0 ) {
            return NO_SUCH_PAGE;
        }
        /* We have to translate the X and Y values in the PageFormat
         * to avoid clipping
         */
     
        Graphics2D g2d = (Graphics2D)graphics;
        g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
     
        graphics.drawString("Hello World!", 100, 100);
     
        return PAGE_EXISTS;
     
    }

Notice that
Graphics2D g2d = (Graphics2D) graphics;
where Graphcis2D g2d is an abstract class.

No comments:

Post a Comment