我正在尝试打印一个由可滚动的摆动组件组成的表单JFrame
。我试过下面的代码来做,但我得到的只是当前窗口中的滚动区域。我需要打印整页。
代码:
public int print(Graphics arg0, PageFormat arg1, int arg2) throws PrinterException {
// TODO Auto-generated method stub
//return 0;
if (arg2 > 0) { /* We have only one page, and 'page' is zero-based */
return NO_SUCH_PAGE;
}
Graphics2D g2d = (Graphics2D)arg0;
g2d.translate((int)arg1.getImageableX(), (int)arg1.getImageableY());
float pageWidth = (float)arg1.getImageableWidth();
float pageHeight = (float)arg1.getImageableHeight();
float imageHeight = (float)this.getHeight();
float imageWidth = (float)this.getWidth();
float scaleFactor = Math.min((float)pageWidth/(float)imageWidth, (float)pageHeight/(float)imageHeight);
int scaledWidth = (int)(((float)imageWidth)*scaleFactor);
int scaledHeight = (int)(((float)imageHeight)*scaleFactor);
BufferedImage canvas = new BufferedImage( this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D gg = canvas.createGraphics();
this.paint( gg );
Image img = canvas ;
g2d.drawImage(img, 0, 0, scaledWidth, scaledHeight, null );
return Printable.PAGE_EXISTS;
}
private void button4ActionPerformed() {
// TODO add your code
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(this);
boolean ok = job.printDialog();
if (ok) {
try {
job.print();
} catch (PrinterException ex) {
System.out.println("Error printing: " + ex);
/* The job did not successfully complete */
}
}
}
我还需要隐藏一些按钮和文本字段以防止打印。(例如:“打印”按钮)任何帮助将不胜感激。