纯后台生成echarts图片-phantomjs-2.1.1

2023-10-29 18:48

本文主要是介绍纯后台生成echarts图片-phantomjs-2.1.1,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

问题场景

后端需要定时发邮件,邮件正文带图片,图片要求每次即时生成。

开发环境

idea+Java8+springboot2
echart-convert.js
phantomjs-2.1.1与字体

分析

phantomjs可以模拟浏览器执行js请求ajax等效果,俗称无头浏览器,可以用于客户端渲染。

步骤

  1. 下载上述资源,放入工程里,待调用。
  2. 安装phantomjs-2.1.1及微软雅黑字体[图表中文乱码-服务器可能需要安装字体]

 字体:- yum install -y mkfontscale- yum install -y fontconfig- mkdir /usr/share/fonts/chinese- cp msyh.ttf /usr/share/fonts/chinese- mkfontscale- mkfontdir- fc-cache -fv# 查看是否安装成功- fc-list

 phantomjs-2.1.1- yum install -y bzip2# just do it- yum install -y fontconfig freetype libfreetype.so.6- tar -jxvf phantomjs-2.1.1-linux-x86_64.tar.bz2 -C /usr/local/# 创建软链接- ln -s /usr/local/phantomjs-2.1.1-linux-x86_64/bin/phantomjs /usr/local/bin/phantomjs# 验证安装是否成功- phantomjs --version
  1. 引入maven依赖
<dependency><groupId>com.github.abel533</groupId><artifactId>ECharts</artifactId><version>2.2.7</version>
</dependency>
  1. 后台组织好echart生成图片的option
  2. 调用下面的代码
