Open a Printer Dialog in Java

This tutorial will teach you how to create a program that will open a printer dialog in Java. The printer dialog helps you to perform printing of documents. So, now let's start this tutorial! 1. Open JCreator or NetBeans and make a java program with a file name of printDialog.java. 2. Import java.awt.print package. Hence we will use the print class of AWT package and this will access the PageFormat and PrinterJob in the print class.
  1. import java.awt.print.*; // this is used to access the PageFormat and PrinterJob in the print class
3. Initialize your variables in your Main, variable printer used for PrinterJob method and pFormat for PageFormat method.
  1.     PrinterJob printer = PrinterJob.getPrinterJob(); // this method calls to setup a job for printing pages
  2.     PageFormat pFormat = printer.defaultPage(); // the page is set to default size format and orientation
4. To open the printer dialog, have the syntax below:
  1.         printer.printDialog(); // show the print dialog
5. Create a try and catch method. In the try method, this will print the pages with the default format and in catch, this will catch the error during printing.
  1. try {
  2.     printer.print(); //if clicking ok in the print dialog, this will print the pages with the default format
  3.   }
  4.  catch (  Exception PrintException) { //catch the error during printing
  5.   }
Output: printDialog Here's the full source code of this tutorial:
  1. import java.awt.print.*; // this is used to access the PageFormat and PrinterJob in the print class
  2.  
  3.  
  4. public class printDialog {
  5.        
  6.   public static void main(String[] args) throws Exception {
  7.  
  8.     PrinterJob printer = PrinterJob.getPrinterJob(); // this method calls to setup a job for printing pages
  9.     PageFormat pFormat = printer.defaultPage(); // the page is set to default size format and orientation
  10.  
  11.         printer.printDialog(); // show the print dialog
  12.    
  13. try {
  14.     printer.print(); //if clicking ok in the print dialog, this will print the pages with the default format
  15.   }
  16.  catch (  Exception PrintException) { //catch the error during printing
  17.   }
  18.   }
  19. }
Best Regards, Engr. Lyndon Bermoy IT Instructor/System Developer/Android Developer/Freelance Programmer If you have some queries, feel free to contact the number or e-mail below. Mobile: 09488225971 Landline: 826-9296 E-mail:donbermoy@engineer.com Add and Follow me on Facebook: https://www.facebook.com/donzzsky Visit and like my page on Facebook at: https://www.facebook.com/BermzISware

Add new comment