邮件显示统计图表echarts-java+phantomjs实现

邮件显示统计图表echarts-java+phantomjs实现

项目背景是产品业务上的订阅推送,纯java后端实现,通过邮件将统计报表发送给用户。这里会涉及一些关键点:

  • 首先是统计图表的生成,我们采用常见的echarts,简单易用,支持图表类型丰富美观;java后端实现可使用echarts-java来实现图表的生成。
  • 其次使用模板渲染的方式将获取到的订阅数据(标题,日期,描述,统计图表,列表)渲染成html,这里使用handlebars实现模板渲染。文档地址:https://handlebarsjs.com/zh/guide/
  • 将渲染后的html,作为邮件内容发送给想用用户。

1 首选解决echarts图表生成

<!-- https://mvnrepository.com/artifact/org.icepear.echarts/echarts-java -->
<dependency>
    <groupId>org.icepear.echarts</groupId>
    <artifactId>echarts-java</artifactId>
    <version>1.0.7</version>
</dependency>

项目中添加上述依赖,echarts-java为java生成echarts的option或者完整的html提供了简洁的接口。目前好像不在更新维护了,所以没有提供直接生成图片或者相关的功能。

@Slf4j
public class ChartGenHandle {
   

    private static final String TEMPLATE_PREFIX = "templates/";
    private static final String EMPTY_REPORT = "empty-push-template";
    private static final String BO_REPORT = "bo-push-template";
    private static final String REPORT_CENTER = "center";

    public static final Map<String, Template> TEMPLATES = new ConcurrentHashMap<>();

    public static String genReport(String title, String summary, List<BaseNameValue<String, Integer>> barData,
                                  List<BaseNameValue<String, Integer>> pieData, List<ReportDataVO> details) {
   
        ReportVO reportData = new ReportVO();
        try {
   
            Handlebars handlebars = new Handlebars();
            String path = TEMPLATE_PREFIX + BO_REPORT;
            Template template = TEMPLATES.getOrDefault(path, handlebars.compile(path));
            reportData.setTitle(title);
            reportData.setSummary(summary);
            Engine engine = new Engine();
            reportData.setBar(engine.renderJsonOption(genBar(barData)));
            reportData.setPie(engine.renderJsonOption(genPie(pieData)));
            reportData.setDetails(details);
            return template.apply(reportData);
        } catch (IOException e) {
   
            log.error("报告生成异常:template=" + BO_REPORT + ",params=" + JSON.toJSONString(reportData), e);
        }
        return null;
    }

    public static String genHtml(Chart<?, ?> chart) {
   
        Engine engine = new Engine();
        return engine.renderHtml(chart);
    }

    public static Bar genBar(List<BaseNameValue<String, Integer>> datas) {
   
        if (datas == null || datas.isEmpty()) {
   
            return new Bar().setTitle(new Title()
                    .setLeft(REPORT_CENTER).setRight(REPORT_CENTER).setTop(REPORT_CENTER).setBottom(REPORT_CENTER)
                    .setText("无数据").setTextStyle(new Label().setFontSize(20).setFontWeight("normal")));
        }
        String[] names = new String[datas.size()];
        Integer[] values = new Integer[datas.size()];
        for (int i = 0; i < datas.size(); i++) {
   
            BaseNameValue<String, Integer> data = datas.get(i);
            names[i] = data.getName();
            values[i] = data.getValue();
        }
        return new Bar().setLegend().setTooltip("item")
                .addXAxis(names)
                .addYAxis()
                .addSeries(values);
    }

    public static Pie genPie(List<BaseNameValue<String, Integer>> datas) {
   
        if (datas == null || datas.isEmpty()) {
   
            return new Pie().setTitle(new Title()
                    .setLeft(REPORT_CENTER).setRight(REPORT_CENTER).setTop(REPORT_CENTER).setBottom(REPORT_CENTER)
                    .setText("无数据").setTextStyle(new Label().setFontSize(20).setFontWeight("normal")));
        }
        List<PieDataItem> items = datas.stream().map(data -> new PieDataItem().setName(data.getName()).setValue(data.getValue()))
                .collect(Collectors.toList());
        return new Pie()
                .addSeries(new PieSeries()
                        .setRadius(new String[]{
   "40%", "70%"})
                        .setItemStyle(new PieItemStyle().setBorderRadius(10).setBorderColor("#fff").setBorderWidth(2))
                        .setLabel(new PieLabel().setShow(true).setPosition("outside").setFormatter("{b}:{c}({d}%)")
                                .setFontWeight("bold").setOverflow("break"))
                        .setData(items.toArray()));
    }
}
@Data
class ReportVO {
   
    private String title;
    private String summary;
    private String pushDate;
    private String bar;
    private String pie;
    private List<ReportDataVO> details;
}
@Data
class ReportDataVO {
   
    private String name;
    private String area;
    private String age;
}
@Data
class BaseNameValue<K, V> {
   
    private K name;
    private V value;
}

模板如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <script
            src="https://cdnjs.cloudflare.com/ajax/libs/echarts/5.2.2/echarts.min.js"
            integrity="sha512-ivdGNkeO+FTZH5ZoVC4gS4ovGSiWc+6v60/hvHkccaMN2BXchfKdvEZtviy5L4xSpF8NPsfS0EVNSGf+EsUdxA=="
            crossorigin="anonymous"
            referrerpolicy="no-referrer"></script>
    <title>推送报告</title>
</head>

<body class="mail-template">
<h1>{
  {title}}</h1>
<h3 align="center">来源:<a href="http://xxxxxxx">推送平台</a> </h3>
<section class="business-overview">
    <h2>1、概览</h2>
    <div class="content">{
  {
  {summary}}}</div>
</section>
<section class="business-type">
	<h2>2、统计</h2>
    <h3>区域分布</h3>
    <div id="area-bar" style="height: 600px"
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值