java 后台 生成的表格通过HtmlImageGenerator(Html2Image) 生成图片,以及解决汉字乱码的问题

本人因为业务需求,需要在后台生成数据表格,然后推送到公众号里面,所以整理了下面这篇文章,可以生产图片

转:https://blog.csdn.net/jishoujiang/article/details/78566759  参考的是这个博客;

在他的基础上改的:但是上面没有说明缺点,下面我将详细的进行介绍:

上面的那篇博客已经很完善了,但是没有给出生产表格的入参,本人就加上了;

package tk.mybatis.web.controller;

import java.util.ArrayList;
import java.util.List;
import gui.ava.html.image.generator.HtmlImageGenerator;

public class TestTable2 {

	private static String getSingleImageHtml(String title, List<String> headTitle, List<List<String>> contentArray) {
		// String html = "<!DOCTYPE html><html><body style=\"width:570px;\">";
		String html = "<table border=\"1\" style=\"border-collapse:collapse;width:570px;border:1px solid black;background: white;\" cellpadding=\"0\" cellspacing=\"0\">";

		html += "<thead>";
		html += "<tr ><th colspan=\"4\" style=\"text-align: center;width: 570px;height:40px;font-size: 22px;\">" + title
				+ "</th></tr>";
		html += "<tr>";
		for (int i = 0; i < 4; i++) {
			String thEle = "";
			thEle = "<th style=\"height:30px;width:" + (i == 2 ? "52%" : "16%")
					+ ";text-align: center;margin:0;color: #ffffff;background:#0070c0;border:1px solid black;font-size: 20px;\">"
					+ headTitle.get(i) + "</th>";
			html += thEle;
		}
		html += "</tr>";
		html += "</thead>";

		html += "<tbody>";
		for (List<String> contents : contentArray) {
			html += "<tr>";
			for (int j = 0; j < 4; j++) {
				String tdEle = "";
				tdEle = "<td style=\"height:30px;width:" + (j == 2 ? "52%" : "16%")
						+ ";text-align: center;margin:0;border:1px solid black;font-size: 18px;\">" + contents.get(j)
						+ "</td>";
				html += tdEle;
			}
			html += "</tr>";
		}

		html += "</tbody>";
		html += "</table>";
		// html+="</body></html>";
		return html;
	}

	public static String graphicsHtmlGeneration(List<List<List<String>>> allValue, List<String> titles,
			List<List<String>> headers) throws Exception {
		int i = 0;
		String html = "";
		for (List<List<String>> list : allValue) {
			String title = titles.get(i);
			List<String> headTitle = headers.get(i);
			html += getSingleImageHtml(title, headTitle, list);
			i++;
		}
		if (html != null && html.length() > 0) {
			HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
			imageGenerator.loadHtml(html);
			try {
				// Thread.sleep(5000);
				imageGenerator.getBufferedImage();
				// Thread.sleep(8000);
				String path = "d:\\1.png";
				imageGenerator.saveAsImage(path);
				return path;
			} catch (Exception e) {
			}
		}
		return null;

	}

