我認爲,你的打印機安裝在操作系統中不是默認的。檢查你的「服務」是什麼。 您也可以從打印對話框中選擇打印機,就像這樣:
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();
}
}
}
您的代碼在這裏工作,如果我取代「MYFILE」與路徑,指向一個文本文件中。您是否已在系統中正確安裝打印機?你可以在其他應用程序打印?例如gedit,gvim ...? – Kent 2012-04-11 14:31:37
我可以使用cat「filename」|從終端打印lpr ...通常「myfile」是從打開的文件對話框的路徑的字符串... – Sin5k4 2012-04-11 14:35:41
我刪除了'eclipse'標籤。該標籤專門針對有關Eclipse,IDE的問題。 – ArjunShankar 2012-04-11 14:50:20