【问题标题】:How do I paint Swing Components to a PDF file with iText?如何使用 iText 将 Swing 组件绘制到 PDF 文件?
【发布时间】:2010-09-30 08:21:57
【问题描述】:

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

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

【问题讨论】:

    标签: java swing pdf pdf-generation itext


    【解决方案1】:

    我已经想通了添加 addNotify 和 validate 帮助。

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

    【讨论】:

    • 是的。 addNotify() 的 JavaDoc 说它“不应该被程序直接调用”,但实际上,在无头上下文中是必要的(在没有 GUI 的情况下导出)。否则,组件的子级不会布局并保持大小为零。
    【解决方案2】:

    我需要打电话

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

    【讨论】:

      【解决方案3】:

      我对 iText 了解不多,但是...您确实在某个时候关闭了 PdfWriter,对吧?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-19
        • 2010-11-21
        • 1970-01-01
        • 2012-02-12
        相关资源
        最近更新 更多