gpt4 book ai didi

java - 打印机在服务器而不是客户端打印

转载 作者:行者123 更新时间:2023-11-30 07:08:28 26 4
gpt4 key购买 nike

我有一个java程序,可以将原始数据打印到热敏打印机。该代码在服务器中运行完美,但是当在客户端中访问时,它会在服务器的打印机本身而不是客户端的默认打印机上打印。下面是我用来打印的代码。请帮助我编写该代码。

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;

import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;

import javax.print.event.PrintJobAdapter;
import javax.print.event.PrintJobEvent;

public class PrintText {

public static void main(String[] args) throws PrintException, IOException {

String defaultPrinter = PrintServiceLookup.lookupDefaultPrintService().getName();
System.out.println("Default printer: " + defaultPrinter);
PrintService service = PrintServiceLookup.lookupDefaultPrintService();

// prints the famous hello world! plus a form feed
InputStream is = new ByteArrayInputStream("\nMadha Enterprice\n".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 done ...");
PrintJobWatcher.this.notify();
}
}
});
}

public synchronized void waitForDone() {
try {
while (!done) {
wait();
}
} catch (InterruptedException e) {
}
}
}

最佳答案

使用以下代码:

PrintService service = PrintServiceLookup.lookupDefaultPrintService();

您选择此代码运行的计算机上的默认打印机 - 如果它在服务器上运行,则预计它会在服务器默认打印机上打印。

关于java - 打印机在服务器而不是客户端打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39630951/

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