我正在使用Java进行调查,并且也希望有一个可打印的版本。但是,有些问题不在可视区域之内(它们在JScrollPane中)。以下是我用于打印的代码,但它仅打印JFrame的可视部分。请有人帮忙吗?
private void printFrame(){
PrinterJob printerJob = PrinterJob.getPrinterJob();
printerJob.setPrintable(this);
// pop up a dialog box for the end user to fine tune the options.
if ( printerJob.printDialog() )
{
try
{
// render the component onto the printer or print queue.
printerJob.print();
}
catch ( PrinterException e )
{
System.out.println( "Error printing: " + e );
}
}
}
public int print( Graphics gr, PageFormat pageFormat, int pageIndex ){
if ( pageIndex > 0 )
{
return Printable.NO_SUCH_PAGE;
}
Graphics2D g2d = (Graphics2D)gr;
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
double xScale = 0.33;
double yScale = 0.33;
g2d.scale(xScale, yScale);
paint(g2d);
return Printable.PAGE_EXISTS;
}
提前致谢,
d
最佳答案
谢谢,亚瑟。
现在,我可以使用它:
public void PrintFrameToPDF(File file) {
try {
Document d = new Document();
PdfWriter writer = PdfWriter.getInstance(d, new FileOutputStream(file));
d.open();
PdfContentByte cb = writer.getDirectContent();
PdfTemplate template = cb.createTemplate(PageSize.A4.getWidth(),PageSize.A4.getHeight());
cb.addTemplate(template, 0, 0);
Graphics2D g2d = template.createGraphics(PageSize.A4.getWidth(),PageSize.A4.getHeight());
g2d.scale(0.4, 0.4);
for(int i=0; i< this.getContentPane().getComponents().length; i++){
Component c = this.getContentPane().getComponent(i);
if(c instanceof JLabel || c instanceof JScrollPane){
g2d.translate(c.getBounds().x,c.getBounds().y);
if(c instanceof JScrollPane){c.setBounds(0,0,(int)PageSize.A4.getWidth()*2,(int)PageSize.A4.getHeight()*2);}
c.paintAll(g2d);
c.addNotify();
}
}
g2d.dispose();
d.close();
} catch (Exception e) {
System.out.println("ERROR: " + e.toString());
}
}
如果有人对以上内容有最佳选择,我很想听听您的意见。谢谢您的帮助!
d