Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何从字符串打印文本_Java_Printing - Fatal编程技术网

Java 如何从字符串打印文本

Java 如何从字符串打印文本,java,printing,Java,Printing,我现在已经成功地在JSF中创建了一个上传,允许用户上传一个文本文件,我也可以显示它。我设法将它打印到连接到客户端的打印机上。如何将此文本打印到使用Java代码连接到服务器端的打印机上?非常简单,一旦上传文件,您将拥有整个文件内容,创建一个实用工具PrintDocument类,并在需要打印时调用它 public class PrintDocument { public void printText(String text) throws PrintException, IOException

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

非常简单,一旦上传文件,您将拥有整个文件内容,创建一个实用工具
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()

非常感谢,我现在就试试这个,有没有办法将它发送到打印机队列或打印机的ip地址,而不是选择打印机?如果需要打印默认打印机,这是您的选择,只需发送它即可。如果用户选择,则添加一个jsf弹出窗口以选择打印机