1

I'm trying to print an html file directly to the default printer without showing print dialog to the user.

I just got the below code from some online tutorials and it worked well for the PNG file.

import javax.print.*;
import javax.print.attribute.*;
import java.io.*;

public class Printing {
  public static void main(String args[]) throws Exception {
    String filename = args[0];
    PrintRequestAttributeSet pras = 
      new HashPrintRequestAttributeSet();
    DocFlavor flavor = DocFlavor.INPUT_STREAM.PNG;
    PrintService printService[] = 
      PrintServiceLookup.lookupPrintServices(flavor, pras);
    PrintService defaultService = 
      PrintServiceLookup.lookupDefaultPrintService();
    PrintService service = ServiceUI.printDialog(null, 200, 200, printService, defaultService, flavor, pras);
    if (service != null) {
      DocPrintJob job = service.createPrintJob();
      FileInputStream fis = new FileInputStream(filename);
      DocAttributeSet das = new HashDocAttributeSet();
      Doc doc = new SimpleDoc(fis, flavor, das);
      job.print(doc, pras);
      Thread.sleep(10000);
    }
    System.exit(0);
  }
}

I would like to change DocFlavor flavor = DocFlavor.INPUT_STREAM.PNG; to DocFlavor flavor = DocFlavor.INPUT_STREAM.<some html format>;

Please suggest which format would be appropriate to use here ?

and please suggest how to avoid print dialog pop up while running this code. ?

Thanks in Advance Sandy

Sandeep K Gujje
  • 43
  • 1
  • 1
  • 13

1 Answers1

0
PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
//    PrintService service = ServiceUI.printDialog(null, 200, 200, printService, defaultService, flavor, pras);
if (service != null) {
     ... the rest code

You can use just default service rather than showing from the dialog

StanislavL
  • 56,971
  • 9
  • 68
  • 98
  • thanks for your reply.. what if I need to pass printer name as an argument instead of using default one.. Please suggest how to use a specific printer name ? – – Sandeep K Gujje May 16 '14 at 13:44
  • 1
    You have PrintService printService[] = PrintServiceLookup.lookupPrintServices(flavor, pras); Go through the array and compare the necessary name with each PrintService's name till required one is found – StanislavL May 16 '14 at 13:47
  • thanks for your valuable suggestion, will try the same and get back to you.. and regarding printing html instead of png, what would be the proper format we should use in `DocFlavor flavor = DocFlavor.INPUT_STREAM.PNG` Please suggest – Sandeep K Gujje May 16 '14 at 13:49
  • Using the PrintService array to look for specific printer worked.. thanks for that.. Could you also please suggest how to print html using DocFlavor? – Sandeep K Gujje May 17 '14 at 08:34