2012-11-19 89 views
2

在更大的應用程序環境中,我的小程序需要將一些數據打印到Zebra或Dymo(取決於用戶安裝的內容)標籤打印機。向打印機發送轉義碼(原始數據)的正確方法

我收到的數據是轉義形式的數據,我只需要發送到打印機並讓它解釋它。

搜索我發現了兩種解決方案。 方法1:

byte[] printdata; 
PrintService pservice = PrintServiceLookup.lookupDefaultPrintService(); //or get the printer in some other way 
DocPrintJob job = pservice.createPrintJob(); 
DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE; 
Doc doc = new SimpleDoc(printdata, flavor, null); 

和方法2:

PrintStream printStream = new PrintStream(new FileOutputStream(「LPT1」)); 
printStream.print(「Hello World」); 
printStream.close(); 

我想這能跨平臺工作,使用USB或串行端口的打印機。 什麼是正確方式來實現這種行爲?與方法2

的一個問題是,我需要找到相同的方式,打印機的URL ...

回答

3
public String rawprint(String printerName, String conte) { 
    String res = ""; 
    PrintServiceAttributeSet printServiceAttributeSet = new HashPrintServiceAttributeSet(); 
    printServiceAttributeSet.add(new PrinterName(printerName, null)); 
    PrintService printServices[] = PrintServiceLookup.lookupPrintServices(null, printServiceAttributeSet); 
    if (printServices.length != 1) { 
     return "Can't select printer :" + printerName; 
    } 
    byte[] printdata = conte.getBytes(); 
    PrintService pservice = printServices[0]; 
    DocPrintJob job = pservice.createPrintJob(); 
    DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE; 
    Doc doc = new SimpleDoc(printdata, flavor, null); 
    PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet(); 
    try { 
     job.print(doc, aset); 
    } catch(Exception e){ 
     res = e.getMessage(); 

    } 
    return res; 
} 

作品中的JavaFX

+0

酷我跟着你的答案,但無法打印的圖像文件。 – Lokesh

0

六角打印是值得信賴的。撥打String.getBytes(encoding),然後用System.out.format以十六進制數字打印每個字節。

相關問題