Use PHANTOMJS to implement reports such as Highcharts by mail (this article only provides a complete solution and implementation ideas, completely copy the code can not immediately get results)
Recently, the project team needed to show the quality data related to the test by automatically generating reports daily, and automatically informed the stakeholder mailbox by using the report as the message body content. Then the problem came, the report generated, but the message how to send, because Highcharts and other reports are generated by JS and HTML in front-end browser rendering, and the most deadly is the mailbox for security generally do not support JS, so even if the background to calculate the data required for the report, but also can not be in the report is generated in the message content. Later thought Phantomjs this artifact, it is a webkit-based kernel browser, can not pop up the browser interface in memory to open the Web page, and then load the required east (of course, including the highchars and other relying on JS generated report rendering), so the following solutions:
1. Use Java to query the database for the various data required by the report
2. When the server calls the PHANTOMJS boot process through Java Cross process to open the specified URL, load and render the Highchars report
3. Wait a few seconds, after rendering the Highchars report, call Phantomjs's webpage screenshot function, and then save the content of course Web page (report content) as a picture png or jpg of the specified URI, save to a specified directory on the server
4. Load the picture directly in the message using Reference
Related Reference code:
1. Create your Java class and send the Mail main Java method:
。。。。 Use Java to go to the database to remove the data required by the report, omit ...
Initialize trend picture
ServletContext ServletContext = Contextloaderlistener.getcurrentwebapplicationcontext (). GetServletContext ();
String ip = "IP";
int port = 8080;
String ContextPath = Servletcontext.getcontextpath ();
String url =
"//" + 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 path/apache-tomcat-7.0.54/webapps/root/" + Outfile_suffix;
String Outfileurl = "http://" + IP + "" + Port + "/" + Outfile_suffix;
//PHANTOMJS file storage location
String infile = Servletcontext.getrealpath ("/") + "js/phantomjs/capture.js";
Try
{
Phantomjsutil.inithighchartimage to call Phantomjs and return the result infile the Phantomjs script file, outfile the server URI that was saved after generating the picture for PHANTOMJS
if ("Success". Equalsignorecase (Phantomjsutil.inithighchartimage (infile, URL, outfile)))
{
Rootmap.put ("Count404image", Outfileurl);
}
Else
{
Default picture
Rootmap.put ("Count404image", "http://URL/1208_tOl.gif");
}
}
catch (Exception e)
{
Default picture
Rootmap.put ("Count404image", "http://url/1208_tOl.gif");
E.printstacktrace ();
}
。。。
result = Testreportservice.sendtemplatemail (Rootmap, from, Toemail, CC, subject, templatename);
}
2. New Java class Phantomjsutil.java implement PHANTOMJS calls (ensure that PHANTOMJS is installed on the server and that environment variables are configured)
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/cap Ture.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. Create a new Phantomjs script file Capture.js and place it in the specified directory js/phantomjs/
var page = require (' webpage '). Create ();
var system = require (' system ');
var url = system.args[1];
var Outuri = system.args[2];
Page.viewportsize = {width: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 Chart Definition file TESTREPORT_CHART.FTL
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<head>
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
<title>xxxx Trend Chart </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-width:700px;height:400px" ></div>
</body>
<script>
function Inithighcharts (Newcountarray,closecountarray,datesarray)
{
var closedate = Datesarray;
var Closearray = eval (' ([' + Closecountarray + ') ');
var NewArray = eval (' ([' + Newcountarray + ') ');
$ (' #container '). Highcharts ({
Chart: {
Type: ' Line'
},
Title: {
Text: ' Bug Day new and day off trend chart '
},
Subtitle: {
Text: ' app-sale '
},
Xaxis: {
/*categories: [' Jan ', ' Feb ', ' Mar ', ' Apr ', ' may ', ' June ', ' Jul ', ' April ', ' Sep ', ' Oct ', ' Nov ', ' Dec ']*/
Categories:closedate
},
YAxis: {
Title: {
Text: ' unit (each) '
}
},
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: ' New Day ',
Data:newarray
}, {
Name: ' Day Off ',
Data:closearray
}]
});
}
Get the required version statistics asynchronously
function Querycountlist ()
{
var Version = $ (' #version '). Val ();
if (IsEmpty (version))
{
Alert ("Don't be lazy, please select the version first ...");
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 is an array that is asynchronously isolated from the background data, where it is first asynchronous to fetch data from PHP or Java to the database.
Inithighcharts (Newcountarray,closecountarray,datesarray);
});
}
</script>
5. Mail references the saved report directly from the URL of the report picture server
span style= "font-size:12px" > (<a href= "${rootmap.charturl}" target= "_blank" > Click to view detailed trend chart </a>) </span></strong><div>
</div>
In the spirit of the principle of sharing resources, welcome all friends on this basis to improve and further share, let us achieve more elegant. If you have any questions and need further communication can add my QQ 1922003019 or directly send QQ mail to me to communicate
Use PHANTOMJS for reports such as Highcharts to be sent by mail