问题
I am working on a sample application to print file on network printer. But i m unable to get success. Guys please help me out to get rid this problem.
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();
}
Many thanks.
回答1:
That code won't compile, because you have invalid escape sequences in the printer name:
new PrinterName("ipp:\\witnw21va\ipp\ITDepartment-HP4050", null)
The Java compiler thinks you are trying to write special characters like newline \n
, and is confused by \w
, \i
etc in that string, which are not legal.
You need to escape each backslash to make it legal:
new PrinterName("ipp:\\\\witnw21va\\ipp\\ITDepartment-HP4050", null)
or change it if it should in fact be forward slashes
来源:https://stackoverflow.com/questions/9098853/java-application-to-print-on-network-printer