使用phantomjs实现highcharts等报表通过邮件发送

使用phantomjs实现highcharts等报表通过邮件发送(本文仅提供完整解决方案和实现思路,完全照搬不去整理代码无法马上得到效果)

 

前不久项目组需要将测试相关的质量数据通过每日自动生成报表展示,并自动通过将报表作为邮件正文内容知会到干系人邮箱。那么问题来了,报表生成了,但是邮件怎么发送,因为highcharts等报表都是通过JS和HTML在前端浏览器进行渲染生成的,而最要命的是邮箱为了安全起见一般都不支持JS,所以就算后台计算出了报表所需的数据,但是也无法在邮件内容中生成报表。 后来想到phantomjs这个神器,它是一个基于webkit的内核浏览器,可以不弹出浏览器界面在内存中模拟打开网页,进而加载需要的东东(当然包括highchars等依靠JS生成的报表渲染);  于是采用以下解决方案

1. 用JAVA从数据库查询出报表需要的各种数据

2. 在服务器通过JAVA跨进程调用phantomjs启动进程打开指定的URL,加载和渲染highchars报表

3. 等待若干秒,渲染完highchars报表后,调用phantomjs的网页截屏功能,将当然网页内容(报表内容)截图保存成一个指定URI的图片PNG或者JPG,保存到服务器某个指定目录

4. 在邮件中直接用<img src="服务器上保存的报表图片URI"> 进行引用加载图片

相关参考代码:

1. 新建你的JAVA类,发送邮件主JAVA方法:

。。。。用java去数据库取出报表所需数据,省略。。。

// 初始化趋势图片

ServletContext servletContext = ContextLoaderListener.getCurrentWebApplicationContext().getServletContext();
String ip = "IP";
int port = 8080;
String contextPath = servletContext.getContextPath();


String url =
"http://" + ip + ":" + port + contextPath + "/" + "router.do?service=testReport.testReportChart";

rootMap.put("chartUrl", url);

// String outfile = "/images"+contextPath+"/testReportChart/"+new Date().getTime()+"_"+new
// Random().nextInt(9999)+".png" ;

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmSS");
Date date = new Date();
String outfile_suffix =
"testReportChart/" + sdf.format(date) + date.getTime() + "_" + new Random().nextInt(9999) + ".png";

String outfile = "/xxx路径/apache-tomcat-7.0.54/webapps/ROOT/" + outfile_suffix;
String outfileUrl = "http://" + ip + ":" + port + "/" + outfile_suffix;

// phantomjs文件存放位置
String infile = servletContext.getRealPath("/") + "js/phantomjs/capture.js";

try
{

  //PhantomjsUtil.initHighchartImage为调用phantomjs并返回结果   infile为phantomjs脚本文件,outfile为phantomjs生成图片后保存的服务器URI
   if ("success".equalsIgnoreCase(PhantomjsUtil.initHighchartImage(infile, url, outfile)))
   {
        rootMap.put("count404Image", outfileUrl);

   }
else
{
// 默认图片
rootMap.put("count404Image", "http://URL/1208_tOl.gif");
}
}
catch (Exception e)
{
// 默认图片
rootMap.put("count404Image", "http://url/1208_tOl.gif");
e.printStackTrace();
}

。。。

result = testReportService.sendTemplateMail(rootMap, from, toEmail, cc, subject, templateName);

}

2.新建JAVA类PhantomjsUtil.java实现phantomjs调用(确保服务器上安装好了phantomjs以及配置好环境变量)

package com.vipshop.util.hcharts.svg;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class PhantomjsUtil
{

/**
* @author sea.zeng
* @param infile String infile = " d:/phantomjs/capture.js " ;
* @param url String url = " http://ip:8080/xxx/router.do?service=xxxReport.xxxReportChart " ;
* @param outfile String outfile = " D:/phantomjs/testReportChart"+new Date().getTime()+"_"+new
* Random().nextInt(9999)+".png" ;
* @return String fail success
* @throws IOException
*/
public static String initHighchartImage(String infile, String url, String outfile)
throws IOException
{
String shell = " phantomjs ";

Runtime rt = Runtime.getRuntime();
Process p = rt.exec(shell + " " + infile + " " + url + " " + outfile);
InputStream is = p.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuffer sbf = new StringBuffer();
String tmp = "";

while ((tmp = br.readLine()) != null)
{
sbf.append(tmp);
}

  return sbf.toString();

}

}

3. 新建phantomjs的脚本文件capture.js并存放到指定目录js/phantomjs/下


var page = require(‘webpage‘).create(); 
var system = require(‘system‘) ;
var url = system.args[1];
var outUri = system.args[2];

page.viewportSize = { 1400, height: 450 };
page.open(url, function (status) {
if (status !== ‘success‘) {
console.log(‘fail‘);
} else {
window.setTimeout(function () {
console.log(‘success‘); 
page.render(outUri);
phantom.exit();
}, 10000);
}
});

4. highchars图表定义文件testReport_chart.ftl

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>xxxx趋势图</title>


