Paint Swing Component to PDF using iText

2019-08-07 09:53发布

问题:

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

回答1:

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


标签: jframe itext