2012-05-27 114 views
0

我需要在热敏打印机中逐行打印。在%n的线断行 我想坚持字符串模式,而打印.. 我不熟悉打印机API和图形2DADI ..我需要修复这1小时的时间.. 将不胜感激快速答案.. 预先感谢 我的字符串格式是这样的:如何使用打印机API在JAVA中打印用于打印的文本?

String printStat = 
         "    *****     %n" 
         + "  W*** OF ** AND *****  %n" 
         + "  4/400 kfjkasjfdkas ajdksa  %n" 
         + " aksdka ajke ajeklaje kajke ka a %n" 
         + " Date: "+now.get(Calendar.DAY_OF_MONTH)+"/"+(now.get(Calendar.MONTH)+1)+"/"+now.get(Calendar.YEAR)+"    Time: "+now.get(Calendar.HOUR_OF_DAY)+":"+now.get(Calendar.MINUTE)+"%n" 
         + "--------------------------------------%n" 
         + " Name   Qty  Price %n" 
         + "--------------------------------------%n"; 

打印方法:

@Override 
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException { 
     /* We'll assume that Jav2D is available. Create a copy 
     * of it so that we can pass the original Graphics 
     * instance to the PageFormat instance. 
     */ 
     Graphics2D g2d = (Graphics2D) graphics.create(); 
     /* Move the origin from the corner of the Paper to the corner 
     * of the imageable area. 
     */ 
     g2d.translate(format.getImageableX(), format.getImageableY()); 
     /* Set the text color. 
     */ 
     g2d.setPaint(Color.black); 
     g2d.setFont(new Font("Arial", Font.BOLD, 10)); 
     /* Use a LineBreakMeasurer instance to break our text into 
     * lines that fit the imageable area of the page. 
     */ 
     Point2D.Float pen = new Point2D.Float(); 
     AttributedCharacterIterator charIterator = mStyledText.getIterator(); 
     //LineBreakMeasurer measurer = new LineBreakMeasurer(charIterator, g2d.getFontRenderContext()); 
     LineBreakMeasurer measurer = new LineBreakMeasurer(charIterator, g2d.getFontRenderContext()); 
     float wrappingWidth = (float) format.getImageableWidth(); 
     while (measurer.getPosition() < charIterator.getEndIndex()) { 

     TextLayout layout = measurer.nextLayout(wrappingWidth); 
     pen.y += layout.getAscent(); 
     float dx = layout.isLeftToRight() ? 0 : (wrappingWidth - layout.getAdvance()); 
     layout.draw(g2d, pen.x + dx, pen.y); 
     pen.y += layout.getDescent() + layout.getLeading(); 
     } 
     g2d.dispose(); 
     g2d = null; 
     /* Calling the PageFormat is not part of the printing API, 
     * but it is a useful convention. In this example PageFormat 
     * does not implement Printable and so it is not invoked here. 
     * In later examples, PageFormat will implement Printable. 
     */ 
     try { 
     Printable formatPainter = (Printable) format; 
     formatPainter.print(graphics, format, pageIndex); 
     /* Nothing to do here. The PageFormat has nothing to print. 
     */ 
     } catch (ClassCastException exception) { 
     } 
     return Printable.PAGE_EXISTS; 
     } 

回答

1

使用固定宽度的字体,替换宋体用“等宽”或“信使”。

+0

谢谢,确实有一个统一的宽度。 对于换行符,我修改了迭代通过分隔打印字符串在分隔符处(行尾)并绘制每行所生成的数组的打印方法。不知道这是否是最好的方式..但工作! – bmusical