5

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?

Michael Myers
  • 188,989
  • 46
  • 291
  • 292
Jonas
  • 232
  • 3
  • 13

3 Answers3

4

I have figured it out adding addNotify and validate helps.

    com.addNotify( );
    com.validate( );
Jonas
  • 232
  • 3
  • 13
  • Yes. JavaDoc of addNotify() says it "should not be called directly by programs", but in practice, it is necessary in headless context (exporting without a GUI). Otherwise, the children of the component are not laid out and keep a size of zero. – PhiLho Oct 31 '12 at 13:21
2

I needed to call

com.addNotify()
com.setSize()
com.validate()
Sam Barnum
  • 10,559
  • 3
  • 54
  • 60
1

I don't know that much about iText, but... you did close the PdfWriter at some point, right?

Michael Myers
  • 188,989
  • 46
  • 291
  • 292