在任何论坛上有关编程的第一篇文章...我通常只是搜索直到找到答案...但是这次我真的被卡住了...

这是问题所在...
我有一个JPanel,最近发现itext为您提供了一种将Java GUI导出为PDF的方法。

我似乎无法理解itext的语言,也无法理解如何将简单的JPanel添加到文档中,然后再将该文档导出为PDF ...这是我目前所拥有的...

import java.io.FileOutputStream;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;

import java.awt.Color;
import javax.swing.*;
public class HelloWorld {

public static void main(String[] args) {
    try
    {
        //Panel creation and setup
        JPanel panel    = new JPanel();

        //just to ensure that the panel has content...
        JLabel label    = new JLabel("i am a label");
        panel.add(label);
        panel.setSize(100,100);
        //so that even if the label doesnt get added...
        //i can see that the panel does
        panel.setBackground(Color.red);


        //my understanding of the code below: the virtual document
        Document document   = new Document();

        //my interpretation just writes the virtual pdf document to the hdd
        PdfWriter writer    = PdfWriter.getInstance
                (document, new FileOutputStream("C:/test.pdf"));

        //begin editing the vpdf
        document.open();


        //i wanna do something like this
        //document.add(panel);

        //end editing the vpdf
        document.close();

    } catch (Exception e)
    {
        System.out.println(e);
    }
}

请帮助...我试图使代码尽可能短,以避免无用的东西...

提前致谢...
克雷格

最佳答案

您需要在面板上调用print并指定要打印到的pdf图形,如下所示:

JPanel panel    = new JPanel();

//just to ensure that the panel has content...
JLabel label    = new JLabel("i am a label");
panel.add(label);
panel.setSize(100,100);
//so that even if the label doesnt get added...
//i can see that the panel does
panel.setBackground(Color.red);

//the frame containing the panel
JFrame f = new JFrame();
f.add(panel);
f.setVisible(true);
f.setSize(100,100);

//print the panel to pdf
Document document = new Document();
try {
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:\\temp\\test.pdf"));
    document.open();
    PdfContentByte contentByte = writer.getDirectContent();
    PdfTemplate template = contentByte.createTemplate(500, 500);
    Graphics2D g2 = template.createGraphics(500, 500);
    panel.print(g2);
    g2.dispose();
    contentByte.addTemplate(template, 30, 300);
} catch (Exception e) {
    e.printStackTrace();
}
finally{
    if(document.isOpen()){
        document.close();
    }
}

10-02 23:47