java如何不通过浏览器直接在后端生成echarts图片(phantomjs),并将图片插入到word中

需求

数据进行统计后,需要将统计好的数据生成对应的echarts图,并将echarts图插入到word文档中导出使用。不需要在页面(浏览器)上展示。这就导致了,无法通过浏览器对echarts数据进行渲染后,在提供对应的base64的字符串给后端进行下载。

实现

1. 首先下载phantomjs以及基础的js插件

链接:https://pan.baidu.com/s/1oEpsj0AxJZ1Tsi3ziEjrIw
提取码:u3ba
在这里插入图片描述
在这里插入图片描述
4个js文件放置到系统代码的同个文件夹下面即可

2. 创建好word文档,并在word文档中定义好插入图片的位置(域)

在这里插入图片描述
在这里插入图片描述

3. 代码实现

使用cmd命令的方式去调用phantomjs生成图片

package com.test.word;

import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.UUID;

import javax.imageio.ImageIO;

import org.apache.tomcat.util.http.fileupload.IOUtils;

import com.aspose.words.Document;
import com.aspose.words.DocumentBuilder;

public class Test1 
{
	public static void main(String[] args) 
	{
		try
		{
			//文档对象
			Document mainDocument = new Document("模板文档路径,也就是第二步中创建的文档的路径");
			DocumentBuilder builder = new DocumentBuilder(mainDocument);
			//该方法一共是3个参数,第2个参数是用于生成echarts的数据,可以到echarts官网复制,第3个参数是word文档中定义的域名
			insertEchartsToWord(
					
					builder, 
					
					"option = {xAxis: {type: 'category',data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']},"
					
					+ "yAxis: {type: 'value'},series: [{data: [150, 230, 224, 218, 135, 147, 260],type: 'line'}]}",
					
					"map");
			mainDocument.save("生成结果文档保存路径");
			System.out.println("成功!");
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 插入echart图片到word中(单个)
	 * @param builder 文档document对应的builder对象
	 * @param options echarts图的json字符串-在echarts官网上能直接构成echarts图的json串
	 * @param keyName word文档中的域名
	 * @throws Exception
	 */
	public static void insertEchartsToWord(DocumentBuilder builder, String options, String keyName) throws Exception
	{
		InputStream in = null;
		try
		{
			File imgFile = generateEChart(options);
			in = new FileInputStream(imgFile);
			BufferedImage image = ImageIO.read(in);
			if (image != null)
			{
				builder.moveToMergeField(keyName);
				builder.insertImage(image);
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			IOUtils.closeQuietly(in);
		}
	}
	
	/**
	 * 生成echarts
	 * @param options
	 * @return
	 * @throws InterruptedException
	 */
	public static File generateEChart(String options) throws Exception
	{
		// echarts对应js文件路径
		  String jsPath ="xxx\\echarts-convert.js";
		// 生成图片的临时路径 配置到文件夹
		  String tmpPath = "F:\\test\\";
		// cmd命令头 其实也就是解压后的phantomjs的路径
		  String commandHead = "xxxx\\phantomjs.exe ";
		//输出文件的路径
		String dataPath = writeFile(options, tmpPath);
		String fileName = UUID.randomUUID().toString().substring(0, 8) + ".png";
		String path = tmpPath + fileName;
		// 文件路径(路径+文件名)
		File file = new File(path);
		if (!file.exists())
		{
			// 文件不存在则创建文件,先创建目录
			File dir = new File(file.getParent());
			dir.mkdirs();
			if (!file.createNewFile())
			{
				throw new RuntimeException("生成echarts图片失败");
			}
		}
		//执行的命令
		String command = commandHead + jsPath + " -infile " + dataPath + " -outfile " + path;
		Process process = Runtime.getRuntime().exec(command);
		int result = process.waitFor();
		// 执行成功
		if (result == 0)
		{
			if (!new File(dataPath).delete())
			{
				throw new RuntimeException("生成echarts图片失败");
			}
			return file;
		}
		throw new RuntimeException("生成echarts图片失败");
	}
	

	/**
	 * 将optionJSON字符串写入文件中
	 * @param options
	 * @param tmpPath
	 * @return
	 */
	public static String writeFile(String options, String tmpPath) throws Exception
	{
		String dataPath = tmpPath + UUID.randomUUID().toString().substring(0, 8) + ".json";
		BufferedWriter out = null;
		try
		{
			/* 写入txt文件 */
			File writename = new File(dataPath); // 相对路径,如果没有则要建立一个新的output.txt文件
			if (!writename.exists())
			{ // 文件不存在则创建文件,先创建目录
				File dir = new File(writename.getParent());
				dir.mkdirs();
				if (!writename.createNewFile()) // 创建新文件
				{
					throw new Exception("optionJSON字符串写入文件中失败");
				}
			}
			out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(writename), "UTF-8"));
			out.write(options); // \r\n即为换行
			out.flush(); // 把缓存区内容压入文件
		}
		catch (IOException e)
		{
			throw new RuntimeException("optionJSON字符串写入文件中失败");
		}
		finally
		{
			IOUtils.closeQuietly(out);// 最后记得关闭文件
		}
		return dataPath;
	}
}

4.jar包展示

<dependency>
	<groupId>com.aspose</groupId>
	<artifactId>aspose-words</artifactId>
	<version>16.11.0</version>
</dependency>

5.结果展示

在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
图表图片的步骤是什么? 回答: 生成echarts图表图片的步骤如下: 1. 首先,需要安装部署Phantomjs,可以将下载好的Phantomjs放在任意位置。 2. 找到echarts-convert.js文件,并将其放在与Phantomjs相同的目录下。 3. 在命令行执行命令,例如在Linux系统可以执行nohup phantomjs echarts-convert.js -s -p 50130 > echarts.log 2>&1 &,而在Windows系统可以执行C:\Users\Administrator\Desktop\phantomjs-2.1.1-windows\bin>phantomjs C:\Users\Administrator\Desktop\echartsconvert\echarts-convert.js -s -p 9090。\[2\]\[3\] 4. 调用接口生成图片,可以通过发送请求来调用接口生成echarts图表的图片。 #### 引用[.reference_title] - *1* *2* [java后台生成echarts图表图片](https://blog.csdn.net/zixuanyankai/article/details/130702369)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [java 实现后台生成echarts 图片](https://blog.csdn.net/weixin_43831289/article/details/119645323)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值