	public static void main(String[] args) {
		List<String> allValue1 = new ArrayList<String>();
		allValue1.add("汉字");
		allValue1.add("这个行不11111");
		allValue1.add("最后");
		allValue1.add("6");
		List<List<String>> allValue2 = new ArrayList<>();
		allValue2.add(allValue1);
		allValue2.add(allValue1);
		allValue2.add(allValue1);
		List<List<List<String>>> allValue = new ArrayList<>();
		allValue.add(allValue2);
		List<String> titles = new ArrayList<>();
		titles.add("标题可以识汉字不");
		List<List<String>> headers = new ArrayList<>();
		List<String> header = new ArrayList<>();
		header.add("测试一");
		header.add("北京武汉");
		header.add("哈尔滨");
		header.add("7月营业额");
		headers.add(header);
		try {
			TestTable2.graphicsHtmlGeneration(allValue, titles, headers);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

注意:第一:html不能够添加head,只能是现在这种样子;

          第二:在linux上运行可能会出现中文汉字乱码(中文汉字空格)。这个时候有两种解决办法。第一:https://blog.csdn.net/hu_wen/article/details/78543645;第二:https://blog.csdn.net/eric_hwp/article/details/69524407(这个方法中的第三种);我这边一开始使用的是第一种办法,是在自己电脑的虚拟机上centos,解决了问题;但是到了公司的redhat服务器上就不好使了。我找了很多办法,都没有生效,后来又看了下这个jar包的源码,看用到了awt这个包,后来就去从awt乱码这个方向查了下,就招到了第二种方法,就解决了;如果你项目也用到了awt,也是乱码,原因就是应用没有找到系统的字符集;

记住操作完成需要重启下web服务器(tomcat);

非常感谢上面的两篇博客,在这里解决了我的问题;如有版权问题,请联系我;

顺便把需要的jar包给大家吧:

<dependency>
                <groupId>com.github.xuwei-k</groupId>              
                  <artifactId>html2image</artifactId>
                  <version>0.1.0</version>
</dependency>

有什么问题可以给我留言,如果觉得文章不错,希望得到点赞!

  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
这个需求可以分为以下几个步骤: 1. 使用 Java 代码生成表格图片 2. 调用钉钉群机器人 API 发送通知,附带表格图片 下面是一个简单的示例代码,可以参考实现: ```java import javax.imageio.ImageIO; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.Base64; public class DingtalkBotNotifier { private static final String WEBHOOK_URL = "https://oapi.dingtalk.com/robot/send?access_token=ACCESS_TOKEN"; public static void main(String[] args) throws IOException { // 生成表格图片 BufferedImage image = createTableImage(); // 将图片转成 Base64 编码 ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image, "png", baos); String base64Image = Base64.getEncoder().encodeToString(baos.toByteArray()); // 发送钉钉群机器人通知 sendDingtalkNotification(base64Image); } private static BufferedImage createTableImage() { int columnCount = 3; int rowCount = 5; int cellWidth = 100; int cellHeight = 50; int padding = 10; int borderWidth = 2; int width = columnCount * cellWidth + (columnCount + 1) * padding + 2 * borderWidth; int height = rowCount * cellHeight + (rowCount + 1) * padding + 2 * borderWidth; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g = image.createGraphics(); g.setColor(Color.WHITE); g.fillRect(0, 0, width, height); g.setColor(Color.BLACK); g.setStroke(new BasicStroke(borderWidth)); for (int i = 0; i <= rowCount; i++) { int y = borderWidth + (i + 1) * padding + i * cellHeight; g.drawLine(borderWidth + padding, y, width - borderWidth - padding, y); } for (int j = 0; j <= columnCount; j++) { int x = borderWidth + (j + 1) * padding + j * cellWidth; g.drawLine(x, borderWidth + padding, x, height - borderWidth - padding); } g.setFont(new Font("Arial", Font.PLAIN, 12)); for (int i = 0; i < rowCount; i++) { for (int j = 0; j < columnCount; j++) { int x = borderWidth + (j + 1) * padding + j * cellWidth; int y = borderWidth + (i + 1) * padding + i * cellHeight; String text = "Cell " + (i + 1) + "," + (j + 1); int textWidth = g.getFontMetrics().stringWidth(text); int textHeight = g.getFontMetrics().getHeight(); g.drawString(text, x + (cellWidth - textWidth) / 2, y + (cellHeight + textHeight) / 2); } } g.dispose(); return image; } private static void sendDingtalkNotification(String base64Image) throws IOException { String message = "这是一个表格图片:\n![table](data:image/png;base64," + base64Image + ")"; String encodedMessage = URLEncoder.encode(message, "UTF-8"); String webhookUrl = WEBHOOK_URL.replace("ACCESS_TOKEN", "YOUR_ACCESS_TOKEN"); URL url = new URL(webhookUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); String json = "{\"msgtype\":\"text\",\"text\":{\"content\":\"" + encodedMessage + "\"}}"; byte[] bytes = json.getBytes("UTF-8"); conn.getOutputStream().write(bytes); conn.getOutputStream().flush(); conn.getOutputStream().close(); conn.getInputStream().close(); conn.disconnect(); } } ``` 这个示例代码生成一个 3 列 5 行的表格图片,并发送到钉钉群机器人通知中。你需要将其中的 `YOUR_ACCESS_TOKEN` 替换成你自己的钉钉群机器人的 access token。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值