Java 如何将可滚动的jpanel保存为pdf或任何格式

Java 如何将可滚动的jpanel保存为pdf或任何格式,java,swing,pdf,jpanel,itext,Java,Swing,Pdf,Jpanel,Itext,我在jscrollpane中有一个jpanel,我想将jpanel的所有内容(包括一些label,textarea)导出为pdf格式。目前我在jbutton上使用此代码: Document document = new Document(PageSize.A4.rotate(),50,50,50,50); try { PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:\\Users\\Admin\

我在jscrollpane中有一个jpanel,我想将
jpanel
的所有内容(包括一些
label
textarea
)导出为pdf格式。目前我在
jbutton
上使用此代码:

Document document = new Document(PageSize.A4.rotate(),50,50,50,50);
try {
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:\\Users\\Admin\\Desktop\\test1.pdf"));
document.open();
PdfContentByte contentByte = writer.getDirectContent();
//jp is the jpanel
PdfTemplate template = contentByte.createTemplate(jp.getWidth(), jp.getHeight());
Graphics2D g2 = template.createGraphics(jp.getWidth(),jp.getHeight());
g2.scale(0.8, 1);
        jp.printAll(g2); // also tried with jp.paint(g2), same result
        g2.dispose();

        //document.close();
contentByte.addTemplate(template, 5, 60);
} catch (Exception e) {
e.printStackTrace();
}
finally{
if(document.isOpen()){
    document.close();
}

}
输出:我得到的是pdf格式的
jpanel
的下半部分…(我制作了jpanel的sanpshot,但我的声誉不允许发布图像),上半部分被丢弃。我认为最后一部分是在使用单页时导出的。第一部分写得太多(这只是猜测!) 为了查看整个
jpanel
我们需要滚动。。。当jpanel的高度超过A4页时,如何将整个面板(从上到下)导出为pdf到多页。请提供帮助。提前谢谢


注意:我正在使用netbeans开发我的gui和
itextpdf-5.4.1
。我是java编程的初学者。

您需要关闭
PrintWriter
并尝试添加addNotify、validate

jp.addNotify();
jp.setSize();
jp.validate();