Echarts導出為pdf echarts導出圖表(包含背景)


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM