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

时间:2022-09-04 21:10:36

I would like to print my Swing JComponent via iText to pdf.

我想通过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( );

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

遗憾的是,PDF文件中没有显示任何内容。你知道如何解决这个问题吗?

3 个解决方案

#1


I have figured it out adding addNotify and validate helps.

我已经想到添加addNotify并验证帮助。

    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?

我对iText知之甚少,但是......你确实在某个时候关闭了PdfWriter,对吧?

#1


I have figured it out adding addNotify and validate helps.

我已经想到添加addNotify并验证帮助。

    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?

我对iText知之甚少,但是......你确实在某个时候关闭了PdfWriter,对吧?