gpt4 book ai didi

java - 如何从字符串中打印出文本

转载 作者:行者123 更新时间:2023-12-01 14:58:24 25 4
gpt4 key购买 nike

我现在已经成功在 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();

关于java - 如何从字符串中打印出文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14033969/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com