網友結論:PhantomJS技術方案老舊,推薦使用Puppeteer, 最差也用 casperjs
自帶示例:網頁指定生成文件
phantomjs printmargins.js https://my.oschina.net/liuzidong myoschina.png 0 0 1000 1000
參考資料
phantomjs
PhantomJS是一個基於webkit內核的無頭瀏覽器,即沒有UI界面的一個瀏覽器,只是其內的點擊、翻頁等人爲相關操做須要程序設計實現。
PhantomJS提供JavaScript API接口,即經過編寫js程序能夠直接與webkit內核交互,在此之上能夠結合Java語言等,經過java調用js等相關操做,從而解決了之前c/c++才能比較好的基於webkit開發優質採集器的限制。
可經過:npm install phantomjs -g 安裝
檢查版本:phantomjs --version
方案1: 半自動方案:ECharts+Java實現,ECharts>Base64>ToImages
直接訪問:http://localhost/echarts/line.html 獲取ECharts的base64自動請求url,Java後臺生成圖片。
優勢:實現方便
不足:手工打開
方案2: 全動方案:純Java實現,Phantomjs的API
提供url(http://localhost/echarts/createPhantomjs),Java後臺調用Phantomjs的API生成圖片
優勢:實現方便
手工啓動PhantomJS服務器,經過構造ECharts的Options數據調用Java生成圖片。
優化點:將相關JS放置資源文件下,所有經過Java後臺實現調用。
關鍵點
1. 環境變量配置
將phantomjs添加至環境變量中。
windows:
右鍵個人電腦->屬性->高級系統設置->高級->環境變量->用戶變量/系統變量->Path=D:\phantomjs\bin;
或
cmd->set path=%path%;D:\phantomjs\bin
linux:
vi /etc/profile
export PATH=$PATH:/usr/phantomjs/bin
2. application.properties配置
phantomjs.exec.path=D:/phantomjs-2.1.1-windows/bin/phantomjs
# 經過調用myChart.getDataURL()獲得base64,調用java直接生成圖片,適用於不復雜的場景
phantomjs.echarts.get.base64.call.java.url=http://localhost/echarts/line.html
phantomjs.call.java.url=http://localhost/echarts/phantomjs
image.root.path=D:/images
image.width=850
image.height=850
3. Java配置
一、拼接cmd命令並執行>啓動服務
private static String getCmd() throws FileNotFoundException {
StringBuilder cmd = new StringBuilder();
cmd.append("D:/phantomjs-2.1.1-windows/bin/phantomjs").append(SP);
cmd.append(getEchartsRootPath() + "/echarts-convert.js").append(SP);
cmd.append("-s").append(SP);
return cmd.toString();
}
private static String getEchartsRootPath() throws FileNotFoundException {
return ResourceUtils.getFile("classpath:phantomjs/echarts").getAbsolutePath();
}
public static void startPhantomjs() throws FileNotFoundException {
Runtime rt = Runtime.getRuntime();
String cmdStr = getCmd();
log.info("執行命令:{}", cmdStr);
try {
rt.exec(cmdStr);
} catch (IOException e) {
log.error("執行phantomjs的指令失敗!請檢查是否安裝有PhantomJs的環境或配置path路徑!PhantomJs詳情參考這裏:http://phantomjs.org", e);
}
log.info("打開地址完成!");
}
二、拼接ECharts的Options,調用HttpClients的API生成。
private static void createImage() throws Exception {
//
String url = "http://localhost:9090";
// 沒必要要的空格最好刪除,字符串請求過程當中會將空格轉碼成+號
String optJson = "{title:{text:'ECharts 示例'},tooltip:{},legend:{data:['銷量']},"
+ "xAxis:{data:['襯衫','羊毛衫','雪紡衫','褲子','高跟鞋','襪子']},yAxis:{},"
+ "series:[{name:'銷量',type:'bar',data:[5,20,36,10,10,20]}]}";
Map<String, String> map = new HashMap<>();
map.put("opt", optJson);
map.put("echartsRoot", getEchartsRootPath());
try {
String post = post(url, map, "utf-8");
System.out.println(post);
Map<String, Object> jsonMap = new Gson().fromJson(post, Map.class);
String base64Info = (String) jsonMap.get("data");
Base64ImgsUtil.base64StringToImage(base64Info, "D:\\images\\" + UUID.randomUUID().toString() + ".png");
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// post請求
public static String post(String url, Map<String, String> map, String encoding) throws ParseException, IOException {
String body = "";
// 建立httpclient對象
CloseableHttpClient client = HttpClients.createDefault();
// 建立post方式請求對象
HttpPost httpPost = new HttpPost(url);
// 裝填參數
List<NameValuePair> nvps = new ArrayList<>();
if (map != null) {
for (Entry<String, String> entry : map.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
// 設置參數到請求對象中
httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));
// 執行請求操做,並拿到結果(同步阻塞)
CloseableHttpResponse response = client.execute(httpPost);
// 獲取結果實體
HttpEntity entity = response.getEntity();
if (entity != null) {
// 按指定編碼轉換結果實體爲String類型
body = EntityUtils.toString(entity, encoding);
}
EntityUtils.consume(entity);
// 釋放連接
response.close();
return body;
}