2011-04-21 83 views
0

當我調試這個程序的服務數組是空的?打印機服務未找到?

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.attribute.PrintRequestAttributeSet; 
    import javax.print.attribute.standard.Copies; 
    import javax.print.attribute.standard.MediaSize; 

    import javax.print.attribute.standard.Sides; 


    public class PrintFileWithSpec { 


     public static void printFile(String filename){ 

     FileInputStream psStream=null; 
     try { 
      psStream = new FileInputStream(filename); 
     } catch (FileNotFoundException ffne) { 
     } 
     if (psStream == null) { 
      return; 
     } 

     DocFlavor psInFormat = DocFlavor.INPUT_STREAM.POSTSCRIPT; 
     Doc myDoc = new SimpleDoc(psStream, psInFormat, null); 
     PrintRequestAttributeSet aset = 
      new HashPrintRequestAttributeSet(); 
     aset.add(new Copies(5)); 
     //aset.add(MediaSize.ISO_A4); 
     aset.add(Sides.DUPLEX); 
     PrintService[] services = 
      PrintServiceLookup.lookupPrintServices(psInFormat, aset); 
     if (services.length > 0) { 
      DocPrintJob job = services[0].createPrintJob(); 
      try 
      { 
       job.print(myDoc, aset); 
      } catch (PrintException pe) {} 
     } 
     } 

     public static void main(String [] args){ 

      printFile("D:/Resume.doc"); 
     } 
    } 
+0

這似乎是在指定的屬性'aset'有點限制太多 - 當我通過'null'時,它對我有用。 – AbdullahC 2011-04-21 09:35:28

+0

那我該怎麼辦? – Harinder 2011-04-21 09:40:33

+0

我通過null而不是一個仍然相同的問題 – Harinder 2011-04-21 09:41:41

回答

1

這是因爲沒有找到對應於指定的DocFlavor和屬性集的PrintService。可能很難找到支持PostScript的打印機,除非您的打印機硬件相當新。您可以檢查什麼都DocFlavors都是這樣的支持:

對於定位特定的打印服務,你可以做這樣的事情:

PrintService prnSvc = null; 

    /* locate a print service that can handle it */ 
    PrintService[] pservices = 
      PrintServiceLookup.lookupPrintServices(null, null); 
    if (pservices.length > 0) { 
     int ii=0; 
     while(ii < pservices.length) 
     { 
      System.out.println("Named Printer found: "+pservices[ii].getName()); 
      if (pservices[ii].getName().endsWith("YourPrinterName")) { 
       prnSvc = pservices[ii]; 
       System.out.println("Named Printer selected: " + pservices[ii].getName() + "*"); 
       break; 
      } 
      ii++; 
     } 
+0

我得到了docFlavor的以下輸出,所以我的打印輸出.txt,.pdf,doc等?圖像/ GIF 圖像/ GIF 圖像/ GIF 圖像/ JPEG 圖像/ JPEG 圖像/ JPEG 圖像/ PNG 圖像/ PNG 圖像/ PNG 應用程序/ x-java的JVM-本地objectref 應用/ x-java-jvm-local-objectref application/octet-stream application/octet-stream application/octet-stream – Harinder 2011-04-25 05:23:59

+0

請看看發生的事情.http://stackoverflow.com/q/5775740/689853 – Harinder 2011-04-25 06:13:36

相關問題