Paint Swing Component to PDF using iText

我怕爱的太早我们不能终老 提交于 2020-01-05 08:57:23

问题


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


来源:https://stackoverflow.com/questions/3109145/paint-swing-component-to-pdf-using-itext

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!