Tuesday, 15 July 2014

Silent print of PDF using JAVA.

I have used javax.print API to perform printing of PDF without user interaction.
It is running only in MAC still search is going on for Windows.

import java.io.FileInputStream;
import java.io.FileNotFoundException;

import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.event.PrintJobAdapter;
import javax.print.event.PrintJobEvent;


public class Abc {
  /**
  * @param args
  */
  public static void main(String[] args) {

    new Abc().print();
  }
  public void print() {
  /*
    The format of Page will be PDF.
    We have different types based on what we pass to printer.
  */
    DocFlavor flavor = DocFlavor.INPUT_STREAM.PDF;

   // Number of printers in network will be recognized.

    PrintService[] services = PrintServiceLookup.lookupPrintServices(flavor, null);
    FileInputStream psStream = null;  
    try {  
        psStream = new FileInputStream
       ("E:/apache-tomcat-7.0.30/webapps/pdf/TripSheetReport 27-3.pdf");  
        } catch (FileNotFoundException ffne) {  
             ffne.printStackTrace();  
        }  
    if (psStream == null) {  
        return;  
    }       
    if (services.length > 0)
    {
       PrintService myService = null;
       for(PrintService service : services) {
       System.out.println(service.getName());
       // Check whether connected printer is recognized.
          if(service.getName().contains("M1136")) {
            myService = service;
     break;
          }
       }
       DocPrintJob printJob = myService.createPrintJob();
       Doc document = new SimpleDoc(psStream, flavor, null);
       
       try {
 
         // Sends the document to print.
  printJob.print(document, new HashPrintRequestAttributeSet());
     } catch (PrintException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
      }
 }
  else
  {
     System.out.println("No PDF printer available.");
  }       
 }
        // To check the status of Print.

   class PrintJobWatcher {
      boolean done = false;
      PrintJobWatcher(DocPrintJob job) {
         job.addPrintJobListener(new PrintJobAdapter() {
       public void printJobCanceled(PrintJobEvent pje) {
          allDone();
       }
       public void printJobCompleted(PrintJobEvent pje) {
         allDone();
       }
       public void printJobFailed(PrintJobEvent pje) {
         allDone();
       }
       public void printJobNoMoreEvents(PrintJobEvent pje) {
         allDone();
       }
       void allDone() {
         synchronized (PrintJobWatcher.this) {
           done = true;
           System.out.println("Printing done ...");
           PrintJobWatcher.this.notify();
         }
       }
   });
 }
   
}
}

No comments: