2013-04-28 53 views
1

我有一个jscrollpane内的jpanel,我想将所有内容jpanel(其中包括一些labeltextarea)导出为pdf格式。目前我使用一个jbutton此代码:如何将可滚动jpanel保存为pdf或任何格式

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页面。请帮助。提前致谢。

注:我使用netbeans来开发我的gui和itextpdf-5.4.1。我是一个java编程的初学者。

回答

0

您需要关闭PrintWriter,也尝试加入信息addNotify,验证

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