我正在尝试打印JPanel ...我有工作代码。但问题是,它正在从四面打印带有广泛的magin的JPanel ... Plz有人检查我的代码。并建议我,如何更改我的代码,适用于具有最小边距的A4尺寸纸张。这个代码为actioperformed
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
PrinterJob pjob = PrinterJob.getPrinterJob();
PageFormat preformat = pjob.defaultPage();
preformat.setOrientation(PageFormat.PORTRAIT);
PageFormat postformat = pjob.pageDialog(preformat);
if (preformat != postformat) {
RepairBill r=new RepairBill();
r.setVisible(false);
pjob.setPrintable(new Printer(r.r), postformat); //r.r is the object for JPanel
if (pjob.printDialog()) {
try {
pjob.print();
} catch (PrinterException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
});
打印机类代码
public static class Printer implements Printable {
final Component comp;
public Printer(Component comp) {
this.comp = comp;
}
@Override
public int print(Graphics g, PageFormat format, int page_index) throws PrinterException {
if (page_index > 0) {
return Printable.NO_SUCH_PAGE;
}
// get the bounds of the component
Dimension dim = comp.getSize();
double cHeight = dim.getHeight();
double cWidth = dim.getWidth();
// get the bounds of the printable area
double pHeight = format.getImageableHeight();
double pWidth = format.getImageableWidth();
double pXStart = format.getImageableX();
double pYStart = format.getImageableY();
double xRatio = pWidth / cWidth;
double yRatio = pHeight / cHeight;
Graphics2D g2 = (Graphics2D) g;
g2.translate(pXStart, pYStart);
g2.scale(xRatio, yRatio);
comp.paint(g2);
return Printable.PAGE_EXISTS;
}
}
答案 0 :(得分:0)
我添加了边距:水平1英寸,垂直0.5英寸。
检查边距是否仍可打印(1 mm边距不可行)。
我所做的页面大小没有受到影响,因为这是一个物理设备问题,例如,有人有A4或US Letter。可以在PrintJob中设置它,查看API,网络中的javadoc。
现在按比例缩放。
// get the bounds of the component
Dimension dim = comp.getSize();
double cHeight = dim.getHeight();
double cWidth = dim.getWidth();
// get the bounds of the printable area
double pHeight = format.getImageableHeight();
double pWidth = format.getImageableWidth();
double pXStart = format.getImageableX();
double pYStart = format.getImageableY();
double paperHeight = format.getHeight();
double paperWidth = format.getWidth();
final int INCH = 72;
double vertMargin = 0.5 * INCH;
double horMargin = 1 * INCH;
// Check whether margins are enough, are printable.
if (paperWidth - 2 * horMargin < pWidth) {
pWidth = paperWidth - 2 * horMargin;
pXStart = horMargin
}
if (paperHeight - 2 * vertMargin < pHeight) {
pHeight = paperHeight - 2 * vertMargin;
pYStart = vertMargin;
}
// Determine scaling
double xRatio = pWidth / cWidth;
double yRatio = pHeight / cHeight;
double ratio = Math.min(xRatio, yRation); // Proportional
Graphics2D g2 = (Graphics2D) g;
g2.translate(pXStart, pYStart);
g2.scale(ratio, ratio);
comp.paint(g2);