• Loading
    • How to Print Documents Using Java


      The java.awt.print Application Program Interface (API) enables you to print documents in Java. This API, available in Java2, provides classes and interfaces that enable printing. The methods provided by this API helps you to specify various printing options, such as the orientation of the page and the page or pages to be printed.

      An Overview of Printing in Java2


      The java.awt.print API makes it easy to print documents. The methods and classes provided by the API, help in formatting and printing documents.

      The Architecture of the java.awt.print API:-
      The java.awt.print API provides three interfaces, Printable, Pageable, and PrinterGraphics. The Printable interface is easy to use, but does not enable different page formats for the pages of the document. On the other hand, the Pageable interface enables different page formats for the pages of the document to be printed. The API provides four classes that manage the printing process and enable you to specify printing options, such as the size, orientation, and number of pages. The classes of the java.awt.print API are:
      • PrinterJob
      • PageFormat
      • Book
      • Paper


      The Printing Process in Java2


      The process of printing in Java2 involves:
      • Creating a print controller, which represents an object of the PrinterJob class. This class controls the entire printing process. The PrinterJob class starts the printing process. It can also display a Print Options dialog box to the end user. This dialog box enables the end user to modify the default Print option. When the printing is complete or the end user cancels the print job, the PrinterJob class signals the termination of the printing process.
      • Creating a page formatter that represents an object of the PageFormat class, which handles the formatting of the page to be printed. The page formatter manages the content to be printed on the page and provides the formatted pages to the print controller.
      • Initiating the printing process by displaying the Print dialog box to the end user.
      • Printing the document.
      • Terminating the printing process when printing is complete.




      The PrinterJob Class



      The PrinterJob class is the main class of the java.awt.print API. This class controls the entire printing process, from the initiation to termination. This class:

      • Displays the Page Setup dialog box.
      • Specifies the number of copies to be printed.
      • Prints the document.


      Declaration and Constructor of the PrinterJob Class
      The PrinterJob class extends the Object class. The declaration of the PrinterJob class is:

      public class java.awt.print.PrinterJob extends Object

      The constructor for the PrinterJob class does not take arguments and creates an object of the PrinterJob class. The getPrinterJob method of the PrinterJob class initiates an object of the class. The constructor of the PrinterJob class is:

      public PrinterJob()


      Methods of the PrinterJob Class

      The PrinterJob class provides several methods that help in controlling the printing process. The main methods of the PrinterJob Class are:-

      1. public static PrinterJob getPrinterJob():- Initiates a new object of the PrinterJob class.
      2. public abstract String getUserName():- Returns the name of the end user who initiates the printing process.
      3. public abstract String getJobName():- Returns the name of the document to be printed
      4. public abstract int getCopies():- Returns the number of copies to be printed.
      5. public abstract void SetCopies(int numCopies):- Specifies the number of copies to be printed.
      6. public abstract void cancel():- Cancels the current in-progress print job, this method is not valid if there is no current print job.
      7. public abstract boolean isCanceled():- Returns true if the print job is to be canceled.
      8. public PageFormat defaultPage():- Returns a new PageFormat instance with the default size and orientation.
      9. public abstract PageFormat defaultPage(PageFormat pf):- Returns a copy of the PageFormat instance, pf, after changing the size and orientation of the instance pf to the default values.
      10. public abstract void print() throws PrinterException:- Prints a set of pages and raises PrinterException in case the print operation is aborted.
      11. public abstract boolean printDialog():- Opens a dialog box that enables the end user to change the printing options, such as the number of copies and the range of pages to be printed, and returns false if the end user closes the Print dialog box.
      12. public abstract boolean pageDialog():- Opens a dialog box that enables the end user to change the property of the PageFormat instance, such as the page orientation, and returns false if the end user closes the Page dialog box.
      13. abstract void setPrintable(Printable p):- Calls the Printable object, p, to provide the page, the format of this page is set to the default values.
      14. public abstract void setPrintable (Printable painter, PageFormat pf):- Calls the Printable object painter to provide the page, the PageFormat object, pf, describes the format of the page.
      15. public abstract void setPageable(Pageable doc) throws NullPointerException:- Obtains information about the number of pages, the PageFormat object, and the Printable object associated with each page of the Pageable object doc, and throws an exception if the Pageable object doc is null.
      16. public abstract PageFormat validatePage(PageFormat pf):- Modifies the PageFormat object, pf, so that the current PrinterJob object can use the PageFormat object.


      The PageFormat Class


      The PageFormat class formats various properties, such as the size and orientation, of the page to be printed.

      Declaration and Constructor of the PageFormat Class
      The PageFormat class extends the Object class and implements the Cloneable interface. The declaration of the PageFormat class is:-

      public class java.awt.print.PageFormat extends Object implements Cloneable

      This constructor does not take an argument and creates the default, portrait-oriented PageFormat object. The constructor of the PageFormat class is:

      public PageFormat()

      Methods of the PageFormat Class
      The PageFormat class provides methods to format and obtain the properties of the page to be printed. These properties include the height and orientation of the page. The various methods of the PageFormat class are:-

      1. public Object clone():- Returns a clone of the PageFormat object, which means that this method returns an object with the identical orientation and size as the PageFormat object.
      2. double getHeight():- Returns the height of the page as specified in the PageFormat object.
      3. double getImageableHeight():- Returns the height of the imageable area of the page as specified in the PageFormat object.
      4. double getWidth():- Returns the width of the page as specified in the PageFormat object.
      5. double getImageableWidth():- Returns the width of the imageable area of the page.
      6. double getImageableY():- Returns the y-coordinate of the upper-left corner of the imageable area of the page.
      7. double[] getMatrix():- Returns a transformation matrix that corresponds the user space translation to the orientation of the page. The transformation matrix maps the coordinates in the user space to the screen coordinates.
      8. int getOrientation():-Returns one of the predefined orientation values depending on the orientation of the page associated with the PageFormat object. The predefined orientation values are LANDSCAPE, REVERSE_LANDSCAPE, and PORTRAIT.
      9. void setOrientation(int orientation) throws IllegalArgumentException:-Sets the orientation of the page to one of the predefined orientation values. Throws IllegalArgumentException in case the value of the orientation parameter is not set to one of the predefined values.
      10. Paper getPaper():- Returns a copy of the Paper object associated with the PageFormat object. The Paper object stores information, such as the height and width, of the paper used for printing.
      11. void setPaper(Paper paper):- Sets the Paper object as specified by the paper parameter of the PageFormat object.




      In the LANDSCAPE orientation, the origin is at the lower-left corner of the page. The x coordinate increases from bottom to top and the y coordinate increases from left to right. In the PORTRAIT orientation, the origin is at the upper-left corner of the page. The x coordinate increases from left to right and the y coordinate increases from top to bottom. In the REVERSE_LANDSCAPE orientation, the origin is at the upper-right corner of the page. The x coordinate increases from top to bottom and the y coordinate increases from right to left.

      Code for Methods of the PageFormat and PrinterJob Classes

      Code:
      /* methodsDemo.java*/
      import java.awt.*;
      import java.awt.print.*;
      class pagePainter implements Printable
        {
          public int print(Graphics g, PageFormat pf,int pageIndex)
          // A demo method implementation: does not do any printing
                 {
                   if (pageIndex>1)return NO_SUCH_PAGE;
                g.drawString("Printed",100,100);
                  /*put something on the paper*/
                  return Printable.PAGE_EXISTS;
                 }
        }
      
      public class methodsDemo
        {
            public static void main(String args[])
          {
            pagePainter p = new pagePainter();
            //An object of the pagePainter class is created
            PrinterJob pj = PrinterJob.getPrinterJob();
            //An object of the PrinterJob class is created using
            //the getPrinterJob() method
             PageFormat pf = pj.defaultPage();
             /* the defaultPage() method is used to get the object of the PageFormat */
             pj.pageDialog(pf);
             pf.setOrientation(PageFormat.LANDSCAPE);
             /*the pageDialog() method is called to show the Page Setup dialog box*/
             pj.setPrintable(p);
             /*The use of the setPrintable() method. An object of the Printable class is passed   as the parameter*/
             pj.setJobName("Demonstrating methods ");
             System.out.println("Parameter of the Imageable Area of the Default Page");
             System.out.println("X (Left): " +pf.getImageableX() +"  Y (Top): "   +pf.getImageableX());
             System.out.println("Width: " +pf.getHeight() +"Height: " +pf.getWidth());
             pj.pageDialog(pf); 
             /*if the user accepts printing*/
              if(pj.printDialog())
                     {
                     try
                            {
                        System.out.println("Printing: " + pj.getJobName() + 
                        /* get the name of the printing job; Java Printing is the default name*/
                                " initiated by "+ pj.getUserName());
                              /* get the name of the user who initiated the printing job*/
                     pj.print();// call the print method
                    }
                         catch (PrinterException pe) { System.out.println(pe); }
                     }
            }
        }
      The output of this code is the Page Setup and the Print dialog boxes.





      The Paper Class



      This class stores information about the dimensions and margins of the paper used for printing. The methods of this class modify the size of the paper being used.

      Declaration and Constructor of the Paper Class

      The Paper class extends the Object class and implements the Cloneable interface. The declaration of the Paper class is:

      public class java.awt.print.Paper extends Object implements Cloneable


      The constructor does not take arguments and creates a letter size paper with a one-inch margin. The constructor of the Paper class is:

      public Paper()

      Methods of the Paper Class

      The Paper class provides various methods to obtain and set the dimensions of the paper used for printing. The methods of the Paper class are:-

      1. public Object clone():-Returns a clone of the Paper object.
      2. public double getHeight():-Returns the height of the Paper object.
      3. public double getWidth():- Returns the width of the Paper object.
      4. public void setSize(double width, double height):- Sets the width and height of the Paper object as specified by the parameters.
      5. public double getImageableX():- Returns the x-coordinate of the upper-left corner of the imageable area of the Paper object.
      6. public double getImageableWidth():- Returns the width of the imageable area of the Paper object.
      7. public double getImageableHeight():- Returns the height of the imageable area of the Paper object.
      8. public void setImageableArea(double x, double y, double width, double height):- Specifies the imageable area of the Paper object. The parameters, x and y, specify the upper-left corner of the imageable area. The width and height parameters specify the width and height.


      The Book Class



      The Book class stores information about a collection of pages that can have different page formats. This class enables the use of different page painters for different pages.

      Declaration and Constructor of the Book Class
      The Book class extends the Object class and implements the Pageable interface. The declaration of the Book class is:

      public class java.awt.print.Book extends Object implements Pageable

      The constructor does not take arguments and creates an empty Book object that does not contain pages. The constructor of the Book class is:-

      public Book()

      Methods of the Book Class
      The main method of the Book class is the append method that adds a page to the Book object. The methods of the Book class are as follows:-

      1. public void append(Printable painter, PageFormat pf):- Appends a page to the end of the Book object. The painter and pf parameters store information about the Printable and PageFormat objects associated with the page.
      2. public void append(Printable painter, PageFormat pf, int num):- Appends num number of pages to the end of the Book object. The painter and pf parameters describe the Printable and PageFormat objects associated with the pages.
      3. public PageFormat getPageFormat(int pageIndex) throws IndexOutOfBoundsException:- Returns the PageFormat object associated with the page specified by the pageIndex parameter of the book class. This method throws IndexOutOfBoundException, in case pageIndex is out of the range of the Book object.
      4. public int getNumberOfPages():- Returns the number of pages in the document.
      5. public void setPage(int pageIndex, Printable painter, PageFormat pf) throws IndexOutOfBoundsException:- Specifies the PageFormat and Printable objects for the page specified by the pageIndex parameter. This method throws IndexOutOfBoundsException, in case pageIndex is out of range of the Book object.
      6. public Printable getPrintable(int pageIndex) throws IndexOutOfBoundsException:- Returns the Printable object associated with the page specified by the pageIndex parameter. This method raises IndexOutOfBoundsException, in case pageIndex is out of range of the Book object.


      Code for Using the Methods of the Book Class

      Code:
      /* The code shows the append() method of the Book class. */
      /* bookDemo.java*/
      
      import java.awt.*;
      import java.awt.print.*;
      
      public class bookDemo
         {
          public static void main(String [] s)
            {
                   Book book = new Book();
                   PrinterJob pj = PrinterJob.getPrinterJob();
                   Printable1 p1 = new Printable1();
                   Printable2 p2 = new Printable2();
                  // get the default page format
                  PageFormat pf1 = pj.defaultPage();
                  pf1.setOrientation (PageFormat.PORTRAIT);
             /*append to the book one page of the p1 type and of the PageFormat pf1*/
                  book.append(p1,pf1);
                  /* create another PageFormat*/
                  PageFormat pf2 = pj.defaultPage();
                  pf2.setOrientation (PageFormat.LANDSCAPE);
             /*append to the book three pages of the p1 type and of the PageFormat pf2*/
                 book.append(p2,pf2,3);
                 pj.setPageable(book);
                 if(pj.printDialog())
                    {
                  try
                       {
                     System.out.println("Printing " + book.getNumberOfPages()+ "  Pages");
                 pj.print();
                   }
                      catch(PrinterException pe)
                      {
                         System.out.println(pe);
                      }
              }
      }
      /* print() method of Printable1 class*/
      static class Printable1 implements Printable 
            {
           public int print(Graphics g, PageFormat pf, int pageIndex)
                 {
                    return Printable.NO_SUCH_PAGE;
               /* the method does not do any printing*/
             }
           }
      /* print() method of Printable1 class*/
      static class Printable2 implements Printable 
          {
          public int print(Graphics g, PageFormat pf, int pageIndex)
                {
                   return Printable.NO_SUCH_PAGE;
               /* the method does not do any printing*/
                }
         }
       }
      The main() method creates a PrinterJob object using the getPrinterJob() method and declares two Printable classes, Printable1 and Printable2, which implement the Printable interface. The main() method creates an object of both the Printable classes. You can create a Book object using the default constructor of the Book class and append one page of PageFormat, pf1 and Printable1, p1, and three pages of the PageFormat, pf2, and Printable2 to the book. The code then passes the book to the PrinterJob setPageable method. pj.printDialog opens the Print dialog box for the end user.

      The Interfaces of the java.awt.print API



      The java.awt.print API provides three interfaces that are implemented for various printing options. These interfaces are, Printable, Pageable, and PrinterGraphics.

      The Printable Interface
      The java.awt.print.Printable interface provides one method, print(), and throws PrinterException when the print operation terminates. The declaration of the Printable interface is:
      abstract interface java.awt.print.Printable

      Code for Using the print() Method of the java.awt.print.Printable Interface
      Code:
      /* The print method of the Printable interface*/
      /* The method takes three parameter*/
      public int print
      (    
              Graphics g,
              /* specifies the context in which the page is drawn*/
              PageFormat pf,
              /* specifies the size and orientation of the page*/
              int pageIndex;
      )
      /* specifies the index of the page to be printed*/
      throws PrinterException;
      /* Exception raised on the termination of the print process*/
      The print() method returns PAGE_EXISTS if the page is submitted successfully, and NO_SUCH_PAGE if the index of the page is out of range. This indicates that the page does not exist. PAGE_EXISTS and NO_SUCH_PAGE represent predefined static integers in the Printable interface.

      The Printable interface is easy to implement because it uses only one page painter to print all the pages. This interface does not maintain the document to be printed in the form of separate pages. As a result, all pages up to the page to be printed are submitted sequentially and then, the specified page is printed.

      The Pageable Interface

      This interface provides three methods that help obtain the number of pages in the document, the format of a page specified by the index of the page, and the Printable instance that submits the page. The declaration of the Pageable interface is:

      abstract interface java.awt.print.Pageable

      The various methods of the Pageable interface are:-

      1. public int getNumberOfPages():- Returns the number of pages in the document. This method returns the constant UNKNOWN_NUMBER_OF_PAGES, defined in the Pageable interface in case the number of pages of the set is not known.
      2. public PageFormat getPageFormat(int indexOfPage) throws IndexOutOfBoundsException:- Returns the orientation and size as the PageFormat object of the page identified by the index. This method raises IndexOutOfBoundsException in case the indexOfPage parameter is greater than the number of pages in the document to be printed.
      3. public Printable getPrintable(int indexOfPage) throws IndexOutOfBoundsException:- Returns the instance of the Printable class that submits the page specified by the indexOfPage parameter. This method raises IndexOutOfBoundsException in case the indexOfPage parameter is greater than the number of pages in the document to be printed.


      The Pageable interface enables the use of multiple page painters for the document. You can specify different formats and layouts for the different pages of the document.
      The Pageable jobs do not need to know the number of pages in advance.

      The PrinterGraphics Interface
      This interface provides only one method, getPrinterJob(). This method returns the PrinterJob object that controls the current printing process. The Graphics object implements this method to provide a page passed to the Printable object. The declaration of the PrinterGraphics interface is:

      abstract interface java.awt.print.PrinterGraphics

      The code for the getPrinterJob() method is:

      Code:
      /* The getPrinterJob() method*/
      /* Returns the PrinterJob controlling the printing process for the Graphics object*/
      public PrinterJob getPrinterJob()
      /* The PrinterGraphics interface is implemented inside the PrinterJob to define Graphics object passed to the Printable object*/

      The PrinterException Class



      This class indicates a problem that arises during the printing operation. The declaration of the PrinterException class is:
      public class java.awt.print. PrinterException extends Exception

      The PrinterException class provides two constructors:

      PrinterException pe= new PrinterException(); // Constructs an object of the PrinterException class without a detailed message

      PrinterException pe= new PrinterException(msg);
      /*Constructs an object of the PrinterException class with the given detailed message msg. The detailed message is generated when a PrinterException is thrown
      */
      The two direct subclasses of the PrinterException class are, PrinterAbortException and PrinterIOException.

      The PrinterAbortException Class
      This class indicates that either the user or the application cancels the printing job while it is in progress. The declaration of the PrinterAbortException class is:

      public class java.awt.print PrinterAbortException extends PrinterException

      The PrinterAbortException class provides two constructors, one without a detailed message and another with a detailed message. These are:

      PrinterAbortException pe= new PrinterAbortException();
      /* Constructs an object of the PrinterAbortException class without a detailed message */

      PrinterAbortException pe= new PrinterAbortException(msg);

      /*Constructs an object of the PrinterAbortException class with the given detailed message msg. The detailed message is generated when a PrinterAbortException is thrown*/

      The PrinterIOException Class

      This class is raised when an error of the I/O type arises while printing. For example, an I/O type error arises when the printer is not ready for printing. The declaration of the PrinterIOException class is:

      public class java.awt.print.PrinterException extends PrinterException


      The PrinterIOException class provides two constructors, one without a detailed message and another with a detailed message. These are:

      PrinterIOException pe = new PrinterIOException();
      /* Constructs an object of the PrinterIOException class without a detailed message */

      PrinterIOException pe = new PrinterIOException(msg);

      /*Constructs an object of the PrinterIOException class with the given detailed message msg. The detailed message is generated when a PrinterIOException is thrown*/

      Printing Shapes and Text



      Printing Shapes
      If you need to print shapes, draw them using a Graphics object and pass the Graphics object to the print() method of the Printable object. In the print() method of the Printable class, you can draw certain shapes using the Graphics2D object.
      Code for Printing Shapes

      Code:
      import java.awt.*;
      import java.awt.print.*;
      import java.awt.Graphics.*;
      import java.awt.geom.*;
      
      public class PrintShape implements Printable{
          public static void main(String args[])
          {
               PrintShape ps = new PrintShape();
               System.exit(0);
          }
             public PrintShape(){
               PrinterJob pj = PrinterJob.getPrinterJob();
               pj.setPrintable(this);
               PageFormat pf = new PageFormat();
               Paper paper = new Paper();
               pf.setOrientation(PageFormat.PORTRAIT);
               paper = pf.getPaper();
               paper.setImageableArea(0,0,530,842);
               pf.setPaper(paper);
               if(pj.printDialog())
               /* if user clicked OK to the print dialog*/
               {
                    try
                    {
                        pj.print();
                    }catch(Exception ex){
              System.out.println("Error in Printing:" + ex);
               }
              }
      }
      
      public int print(Graphics g, PageFormat pf, int pi)
              throws PrinterException{
                   if(pi>=1)/* if page index is greater than one then no more page to print*/
                       return Printable.NO_SUCH_PAGE;
              Graphics2D g2 = (Graphics2D)g;
              /* map graphics g2 to the imageable area of the page*/
              g2.translate(pf.getImageableX(),pf.getImageableY());
      
              /* draw some shapes */
              g2.drawRoundRect(20,85,290,95,30,30);
              g2.drawRect(295,200,25,20);
              g2.drawRect(295,220,25,250);
              g2.drawRect(320,200,50,20);
              g2.drawRect(180,300,100,250);
              g2.drawRect(180,350,100,45);
              g2.drawRect(180,400,100,15);
              g2.setColor(Color.white);
              g2.fillRect(0,0,300,300);
              g2.setColor(Color.blue);
              Ellipse2D.Float circle = new Ellipse2D.Float (100,100,70,80);
              g2.fill(circle);
              return Printable.PAGE_EXISTS;
             }
      }
      This code initializes the constructor of the PrintShape class, the object of the PrinterJob class, the PageFormat class, and the Paper object and sets the properties of the objects. These properties include the orientation and the paper of the PageFormat object and the Imageable area of the Paper object. The print() method of the Printable object draws some shapes using an object of the Graphics2D class. The main() method creates an object of the PrintShape class and initiates the printing process.

      Printing Text
      If you need to print text in Java, draw the text using an object of the Graphics class. This Graphics object is passed to the print method() of the Printable object.

      Code for Printing Text

      Code:
      import java.awt.*;
      import javax.swing.*;
      import java.awt.event.*;
      import java.awt.print.*;
      import java.awt.geom.*;
      
      public class PrintText extends Jframe implements ActionListener {
          public static void main(String[] args)
          {
                 new PrintText();
          }
      
          public PrintText()
          {
                 super("Printing In Java");
                 this.addWindowListener(new WindowAdapter()
          {
                public void windowClosing(WindowEvent e)
                {
                  System.exit(0);
                }
          });
      Container content = getContentPane();
      JButton button = new JButton("Print");
      button.addActionListener(this);
      JPanel panel = new JPanel();
      panel.setBackground(Color.white);
      panel.add(button);
      content.add(panel, BorderLayout.NORTH);
      DrawString drawstr = new DrawString("Printing in Java");
      content.add(drawstr, BorderLayout.CENTER);
      pack();
      setVisible(true);
      }
      
        public void actionPerformed(ActionEvent event) {
          txtPrint.printComponent(this);
        }
      }
      class DrawString extends JPanel {
          private int fntSize = 60;
          private int strW;
          private String str;
      
          public DrawString(String s) {
            str = s;
            setBackground(Color.white);
            Font fnt = new Font("Serif", Font.PLAIN, fntSize);
            setFont(fnt);
            FontMetrics metrics = getFontMetrics(fnt);
            strW = metrics.stringWidth(str);
            int width = strW*5/3;
            int height = fntSize*3;
            setPreferredSize(new Dimension(width, height));
            }
      
      /*Draw the string with a shadow of the string*/
            public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            int x = strW/10;
            int y = fntSize*5/2;
            g2.translate(x, y);
            g2.setPaint(Color.pink);
            AffineTransform origTransform = g2.getTransform();
            g2.shear(1,0 );
            g2.scale(1, 2);
            g2.drawString(str, 40, 0);
            g2.setTransform(origTransform);
            g2.setPaint(Color.red);
            g2.drawString(str, 37, 0);
          }
        }
      class txtPrint implements Printable {
        private Component component;
      
        public static void printComponent(Component c) {
          new txtPrint(c).print();
        }
      
        public txtPrint(Component component) {
          this.component = component;
        }
      
        public void print() {
          PrinterJob printJob = PrinterJob.getPrinterJob();
          printJob.setPrintable(this);
          if (printJob.printDialog())
            try {
              printJob.print();
            } catch(PrinterException pe) {
              System.out.println("Error in printing !!! " + pe);
            }
        }
      
        public int print(Graphics g, PageFormat pf, int pageIndex) {
             RepaintManager currentManager = RepaintManager.currentManager(component);
            if (pageIndex > 0)
            {
                return(NO_SUCH_PAGE);
            } else {
            Graphics2D g2d = (Graphics2D)g;
            g2d.translate(pf.getImageableX(), pf.getImageableY());
            /** Disable double buffering as double buffering slows the printing*/
            currentManager.setDoubleBufferingEnabled(false);
            component.paint(g2d);
            currentManager.setDoubleBufferingEnabled(true);
            return(PAGE_EXISTS);
          }
        }
      }
      In this code, the PrintText class extends the Jframe class. In the constructor of the PrintText class, a title of the window, a print button of the type, Jbutton, and actionListener to the button are initialized. An object of the DrawString class is added to the Jframe class. In the DrawSting class, string properties, such as the font and font size, are initialized. The PrintComponent class declares the print() method that prints any component passed to it. A component of the PrintText is passed to the PrintComponent print() method. The print() method initializes the PrinterJob object and opens the Print dialog box for the end user. The main() method creates an object of the PrintText class and initiates the printing process. The print method of the PrintText class provides the text to be printed. This method returns NO_SUCH_PAGE when the printing process is complete.


      When you click the Print button, the Print dialog box appears. In this dialog box, the end user can choose the printer and initiate or cancel the printing process.



    Disclaimer: Users of techforum4u.com are responsible for ensuring that any material they post (article, blog posts, images or other mulitimedia content) does not violate or infringe upon the copyright, patent, trademark, or any personal or proprietary rights of any third party, and is posted with the permission of the owner of such rights.Anyone who violates these rules may have their access privileges removed without warning.