tags:

views:

12

answers:

1

I have a JFrame, which i wish to save as a PDF. How do i paint this JFrame using iText?

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)  {
        //
    }
}
A: 

This should do the trick (and it's generic for JComponent object):

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)  {
        //
    }
}
Jes