Java应用程序在网络打印机上打印

时间:2012-02-01 15:50:45

标签: java networking printing

我正在开发一个示例应用程序来在网络打印机上打印文件。但我无法取得成功。伙计们请帮我解决这个问题。

FileInputStream fis = new FileInputStream(file);
if (fis == null) {
System.out.print("No File");
return;
}
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();

PrintService service = PrintServiceLookup.lookupDefaultPrintService();

aset.add(new PrinterName("ipp:\\witnw21va\ipp\ITDepartment-HP4050", null));
//PrintServiceAttributeSet aset = HashPrintAttributeSet();
PrintService[] pservices = PrintServiceLookup.lookupPrintServices(flavor, aset);

if (service != null){
System.out.println("Default Printer: " + service.getName());

// Creating DocPrintJob
DocPrintJob job = service.createPrintJob();
try{
Doc doc = new SimpleDoc(fis,flavor,null);

PrintJobWatcher pjDone = new PrintJobWatcher(job);

job.print(doc,aset);

// Wait for the print job to be done
pjDone.waitForDone();

fis.close();
}

非常感谢。

1 个答案:

答案 0 :(得分:2)

该代码无法编译,因为打印机名称中包含无效escape sequences

new PrinterName("ipp:\\witnw21va\ipp\ITDepartment-HP4050", null)

Java编译器认为您正在尝试编写新行\n之类的特殊字符,并且在该字符串中被\w\i等混淆,这是不合法的。

您需要转义每个反斜杠以使其合法:

new PrinterName("ipp:\\\\witnw21va\\ipp\\ITDepartment-HP4050", null)

或者如果它实际上应该是正斜杠则更改