无法在Swing中从特定打印机打印文档

时间:2012-06-13 12:43:54

标签: java swing

我正在编写一个代码,该代码应该在客户端计算机上找到打印机列表,并设置一个用于打印Doc的微粒打印机。但我在网上瞪眼,我发现代码有点像这样:

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;
    }
}

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

1 个答案:

答案 0 :(得分:1)

根据documentation of print()

  

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

这意味着您需要注册PrintJobListener才能告诉问题:

尝试:

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()之前,看看有什么东西输出到控制台