我在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
,我们需要滚动...如何将整个面板(从上到下)导出为pdf到多个页面,因为jpanel的高度超过A4页面。请这样做帮助。提前致谢。
注意:我正在使用 netbeans 来开发我的 gui 和 itextpdf-5.4.1
。我是 java 编程的初学者。
最佳答案
您需要关闭PrintWriter
并尝试添加addNotify,validate
jp.addNotify();
jp.setSize();
jp.validate();
关于java - 如何将可滚动 jpanel 保存为 pdf 或任何格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16261817/