2009-01-08 58 views
4

我想通过iText将我的Swing JComponent打印为pdf。如何使用iText将Swing组件绘制为PDF文件?

JComponent com = new JPanel(); 
com.add(new JLabel("hello")); 

PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dFile)); 
document.open(); 

PdfContentByte cb = writer.getDirectContent(); 
PdfTemplate tp = cb.createTemplate(pageImageableWidth, pageImageableHeight); 
Graphics2D g2d = tp.createGraphics(pageImageableWidth, pageImageableHeight, new DefaultFontMapper()); 
g2d.translate(pf.getImageableX(), pf.getImageableY()); 
g2d.scale(0.4d, 0.4d); 
com.paint(g2d); 
cb.addTemplate(tp, 25, 200); 
g2d.dispose(); 

很遗憾,PDF文件中没有显示任何内容。 你知道如何解决这个问题吗?

回答

4

我已经想通了添加addNotify和验证帮助。

 
    com.addNotify(); 
    com.validate(); 
+0

是的。 addNotify()的JavaDoc表示它“不应该被程序直接调用”,但实际上,它在无头的情况下是必需的(在没有GUI的情况下导出)。否则,组件的孩子没有布置并保持零大小。 – PhiLho 2012-10-31 13:21:11

1

我对iText不太了解,但是......你在某个时候关闭了PdfWriter,对吧?

+0

是,作家被关闭! – Jonas 2009-01-09 07:25:55

2

我需要调用

com.addNotify() 
com.setSize() 
com.validate()