0

我现在已经设法在 JSF 中创建一个上传,允许用户上传一个文本文件,我也可以显示它。我设法将它打印到连接到客户端的打印机上。如何将此文本打印到使用 Java 代码连接到服务器端的打印机?

4

1 回答 1

1

非常简单,上传文件后,您将拥有整个文件内容,创建一个实用程序PrintDocument类并在需要打印时调用它。

public class PrintDocument {

  public void printText(String text) throws PrintException, IOException {

    PrintService service = PrintServiceLookup.lookupDefaultPrintService();
    InputStream is = new ByteArrayInputStream(text.getBytes("UTF8"));
    PrintRequestAttributeSet  pras = new HashPrintRequestAttributeSet();
    pras.add(new Copies(1));

    DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
    Doc doc = new SimpleDoc(is, flavor, null);
    DocPrintJob job = service.createPrintJob();

    PrintJobWatcher pjw = new PrintJobWatcher(job);
    job.print(doc, pras);
    pjw.waitForDone();
    is.close();
  }
}

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 document is done ...");
          PrintJobWatcher.this.notify();
        }
      }
    });
  }
  public synchronized void waitForDone() {
    try {
      while (!done) {
        wait();
      }
    } catch (InterruptedException e) {
    }
  }
}

如果您需要获取所有打印机,请使用PrintService[] services = PrinterJob.lookupPrintServices();

于 2012-12-26T02:01:21.870 回答