1
設置默認邊距爲我的網頁我有一個80毫米*297毫米紙打印頁面。我使用下面的代碼:我怎樣才能在Java
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());
}
}
的代碼工作正常,但唯一的問題是,人們必須每使用此代碼時設置頁邊距。預設邊距離頂部20mm,左側21mm,底部18mm。 所以文本不適合小頁面。 如何從我的代碼設置自定義邊距?或者我可以設置默認的打印機設置,以便我不需要每次都設置頁邊距?