1
我有一個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) {
}
}
}
你是什麼意思服務器?我在這裏沒有看到任何客戶機/服務器體系結構...此代碼是否在服務器上運行,並且是Web應用程序的一部分,還是正在運行您在'客戶機'上發佈的確切代碼? – Plirkee
這不是確切的程序,而是我使用的確切邏輯。我使用澤西休息api與相同的邏輯打印到客戶機。服務器是Tomcat7。 –
如果此代碼在服務器端執行 - 它將在服務器端打印。它是如此簡單。你沒有清楚地說明這個代碼是如何被調用的......所以不清楚執行的地方。但是從你的問題描述中,我會推斷它在服務器端執行... – Plirkee