java生成带表格的png图片,用于将表格数据转换为PNG图像文件的Java API或工具

Is there a way a Java API or application to convert CSV tabular data as text and convert that into a PNG file with lines and a grid and header?

Right now, I am thinking xhtmlrenderer which converts HTML data into an image.

Updated: Andrew gave a good response, I set that as the answer. Also, I used xhtmlrenderer/flying saucer with the same result to convert a html document to an image. It took the same amount of effort as his example.

Now, on github:

解决方案

Can you read the tabular data and put it into a JTable?

If so, call table.paintComponent(Graphics) is a protected method - see instead table.paint(Graphics), where the Graphics object is obtained from an image that is the preferred size of the table.

Could you provide a more complete example?

HICg3.png

This example uses the Nimbus PLAF for the 'alternate row shading' which I think every table should have.

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);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值