我必须在 80 毫米 * 297 毫米的纸张上打印一页。我正在使用以下代码:
public static void printCard(final String bill ){
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());
pageFormat.setOrientation(PageFormat.PORTRAIT);
Paper pPaper = pageFormat.getPaper();
pPaper.setImageableArea(1.0, 1.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;
}
};
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(contentToPrint);
boolean dojob = job.printDialog();
//You can show a print dialog before printing by job by wrapping the following blocks with a conditional statement if(job.printDialog()){...}
try {
job.print();
} catch (PrinterException e) {
System.err.println(e.getMessage());
}
}
该代码运行良好,但唯一的问题是每次使用此代码都必须设置边距。预设边距为距顶部 20 毫米、距左侧 21 毫米和距底部 18 毫米。所以文本不适合小页面。如何从我的代码中设置自定义边距?或者我可以设置默认打印机设置,这样我就不需要每次都设置边距?