Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I paint Swing Components to a PDF file with iText?

I would like to print my Swing JComponent via iText to 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( );

Unfortunately nothing is shown in the PDF file. Do you know how to solve this problem?

like image 820
Jonas Avatar asked Jan 08 '09 19:01

Jonas


1 Answers

I have figured it out adding addNotify and validate helps.

    com.addNotify( );
    com.validate( );
like image 81
Jonas Avatar answered Sep 22 '22 23:09

Jonas