Java API或应用程序是否有办法将CSV表格数据转换为文本并将其转换为带有行和网格和标题的PNG文件?
现在,我在考虑将HTML数据转换为图像的xhtmlrenderer。
更新:安德鲁做出了很好的回应,我将其作为答案。此外,我使用xhtmlrenderer /飞碟与相同的结果将html文档转换为图像。它花了与他的例子相同的努力。
http://code.google.com/p/flying-saucer/
现在,在github上:
https://github.com/berlinbrown/XHTMLRendererForHtmlDataToImage
答案 0 :(得分:2)
您能阅读表格数据并将其放入JTable
吗?
如果是这样,调用 table.paintComponent(Graphics)
是受保护的方法 - 请参阅table.paint(Graphics)
,其中Graphics
对象是从首选大小的图像中获取的该表。
你能提供一个更完整的例子吗?
此示例使用Nimbus PLAF作为“备用行着色”,我认为每个表都应该有。
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.table.JTableHeader;
import javax.imageio.ImageIO;
import java.io.File;
class TableImage {
public static void main(String[] args) throws Exception {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch(Exception useDefault) {
}
Object[][] data = {
{"Hari", new Integer(23), new Double(78.23), new Boolean(true)},
{"James", new Integer(23), new Double(47.64), new Boolean(false)},
{"Sally", new Integer(22), new Double(84.81), new Boolean(true)}
};
String[] columns = {"Name", "Age", "GPA", "Pass"};
JTable table = new JTable(data, columns);
JScrollPane scroll = new JScrollPane(table);
JPanel p = new JPanel(new BorderLayout());
p.add(scroll,BorderLayout.CENTER);
// JTable must have been added to a TLC in order to render
// correctly - go figure.
JFrame f = new JFrame("Never shown");
f.setContentPane(scroll);
f.pack();
JTableHeader h = table.getTableHeader();
Dimension dH = h.getSize();
Dimension dT = table.getSize();
int x = (int)dH.getWidth();
int y = (int)dH.getHeight() + (int)dT.getHeight();
scroll.setDoubleBuffered(false);
BufferedImage bi = new BufferedImage(
(int)x,
(int)y,
BufferedImage.TYPE_INT_RGB
);
Graphics g = bi.createGraphics();
h.paint(g);
g.translate(0,h.getHeight());
table.paint(g);
g.dispose();
JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(bi)));
ImageIO.write(bi,"png",new File("table.png"));
// our TLC forces us to explicitly exit the VM
System.exit(0);
}
}