2012-12-25 32 views
0

我現在已經設法在JSF中創建了一個允許用戶上傳文本文件的上傳文件,我也可以顯示它。我設法將其打印到連接到客戶端的打印機。如何將此文本打印到使用Java代碼連接到服務器端的打印機?如何從字符串中打印出文本

回答

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();

+0

非常感謝你,現在我要試試這個,是有它發送的任何方式來打印到打印機隊列或打印機的IP地址而不是選擇打印機? – user1924104

+0

如果您需要打印默認打印機,只需發送它即可。如果用戶選擇,添加一個jsf彈出窗口來選擇打印機 – vels4j