1

我正在编写一个代码,它应该在客户端机器上找到打印机列表并设置一个特定的打印机来打印一个文档。但是我在网上看了一下,发现一些代码是这样的:

package org.ui;
import java.io.FileInputStream;
import javax.print.*;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
public class Printing {
    public static void main (String [] args) {       
        DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
        PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet ();       
        PrintService [] pservices = PrintServiceLookup.lookupPrintServices (flavor, aset);
        try {
            int printer = getPrinter(pservices);
            if(printer == -1) {
                throw new Exception("No network printer found");
            }
            DocPrintJob pj = pservices[0].createPrintJob();
            FileInputStream fis = new FileInputStream ("c:///file.txt");
            Doc doc = new SimpleDoc (fis, flavor, null);
            pj.print (doc, aset);
        }
        catch (Exception ex) {
            ex.printStackTrace ();
        } 
    }
    private static int getPrinter(PrintService[] pservices) {
        int printer = -1;
        for(int i = 0; i<pservices.length; i++) {
            if(pservices[i].getName().contains("\\\\")) {
                System.out.println("network printer: " + pservices[i].toString());   
                printer = i;
                break;
            }        
        }
        return printer;
    }
}

但是我无法在纸上打印,谁能告诉我这段代码有什么问题?它是一个桌面应用程序。

4

1 回答 1

1

根据文档print()

[...] 当 print 方法返回时,打印可能尚未完成,因为打印可能异步发生,可能在不同的线程中。想要监视成功或失败的应用程序客户端应该注册一个 PrintJobListener。

这意味着您需要注册 aPrintJobListener才能知道问题所在:

尝试:

pj.addPrintJobListener(new PrintJobListener() {
  @Override
  void printDataTransferCompleted(PrintJobEvent pje) {
    System.out.println("Transfer completed");
  }
  @Override
  void printJobCanceled(PrintJobEvent pje) {
    System.out.println("Cancelled");
  }
  @Override
  void printJobCompleted(PrintJobEvent pje) {
    System.out.println("Completed");
  }
  @Override
  void printJobFailed(PrintJobEvent pje) {
    System.out.println("Failed");
  }
  @Override
  void printJobNoMoreEvents(PrintJobEvent pje) {
    System.out.println("No more events");
  }
  @Override
  void printJobRequiresAttention(PrintJobEvent pje) {
    System.out.println("Check printer");
  }
});

在调用之前print()查看输出到控制台的内容

于 2012-06-13T13:23:35.583 回答