我正在尝试从我的java应用程序打印到收据打印机, 收据的宽度是58毫米,似乎边距不正确,并在两边打印边缘为1英寸。这导致仅打印3个字母/数字而不是整行。 我可以成功地从记事本打印,因为我手动将边距调整为1.97mm,这似乎可以解决问题。
我的代码如下;
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 :(得分: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();
}
似乎是一种临时解决方案,但如果没有其他任何问题,它将成为永久性的。