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

回眸只為那壹抹淺笑 提交于 2019-11-28 04:29:40

问题


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?


回答1:


I have figured it out adding addNotify and validate helps.

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



回答2:


I needed to call

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



回答3:


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



来源:https://stackoverflow.com/questions/425590/how-do-i-paint-swing-components-to-a-pdf-file-with-itext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!