2009-01-08 56 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()