Echarts好像是只支持png和jpg的导出,不支持pdf导出。我就想着只能够将png在后台转为pdf了。

首先介绍一下jsp界面的代码。

var thisChart = echarts.init(document.getElementById('myChart'));
$('#activeResourcesExportBtn').on('click',function(){
var chartExportUrl = 'isms/activeResource/export.do';
var picBase64Info = thisChart.getDataURL();//获取echarts图的base64编码,为png格式。
$('#chartForm').find('input[name="base64Info"]').val(picBase64Info);//将编码赋值给输入框
$('#chartForm').attr('action',chartExportUrl).attr('method', 'post');//设置提交到的url地址
$('#chartForm').attr('action',chartExportUrl).attr('method', 'post');//设置提交方式为post
$('#chartForm').submit();
});

<form id="chartForm" style="display:none">
<input id="imageValue" name="base64Info" type="text" maxlength="50000"/>
</form>
<div id="myChart" style="width:auto;height:500px;display:none" class="myChart"></div>

上面的前端代码主要的作用是获取echarts图的base64编码,然后把值赋给一个input输入框,通过form表单提交到后台。下面是后台的代码。

@RequestMapping(value="export", method=RequestMethod.POST)
@ResponseBody
public void chartExport(HttpServletResponse response,String base64Info) throws IOException {
String newFileName;
newFileName = "统计图" + System.currentTimeMillis() + ".pdf";
String newPngName = newFileName.replaceFirst(".pdf", ".png");
String exportFilePath = "d:/export"
base64Info = base64Info.replaceAll(" ", "+");
BASE64Decoder decoder = new BASE64Decoder();
String[] arr = base64Info.split("base64,");
byte[] buffer;
try {
buffer = decoder.decodeBuffer(arr[1]);
} catch (IOException e) {
throw new RuntimeException();
}
OutputStream output = null;
try {
output = new FileOutputStream(new File(exportFilePath+newPngName));//生成png文件
output.write(buffer);
output.flush();
output.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Pdf(exportFilePath+newPngName,exportFilePath+newFileName);
File f = new File(exportFilePath+newPngName);
if(f.exists()){
f.delete();
}
response.setContentType("application/octet-stream");
InputStream input = null;
OutputStream outputString = null;
try {
response.setHeader("Content-Disposition","attachment; filename=" + URLEncoder.encode("统计图" + ".pdf", "UTF-8"));设置浏览器弹出下载框,前端用form表单提交,我用ajax没有效果。

input = new BufferedInputStream(new FileInputStream(new File(exportFilePath + newFileName)));
outputString = new BufferedOutputStream(response.getOutputStream());
copy(input, outputString);
outputString.flush();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}finally{
input.close();
outputString.close();
}

}
//通过png文件来生成pdf文件
public File Pdf(String imagePath, String mOutputPdfFileName) {
Document doc = new Document(PageSize.A4, 20, 20, 20, 20);
try {
PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(mOutputPdfFileName));
doc.open();
doc.newPage();
Image png1 = Image.getInstance(imagePath);
float heigth = png1.getHeight();
float width = png1.getWidth();
int percent = this.getPercent2(heigth, width);
png1.setAlignment(Image.MIDDLE);
png1.setAlignment(Image.TEXTWRAP);
png1.scalePercent(percent + 3);
doc.add(png1);
doc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

File mOutputPdfFile = new File(mOutputPdfFileName);
if (!mOutputPdfFile.exists()) {
mOutputPdfFile.deleteOnExit();
return null;
}
return mOutputPdfFile;
}

private int getPercent2(float h, float w) {
int p = 0;
float p2 = 0.0f;
p2 = 530 / w * 100;
p = Math.round(p2);
return p;
}
//输入流读取到输出流
private void copy(BufferedInputStreaminput,BufferedOutputStream outputString){
byte [] but = new byte[1024];
try {
while(input.read()!=-1){
int by = input.read(but);
outputString.write(but, 0, by);
outputString.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}

上面的代码是controller层的代码,也是后台主要的处理逻辑。在使用代码之前应该倒入itext包,应为是用itex来生成pdf文件。大部分的代码都是io流的东西,就不详细介绍了。希望能对大家有所帮助。

原文链接:https://blog.csdn.net/qq_22778121/article/details/54175358

=====================================================================================================================================================

echarts导出图表(包含背景)

需求:后端返回背景图,在图上显示动画效果绘制图表,之后用户可以在移动端长按保存结果图。
流程:首先利用echarts生成图表,设置动画时长为2s,之后利用echarts的getDataURL方法生成base64格式图片替换到img标签上,覆盖echarts图表。
主要问题:下载echarts时遇到图片跨域问题
解决办法:服务端设置图片头Access-Control-Allow-Origin:*,js设置img.crossOrigin = ‘anonymous’

index.html页面分两层
第一层是img,用于展示背景图And最后的结果图
第二层是div,用来展示echarts的图表
<img v-show="showImgLabel" style="z-index: 2;" id="result_img" v-cloak :src="result_img_url">
<div v-show="showChartLabel" style="z-index: 1;" id="result_charts" v-cloak></div>
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
JS代码
vue_this.result_img_url = resultImg //背景图url
var option = {} //echarts配置项
vue_this.showImgLabel = false
vue_this.showChartLabel = true
var resultImgDiv = document.getElementById('result_img_div')
var width = resultImgDiv.offsetWidth
//根据背景图大小设置div大小
document.getElementById('result_charts').style.width = width + 'px'
var img = new Image()
var base64 = ''
img.crossOrigin = 'anonymous'
img.src = resultImg
img.onload = function() {
//将背景图转为base64
base64 = vue_this.image2Base64(img)
//设置高度
var height = img.height * (resultImgDiv.offsetWidth / img.width)
document.getElementById('result_charts').style.height = height + 'px'
document.getElementById('result_img').style.height = height + 'px'
//设置echarts背景图
option.graphic = [{
type: 'image',
id: 'one',
z: -10,
bounding: 'raw',
zlevel: 0,
style: {
image: base64,
width: width,
height: height
}
}]
var myChart = echarts.init(document.getElementById('result_charts'))
myChart.setOption(option)
setTimeout(function() {
var resultBase64 = myChart.getDataURL({
type: 'png',
pixelRatio: 2, //放大两倍下载,之后压缩到同等大小展示。解决生成图片在移动端模糊问题
backgroundColor: '#fff'
})
vue_this.result_img_url = resultBase64
//利用绝对定位和z-index使charts至于底层,实现覆盖效果
//如果用v-show或者v-if实现替换效果,页面会出现瞬间的抖动
document.getElementById('result_charts').style.position = 'absolute'
vue_this.showImgLabel = true
}, 2000)
}
--------------------------------------------------------------------------------------------------------------------
图片转base64方法

image2Base64: function(img) {
var canvas = document.createElement('canvas')
canvas.width = img.width
canvas.height = img.height
var ctx = canvas.getContext('2d')
ctx.drawImage(img, 0, 0, img.width, img.height)
var dataURL = canvas.toDataURL('image/png')
return dataURL
}
————————————————
原文链接:https://blog.csdn.net/Akony/article/details/79530942

Echarts导出为pdf echarts导出图表(包含背景)的更多相关文章

  1. Confluence 导出为 PDF 格式 - 导出多个页面或者整个空间

    使用 Confluence 的空间导出功能,你可以将多个页面或者整个 Confluence 站点转换为 PDF 文件. 希望使用空间导出功能,你需要 导出空间(Export Space)权限.请查看 ...

  2. Highcharts图表导出为pdf的JavaWeb实践

    写给读者的话^_^: 众所周知,基于Highcharts插件生成的svg图片组(注意这里鄙人指的组是若干图有序组合,并非一张图片,具有业务意义)导出为PDF文档是有难度滴.鄙人也曾“异想天开”用前端技 ...

  3. 把页面上的图表导出为pdf文件,分享一种请求下载文件的方法

    最近客户提出一个需求,就是把页面上的图表导出为pdf文件. 找了很多资料.终于有了点头绪.最主要是参考了HighCharts的做法.http://www.hcharts.cn/ 实现原理:把页面图表的 ...

  4. Spring Boot 2.x基础教程:使用 ECharts 绘制各种华丽的数据图表

    上一节我们介绍了如何在Spring Boot中使用模板引擎Thymeleaf开发Web应用的基础.接下来,我们介绍一下后端开发经常会遇到的一个场景:可视化图表. 通常,这类需求在客户端应用中不太会用到 ...

  5. ECharts(Enterprise Charts 商业产品图表库)初识

    一.简介 大数据时代,重新定义图表的时候到了,所以随之ECharts就随之出现了. ECharts(Enterprise Charts 商业产品图表库) 是基于Canvas的,纯Javascript ...

  6. ECharts学习(1)--简单图表的绘制

    1.获取ECharts 官网 下载:http://echarts.baidu.com/download.html 2.在html页面中引入ECharts文件 <!DOCTYPE html> ...

  7. Django分析之导出为PDF文件

    最近在公司一直忙着做exe安装包,以及为程序添加新功能,好久没有继续来写关于Django的东西了….难得这个周末清闲,来了解了解Django的一些小功能也是极好的了~ 那今天就来看看在Django的视 ...

  8. 将w3cplus网站中的文章页面提取并导出为pdf文档

    最近在看一些关于CSS3方面的知识,主要是平时看到网页中有很多用CSS3实现的很炫的效果,所以就打算系统的学习一下.在网上找到很多的文章,但都没有一个好的整理性,比较凌乱.昨天看到w3cplus网站中 ...

  9. Studio for Winforms FlexGrid:导出到 PDF 文件

    本篇文章主要介绍如何导出 FlexGrid 到 PDF 格式文件.本文源于论坛用户,有多个用户提出如何把 FlexGrid 导出到 PDF 文件的需求.在这里共享给大家. 当前,ComponentOn ...

随机推荐

  1. RDD转换为DataFrame【反射/编程】

    写在前面 主要是加载文件为RDD,再把RDD转换为DataFrame,进而使用DataFrame的API或Sql进行数据的方便操作 简单理解:DataFrame=RDD+Schema 贴代码 pack ...

  2. Jetpack系列:LiveData入门级使用方法

    Android APP开发中,开发者们都想有一个公共的组件,可以实现后台数据的监听,同时实时更新到UI进行显示,从而大大简化开发过程.Google针对这一开发需求,提供了Jetpack LiveDat ...

  3. Eureka实战-4【开启http basic权限认证】

    在我们实际生产环境中,都需要考虑到一个安全问题,比如用户登录,又或者是eureka server,它对外暴露的有自己的rest API,如果没有安全认证,也就意味着别人可以通过rest API随意修改 ...

  4. 体验StartOS

    旧电脑,原来使用的是win xp.随着win及其支持打软件打“成长”,电脑运行越来越慢了.一个操作需要很长的时间等待,终于,失去了耐心,换了新的电脑. 旧电脑弃置多年,留之无用,弃之可惜.偶发奇想,换 ...

  5. vue.js入门代码

    <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title&g ...

  6. 30 分钟快速入门 Docker 教程

    原文地址:梁桂钊的博客 博客地址:http://blog.720ui.com 欢迎关注公众号:「服务端思维」.一群同频者,一起成长,一起精进,打破认知的局限性. 一.欢迎来到 Docker 世界 1. ...

  7. [LeetCode] 470. Implement Rand10() Using Rand7()

    Given a function rand7 which generates a uniform random integer in the range 1 to 7, write a functio ...

  8. Bitmap简介

    1.  BitMap Bit-map的基本思想就是用一个bit位来标记某个元素对应的Value,而Key即是该元素.由于采用了Bit为单位来存储数据,因此在存储空间方面,可以大大节省.(PS:划重点 ...

  9. 02-22 决策树C4.5算法

    目录 决策树C4.5算法 一.决策树C4.5算法学习目标 二.决策树C4.5算法详解 2.1 连续特征值离散化 2.2 信息增益比 2.3 剪枝 2.4 特征值加权 三.决策树C4.5算法流程 3.1 ...

  10. 【Java基础】Java开发过程中的常用工具类库

    目录 Java开发过程中的常用工具类库 1. Apache Commons类库 2. Guava类库 3. Spring中的常用工具类 4. 其他工具 参考 Java开发过程中的常用工具类库 1. A ...