我正在尝试打印一个由可滚动JFrame
中的swing组件组成的表单。我已经尝试了下面的代码来做,但我得到的打印只是当前窗口中的滚动区域。我需要打印整页。
代码:
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 */
}
}
}
另外,我需要隐藏一些按钮和textFields来打印。 (例如:“打印”按钮) 任何帮助将不胜感激。
答案 0 :(得分:1)
而不是this.paint( gg );
来电componentInTheScrollPane.paint(gg);
。最好拨打printAll(gg);
答案 1 :(得分:1)
如果您尝试将jScrollPane绘制到图像,则每次都会失败并仅打印可见部分。要解决这个问题,您需要绘制jScrollPane的内容,理想情况下,您将在jScrollPane中有一个jLayer,jPanel或其他容器,并且可以直接将其绘制到这样的图像:
Form (jPanel top container)
-> jScrollPane
-> jLayer/jPanel/container
-> Contents (tables, buttons etc)
我不会给你如何使用整个scrollPane打印整个表单的代码,这需要一些数学和更多的代码,但是为了让你从这里开始是一个示例方法,将jLayer的内容绘制到一个缓冲图像,无论它是否在jScrollPane中不在视图中,然后将该图像保存到文件:(我不会覆盖打印这是另一个问题)
private void button4ActionPerformed() {
try
{
//get height/width from the jLayeredPane or jPanel inside the scroll pane
int imageHeight = jLayeredPane.getHeight();
int imageWidth = jLayeredPane.getWidth();
//Draw contents of the jLayeredPane or jPanel inside the scroll pane (but not the scroll pane itself)
BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D gg = image.createGraphics();
jLayeredPane.paint(gg);
//The "image" now has jLayers contents
//Insert your code here to scale and print the image here
//Some Code
//In my example I have chosen to save the image to file with no scaling
ImageIO.write(canvas, "png", new File("C:\\out.png"));
//Some Code
System.out.println("Done");
}
catch (IOException ex)
{
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
}
}