import com.github.abel533.echarts.Grid;
import com.github.abel533.echarts.Label;
import com.github.abel533.echarts.code.Trigger;
import com.github.abel533.echarts.series.Bar;
import com.github.abel533.echarts.style.ItemStyle;
import com.github.abel533.echarts.style.TextStyle;
import com.github.abel533.echarts.style.itemstyle.Normal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import com.github.abel533.echarts.axis.AxisLabel;
import com.github.abel533.echarts.axis.CategoryAxis;
import com.github.abel533.echarts.axis.ValueAxis;
import com.github.abel533.echarts.code.Magic;
import com.github.abel533.echarts.code.Tool;
import com.github.abel533.echarts.feature.MagicType;
import com.github.abel533.echarts.json.GsonOption;
import com.github.abel533.echarts.series.Line;import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;/*** 〈〉** @author yangyouxing* @create 2019-12-18* @since 1.0.0*/
@Slf4j
@Service
public class ImageServiceImpl {/*** 调用phantomjs产生图片* @param options       echarts的options* @param imgName       图片名称路径* @param width         1680* @param height        500* @return*/public String createEchartImage(String options, String imgName, Long width, Long height) {String path = "";BufferedReader input = null;String cmd = "";try {// 工具类自己搞if (OSUtil.isLinux()) {path = "/usr/local/download/" + imgName;} else {path = ResourceUtils.getURL("classpath:download").getPath() + File.separator + imgName;}File file = new File(path);if (file.exists()) {file.delete();}File fileParent = file.getParentFile();if(!fileParent.exists()){fileParent.mkdirs();}file.createNewFile();String jsPath;// 区分服务器和本地环境if (OSUtil.isLinux()) {jsPath = "/usr/local/echarts/echarts-convert.js";} else {// resources下创建echarts文件夹jsPath = ResourceUtils.getURL("classpath:echarts").getPath() + File.separator + "echarts-convert.js";}log.info("start cmd exec generate png");cmd = "/usr/local/bin/phantomjs " + jsPath + " -options " + options + " -outfile " + path + " -width " + width + " -height " + height;log.info("cmd: {}", cmd);Process process = Runtime.getRuntime().exec(cmd);log.info("end cmd exec generate png");input = new BufferedReader(new InputStreamReader(process.getInputStream()));String line;while ((line = input.readLine()) != null) {log.info(line);}log.info("close");} catch (Exception e) {e.printStackTrace();log.error("echarts error: {}, cmd: {}, options: {}, imageName: {}", e.getMessage(), cmd, options, imgName, e);} finally {if (input != null) {try {input.close();} catch (IOException e) {e.printStackTrace();log.error("关闭流失败, {}, options: {}, imageName: {}", e.getMessage(), options, imgName, e);}}}return path;}/*** 折线图* @param types             y轴值* @param yColor            y轴颜色-多个请自行换类型* @param title             图表标题* @param titleAglin        标题对齐* @param rotate            横坐标旋转角度* @param interval          刻度间隔* @param xDataList         x轴值* @param yDataList         y轴值* @param axisName          横坐标名* @param isHorizontal      是否颠倒x与y轴* @return*/public String getLineEchartOption(String[] types, String yColor, String title, String titleAglin,Integer rotate, Integer interval, List<String> xDataList, List<String> yDataList, String axisName, boolean isHorizontal) {GsonOption option = new GsonOption();// 大标题、位置option.title().text(title).x(titleAglin);// 提示工具option.tooltip().show(true).trigger(Trigger.axis);// 工具栏option.toolbox().show(true).feature(Tool.mark, Tool.dataView, new MagicType(Magic.line, Magic.bar), Tool.restore, Tool.saveAsImage);// 图例for (String legend : types) {option.legend(legend);}// 循环给y轴赋值数据for (int i = 0; i < types.length; i++) {Line line = new Line();String type = types[i];line.name(type);for (String yy : yDataList) {line.data(yy);}option.series(line);}// 轴分类CategoryAxis x = new CategoryAxis();for (String cate : xDataList) {x.data(cate);}x.name(axisName);// 设置横坐标旋转角度AxisLabel xLabel = new AxisLabel();xLabel.setRotate(rotate);xLabel.setInterval(interval);x.setAxisLabel(xLabel);// 横轴为类别、纵轴为值if (isHorizontal) {// x轴option.xAxis(x);// y轴ValueAxis ecsY = new ValueAxis();ecsY.axisLine().lineStyle().color(yColor);option.yAxis(ecsY);} else {// 横轴为值、纵轴为类别// x轴option.xAxis(new ValueAxis());// y轴option.yAxis(x);}Grid grid = new Grid();// 控制x轴文字与左边的距离grid.setX(70);// 控制x2轴文字与右边的距离grid.setX2(100);// y2可以控制倾斜的文字与底部的距离grid.setY2(100);// y可以控制倾斜的文字与顶部的距离grid.setY(100);option.setGrid(grid);String optionStr = option.toString().replace(" ", "");log.info("line-options: {}", optionStr);return optionStr;}/*** 柱状图* @param types             y轴值* @param typeColors        y轴颜色* @param title             图表标题* @param titleAglin        标题对齐* @param rotate            横坐标旋转角度* @param interval          刻度间隔* @param xDataList         x轴值* @param yDataList         y轴值* @param axisName          横坐标名* @param isHorizontal      是否颠倒x与y轴* @return*/public String getBarEchartOption(String[] types, String[] typeColors, String title, String titleAglin,Integer rotate, Integer interval, String[] xDataList, Integer[] yDataList, String axisName, boolean isHorizontal) {GsonOption option = new GsonOption();// 大标题、位置option.title().text(title).x(titleAglin);//显示工具提示,设置提示格式option.tooltip().show(true).trigger(Trigger.axis);// 工具栏option.toolbox().show(true).feature(Tool.mark, Tool.dataView, new MagicType(Magic.line, Magic.bar), Tool.restore, Tool.saveAsImage);// 图例option.legend(types[0]);// 图类别(柱状图)Bar bar = new Bar(types[0]);int size = xDataList.length;if (size > 30) {bar.setBarWidth(5);} else {bar.setBarWidth(30);}// 循环数据for (int i = 0; i < size; i++) {String color = typeColors[i % typeColors.length];// 类目对应的柱状图/*** itemStyle: {* 				normal: {* 						label: {* 								show: true, //开启显示* 								position: 'top', //在上方显示* 								textStyle: { //数值样式* 								color: 'black',* 								fontSize: 16*                              }*                      }*              }* }*/Label label = new Label();label.show(true);label.position("top");TextStyle textStyle = new TextStyle();textStyle.color("black");textStyle.fontSize(16);label.textStyle(textStyle);ItemStyle itemStyle = new ItemStyle();Normal normal = new Normal();normal.color(color);normal.label(label);itemStyle.normal(normal);Map<String, Object> map = new HashMap<>(16);map.put("value", yDataList[i]);map.put("itemStyle", itemStyle);bar.data(map);}// 轴分类CategoryAxis x = new CategoryAxis();for (String cate : xDataList) {x.data(cate);}x.name(axisName);// 设置横坐标旋转角度AxisLabel xLabel = new AxisLabel();xLabel.setRotate(rotate);xLabel.setInterval(interval);x.setAxisLabel(xLabel);// 横轴为类别、纵轴为值if (isHorizontal) {// x轴option.xAxis(x);// y轴option.yAxis(new ValueAxis());} else {// 横轴为值、纵轴为类别// x轴option.xAxis(new ValueAxis());// y轴option.yAxis(x);}option.series(bar);Grid grid = new Grid();// 控制x轴文字与左边的距离grid.setX(70);// 控制x2轴文字与右边的距离grid.setX2(100);// y2可以控制倾斜的文字与底部的距离grid.setY2(100);// y可以控制倾斜的文字与顶部的距离grid.setY(100);option.setGrid(grid);String optionStr = option.toString().replace(" ", "");log.info("bar-options: {}", optionStr);return optionStr;}
}

这篇关于纯后台生成echarts图片-phantomjs-2.1.1的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/302641

相关文章

Java使用Javassist动态生成HelloWorld类

《Java使用Javassist动态生成HelloWorld类》Javassist是一个非常强大的字节码操作和定义库,它允许开发者在运行时创建新的类或者修改现有的类,本文将简单介绍如何使用Javass... 目录1. Javassist简介2. 环境准备3. 动态生成HelloWorld类3.1 创建CtC

Java实现将HTML文件与字符串转换为图片

《Java实现将HTML文件与字符串转换为图片》在Java开发中,我们经常会遇到将HTML内容转换为图片的需求,本文小编就来和大家详细讲讲如何使用FreeSpire.DocforJava库来实现这一功... 目录前言核心实现:html 转图片完整代码场景 1:转换本地 HTML 文件为图片场景 2:转换 H

Java实现在Word文档中添加文本水印和图片水印的操作指南

《Java实现在Word文档中添加文本水印和图片水印的操作指南》在当今数字时代,文档的自动化处理与安全防护变得尤为重要,无论是为了保护版权、推广品牌,还是为了在文档中加入特定的标识,为Word文档添加... 目录引言Spire.Doc for Java:高效Word文档处理的利器代码实战:使用Java为Wo

基于C#实现PDF转图片的详细教程

《基于C#实现PDF转图片的详细教程》在数字化办公场景中,PDF文件的可视化处理需求日益增长,本文将围绕Spire.PDFfor.NET这一工具,详解如何通过C#将PDF转换为JPG、PNG等主流图片... 目录引言一、组件部署二、快速入门:PDF 转图片的核心 C# 代码三、分辨率设置 - 清晰度的决定因

Python从Word文档中提取图片并生成PPT的操作代码

《Python从Word文档中提取图片并生成PPT的操作代码》在日常办公场景中,我们经常需要从Word文档中提取图片,并将这些图片整理到PowerPoint幻灯片中,手动完成这一任务既耗时又容易出错,... 目录引言背景与需求解决方案概述代码解析代码核心逻辑说明总结引言在日常办公场景中,我们经常需要从 W

使用Python实现无损放大图片功能

《使用Python实现无损放大图片功能》本文介绍了如何使用Python的Pillow库进行无损图片放大,区分了JPEG和PNG格式在放大过程中的特点,并给出了示例代码,JPEG格式可能受压缩影响,需先... 目录一、什么是无损放大?二、实现方法步骤1:读取图片步骤2:无损放大图片步骤3:保存图片三、示php

C#使用Spire.XLS快速生成多表格Excel文件

《C#使用Spire.XLS快速生成多表格Excel文件》在日常开发中,我们经常需要将业务数据导出为结构清晰的Excel文件,本文将手把手教你使用Spire.XLS这个强大的.NET组件,只需几行C#... 目录一、Spire.XLS核心优势清单1.1 性能碾压:从3秒到0.5秒的质变1.2 批量操作的优雅

Python使用python-pptx自动化操作和生成PPT

《Python使用python-pptx自动化操作和生成PPT》这篇文章主要为大家详细介绍了如何使用python-pptx库实现PPT自动化,并提供实用的代码示例和应用场景,感兴趣的小伙伴可以跟随小编... 目录使用python-pptx操作PPT文档安装python-pptx基础概念创建新的PPT文档查看

在ASP.NET项目中如何使用C#生成二维码

《在ASP.NET项目中如何使用C#生成二维码》二维码(QRCode)已广泛应用于网址分享,支付链接等场景,本文将以ASP.NET为示例,演示如何实现输入文本/URL,生成二维码,在线显示与下载的完整... 目录创建前端页面(Index.cshtml)后端二维码生成逻辑(Index.cshtml.cs)总结

Python实现数据可视化图表生成(适合新手入门)

《Python实现数据可视化图表生成(适合新手入门)》在数据科学和数据分析的新时代,高效、直观的数据可视化工具显得尤为重要,下面:本文主要介绍Python实现数据可视化图表生成的相关资料,文中通过... 目录前言为什么需要数据可视化准备工作基本图表绘制折线图柱状图散点图使用Seaborn创建高级图表箱线图热