2016-04-24 132 views
0

我試圖從我的java應用程序打印到收據打印機, 收據的寬度爲58mm,似乎邊距不正確,並且打印的邊距爲1英寸任何一邊。這導致只打印3個字母/數字而不是整行。 我可以成功地從記事本打印,因爲我已經手動調整邊緣到1.97毫米在任何一方似乎做的伎倆。Java:設置可打印寬度(Pageformat)

我的代碼如下;

public int print(Graphics g, PageFormat pf, int pageIndex) 
     throws PrinterException { 

    Font font = new Font("MONOSPACED", Font.PLAIN, 10); 
    FontMetrics metrics = g.getFontMetrics(font); 
    int lineHeight = metrics.getHeight(); 
    if (pageBreaks == null) { 
     initTextLines(); 
     int linesPerPage = (int)(pf.getImageableHeight()/lineHeight); 
     int numBreaks = (textLines.length-1)/linesPerPage; 
     pageBreaks = new int[numBreaks]; 
     for (int b=0; b<numBreaks; b++) { 
      pageBreaks[b] = (b+1)*linesPerPage; 
     } 
    } 

    if (pageIndex > pageBreaks.length) { 
     return NO_SUCH_PAGE; 
    } 

    /* User (0,0) is typically outside the imageable area, so we must 
    * translate by the X and Y values in the PageFormat to avoid clipping 
    * Since we are drawing text we 
    */ 
    Graphics2D g2d = (Graphics2D)g; 
    g2d.setFont(new Font("MONOSPACED", Font.PLAIN, 10)); 
    g2d.translate(pf.getImageableX(), pf.getImageableY()); 

    /* Draw each line that is on this page. 
    * Increment 'y' position by lineHeight for each line. 
    */ 
    int y = 0; 
    int start = (pageIndex == 0) ? 0 : pageBreaks[pageIndex-1]; 
    int end = (pageIndex == pageBreaks.length) 
      ? textLines.length : pageBreaks[pageIndex]; 
    for (int line=start; line<end; line++) { 
     y += lineHeight; 
     g.drawString(textLines[line], 0, y); 
    } 

    /* tell the caller that this page is part of the printed document */ 
    return PAGE_EXISTS; 
} 

我也很感激,如果你能幫助我對齊文本到收貨的右手側,以保持它穿制服用了其它系統,但是我的主要問題是,如果是分類,我將保證金超過月亮:)

謝謝!

p.s.我是新來的java打印和努力,可能有複製在線來源的冗餘代碼。我已經調整了字體,使它更小,這並沒有多大幫助。

回答

0

我已經想出了一個解決方法來獲得所需的結果,只是在文本似乎工作良好之前添加空格,我也調整了代碼如下;

public void print() throws PrintException, IOException { 
    String defaultPrinter = 
      PrintServiceLookup.lookupDefaultPrintService().getName(); 
    System.out.println("Default printer: " + defaultPrinter); 
    PrintService service = PrintServiceLookup.lookupDefaultPrintService(); 

    InputStream is = new ByteArrayInputStream(printableAmounts.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(); 
} 

似乎是一個臨時的解決方案,但如果沒有別的來了就會變成永久性的。