使用iText将Swing组件绘制为PDF

时间:2010-06-24 10:36:45

标签: jframe itext

我有一个JFrame,我希望以PDF格式保存。 如何使用iText绘制此JFrame?

public PrintFrameToPDF(JFrame bill)  {
    try {
        Document d = new Document();
        PdfWriter writer = PdfWriter.getInstance(d, new FileOutputStream ("sample.pdf"));

        d.open ();

        // HOW ?

        d.close ();
    }
    catch(Exception e)  {
        //
    }
}

1 个答案:

答案 0 :(得分:2)

这应该可以解决问题(它对JComponent对象来说是通用的):

public PrintFrameToPDF(JFrame bill)  {
    try {
        Document d = new Document();
        PdfWriter writer = PdfWriter.getInstance(d, new FileOutputStream ("sample.pdf"));
        d.open ();

        PdfContentByte cb = writer.getDirectContent( );
        PdfTemplate template = cb.createTemplate(width, height);
        Graphics2D g2d = template.createGraphics(width, height);
        bill.print(g2d);
        bill.addNotify();
        bill.validate();
        g2d.dispose();

        d.close ();
    }
    catch(Exception e)  {
        //
    }
}