gpt4 book ai didi

java - 如何2 : Add a JPanel to a Document then export to PDF

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:27:01 25 4
gpt4 key购买 nike

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

问题来了...我有一个 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();
}
}

关于java - 如何2 : Add a JPanel to a Document then export to PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4517907/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com