我正在尝试设置一个Java应用程序,它将文档发送到打印机。作为起点,我只是尝试打印一个字符串。我已经到了应用程序无错误运行的地步,并且我已经证明PrintService可以打印我的请求,但是从打印机中什么也不会吐出来。
我一直在遵循以下有关如何设置Java应用程序以将内容发送到打印机的指南。
从这些我有以下代码:
public String print(String name, String message) throws PrintException, IOException {
PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null);
PrintService service = null;
boolean printed = false;
for (PrintService printer : printServices) {
if (printer.getName().contains(name)) {
System.out.println("Printing to : " + printer.getName());
DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
Doc doc = new SimpleDoc(message.getBytes(), flavor, null);
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
pras.add(new Copies(1));
pras.add(MediaSize.ISO.A4.getMediaSizeName());
pras.add(Sides.DUPLEX);
PrintService[] services =
PrintServiceLookup.lookupPrintServices(flavor, null);
boolean found = false;
for(PrintService s : services) {
System.out.println(s.getName());
if (s.equals(printer)) {
found = true;
}
}
if (!found) {
System.out.println("Unable to find a compatible printer");
}
DocPrintJob job = printer.createPrintJob();
PrintJobWatcher pjw = new PrintJobWatcher(job);
job.print(doc, pras);
pjw.waitForDone();
// send FF to eject the page
Doc docff = new SimpleDoc("\f".getBytes(), flavor, null);
DocPrintJob jobff = printer.createPrintJob();
pjw = new PrintJobWatcher(jobff);
jobff.print(docff, null);
pjw.waitForDone();
printed = true;
break;
}
}
return printed ? "Document has been printed" : "Failed to print document";
}
class PrintJobWatcher {
boolean done = false;
PrintJobWatcher(DocPrintJob job) {
job.addPrintJobListener(new PrintJobAdapter() {
public void printJobCanceled(PrintJobEvent pje) {
allDone();
}
public void printJobCompleted(PrintJobEvent pje) {
allDone();
}
public void printJobFailed(PrintJobEvent pje) {
allDone();
}
public void printJobNoMoreEvents(PrintJobEvent pje) {
allDone();
}
void allDone() {
synchronized (PrintJobWatcher.this) {
done = true;
System.out.println("Printing done ...");
PrintJobWatcher.this.notify();
}
}
});
}
public synchronized void waitForDone() {
try {
while (!done) {
wait();
}
} catch (InterruptedException e) {
}
}
}
我在控制台中的输出如下:
Printing to : My Printer XYZ
My Printer XYZ
Microsoft XPS Document Writer
Microsoft Print to PDF
Fax
Printing done ...
Printing done ...
任何人都可以帮助我了解为什么这导致什么都没发生吗?