2012-04-11 46 views
2

我正在開發一個小應用程序在Ubuntu打印數據,問題是我的應用程序在Windows中使用正常工作:的Java打印在Ubuntu

PrintService service = PrintServiceLookup.lookupDefaultPrintService(); 

FileInputStream fis = new FileInputStream(myfile); 

DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE; 
DocPrintJob job = service.createPrintJob(); 

Doc doc = new SimpleDoc(fis, flavor, null); 
job.print(doc, null); 
fis.close(); 

但是在Ubuntu中,它只是不打印。我正在使用的打印API是否有針對Linux打印的特殊配置?還是我錯過了別的?

+0

您的代碼在這裏工作,如果我取代「MYFILE」與路徑,指向一個文本文件中。您是否已在系統中正確安裝打印機?你可以在其他應用程序打印?例如gedit,gvim ...? – Kent 2012-04-11 14:31:37

+0

我可以使用cat「filename」|從終端打印lpr ...通常「myfile」是從打開的文件對話框的路徑的字符串... – Sin5k4 2012-04-11 14:35:41

+1

我刪除了'eclipse'標籤。該標籤專門針對有關Eclipse,IDE的問題。 – ArjunShankar 2012-04-11 14:50:20

回答

2

我認爲,你的打印機安裝在操作系統中不是默認的。檢查你的「服務」是什麼。 您也可以從打印對話框中選擇打印機,就像這樣:

PrintRequestAttributeSet pras = 
       new HashPrintRequestAttributeSet(); 
     DocFlavor flavor = DocFlavor.INPUT_STREAM.TEXT_PLAIN_UTF_8; 
     PrintRequestAttributeSet aset = 
       new HashPrintRequestAttributeSet(); 
     aset.add(MediaSizeName.ISO_A4); 
     aset.add(new Copies(1)); 
     aset.add(Sides.ONE_SIDED); 
     aset.add(Finishings.STAPLE); 

     PrintService printService[] = 
       PrintServiceLookup.lookupPrintServices(flavor, pras); 
     PrintService defaultService = 
       PrintServiceLookup.lookupDefaultPrintService(); 
     PrintService service = ServiceUI.printDialog(null, 200, 200, 
       printService, defaultService, flavor, pras); 
     if (service != null) { 
      try { 
       FileInputStream fis = new FileInputStream("c://test.txt"); 
       DocAttributeSet das = new HashDocAttributeSet(); 
       Doc doc1 = new SimpleDoc(fis, flavor, das); 

       DocPrintJob job1 = service.createPrintJob(); 

       try { 
        job1.print(doc1, pras); 
       } catch (PrintException e) { 
        e.printStackTrace(); 
       } 
      } catch (FileNotFoundException e) { 
       e.printStackTrace(); 
      } 
     } 

有些打印機不支持文本DocFlavors,只圖像。您也可以使用這樣的OS本地方法簡單地打印HTML文件:

if (Desktop.isDesktopSupported()){ 
    Desktop desktop = Desktop.getDesktop(); 
    if (desktop.isSupported(Desktop.Action.PRINT)) 
    { 
     try { 
      File html1 = new File("c://file1.html"); 
      desktop.print(html1); 
      desktop.print(html2); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

}

+0

試過這個對話框,它根本不起作用,我看到打印機那裏,當我點擊打印,沒有工作發送到我的打印隊列... :( – Sin5k4 2012-04-11 15:15:10

+0

對不起,我忘記了將DocFlavor改爲「TEXT_PLAIN_UTF_8」。試試這個,或者嘗試將數據打印爲html,我添加了這個答案。 – 2012-04-11 18:18:33