我正在使用以下代码在带有 80 毫米卷纸的热敏打印机上打印一些文本:
public class printnow {
public static void printCard(final String bill) {
final PrinterJob job = PrinterJob.getPrinterJob();
Printable contentToPrint = new Printable() {
@Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
Graphics2D g2d = (Graphics2D) graphics;
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
g2d.setFont(new Font("Monospaced", Font.BOLD, 7));
pageFormat.setOrientation(PageFormat.PORTRAIT);
Paper pPaper = pageFormat.getPaper();
pPaper.setImageableArea(0, 0, pPaper.getWidth() , pPaper.getHeight() -2);
pageFormat.setPaper(pPaper);
if (pageIndex > 0)
return NO_SUCH_PAGE; //Only one page
String Bill [] = bill.split(";");
int y = 0;
for (int i = 0; i < Bill.length; i++) {
g2d.drawString(Bill[i], 0, y);
y = y + 15;
}
return PAGE_EXISTS;
}
};
boolean don = job.printDialog();
job.setPrintable(contentToPrint);
try {
job.print();
} catch (PrinterException e) {
System.err.println(e.getMessage());
}
}
}
这打印得非常好,正是我想要的。但是,当我删除以下行以禁用打印对话框并自动执行打印过程时,我的打印混乱并且打印机自动在左侧留出一些边距。
boolean don = job.printDialog();
关于为什么会发生这种情况以及如何解决的任何想法?