<script type="text/javascript" src="http://${rootMap.ip}:${rootMap.port}/xxx/js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="http://${rootMap.ip}:${rootMap.port}/xxx/js/highcharts.js"></script>
<script type="text/javascript" src="http://${rootMap.ip}:${rootMap.port}/xxx/js/exporting.js"></script>
<script type="text/javascript" src="http://${rootMap.ip}:${rootMap.port}/xxx/js/highcharts-3d.js"></script>
<script>

</script>

</head>


<body>

<div id="container" style="min-700px;height:400px"></div>

</body>

</html>

<script>

function initHighCharts(newCountArray,closeCountArray,datesArray)
{


var closeDate = datesArray;

var closeArray = eval(‘([‘ + closeCountArray + ‘])‘);

var newArray = eval(‘([‘ + newCountArray + ‘])‘);

$(‘#container‘).highcharts({
chart: {
type: ‘line
},
title: {
text: ‘缺陷日新增与日关闭趋势图‘
},
subtitle: {
text: ‘App-特卖会‘
},
xAxis: {
/*categories: [‘Jan‘, ‘Feb‘, ‘Mar‘, ‘Apr‘, ‘May‘, ‘Jun‘, ‘Jul‘, ‘Aug‘, ‘Sep‘, ‘Oct‘, ‘Nov‘, ‘Dec‘]*/
categories:closeDate 
},
yAxis: {
title: {
text: ‘单位 (个)‘
}
},
tooltip: {
enabled: false,
formatter: function() {
return ‘<b>‘+ this.series.name +‘</b><br/>‘+this.x +‘: ‘+ this.y +‘°C‘;
}
},
plotOptions: {
line: {
dataLabels: {
enabled: true
},
enableMouseTracking: false
}
},
series: [{
name: ‘日新增‘,
data: newArray
}, {
name: ‘日关闭‘,
data: closeArray
}]


});
}

//异步得到需要的版本统计数据 
function queryCountList()
{

var version = $(‘#version‘).val();
if( isEmpty(version))
{

alert("不要偷懒,请先选择版本吧...");
document.getElementById(‘version‘).focus();
return false;
}

$.post("bugzillapost.php", 
{
methodType:‘queryCountList‘,
version:version
}, 
function(data)
{

$("#content").html("");


var obj = JSON.parse(data); 


if (obj.bugzillaCountList != undefined )
{

var bugzillaCountList = JSON.parse(obj.bugzillaCountList);


var trHtml = ‘‘ ;


if(null != bugzillaCountList && bugzillaCountList.length > 0)
{

for(var i=0;i < bugzillaCountList.length;i ++ )
{

var trClass = (i%2 == 0) ?"odd":"even" ;
trHtml += ‘<tr class="‘+trClass+‘">‘;
trHtml += ‘<td >‘+(i+1)+‘</td>‘;
trHtml += ‘<td >‘+bugzillaCountList[i].rep_platform+‘</td>‘ ;
trHtml += ‘<td >‘+bugzillaCountList[i].op_sys+‘</td>‘;
trHtml += ‘<td >‘+bugzillaCountList[i].bug_severity+‘</td>‘ ;
trHtml += ‘<td >‘+bugzillaCountList[i].today_new+‘</td>‘ ;
trHtml += ‘<td >‘+bugzillaCountList[i].today_close+‘</td>‘ ;
trHtml += ‘<td >‘+bugzillaCountList[i].today_reopen+‘</td>‘ ;
trHtml += ‘<td >‘+bugzillaCountList[i].total_reopen+‘</td>‘ ;
trHtml += ‘<td >‘+bugzillaCountList[i].to_fix+‘</td>‘ ;
trHtml += ‘<td >‘+bugzillaCountList[i].to_reg+‘</td>‘ ;
trHtml += ‘<td >‘+bugzillaCountList[i].closed+‘</td>‘ ;
trHtml += ‘<td >‘+bugzillaCountList[i].sub_total+‘</td>‘ ;
trHtml += ‘ </tr>‘;

}

$("#content").prepend (trHtml);
$(‘table[id$="tableItem"]‘).find("tr").bind(‘click‘,function(event){
$(‘table[id$="tableItem"]‘).find("tr").removeClass("selected");
$(this).addClass("selected");
});

}



}


var newCountArray = JSON.parse(obj.newCountArray);
var closeCountArray = JSON.parse(obj.closeCountArray);
var datesArray = JSON.parse(obj.datesArray);


//newCountArray,closeCountArray,datesArray为异步从后台数据查出的数组,这里先异步从PHP或者JAVA去数据库取数据
initHighCharts(newCountArray,closeCountArray,datesArray); 

});

}


</script>

5. 邮件通过报表图片服务器的URL直接引用截图保存后的报表

<h3><strong>附图. xxxx趋势图<span style="font-size:12px">(<a href="${rootMap.chartUrl}" target="_blank">点击查看详细趋势图</a>)</span></strong></h3> 
<div>
<img src = "${rootMap.countImage}" /> 
</div>

本着资源共享的原则,欢迎各位朋友在此基础上完善,并进一步分享,让我们的实现更加优雅。如果有任何疑问和需要进一步交流可以加我QQ 1922003019或者直接发送QQ邮件给我沟通

原文地址:https://www.cnblogs.com/firstdream/p/5119964.html