如何使用iText将Swing组件绘制为PDF文件?

Jon*_*nas 5 java pdf swing pdf-generation itext

我想通过iText将我的Swing JComponent打印到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( );
Run Code Online (Sandbox Code Playgroud)

不幸的是,PDF文件中未显示任何内容。你知道如何解决这个问题吗?

Jon*_*nas 4

我已经弄清楚添加 addNotify 和 validate 有帮助。

    com.addNotify();
    com.validate();