Echarts export to pdf echarts export charts (including background)

Echarts seems to only support the export of png and jpg, pdf export is not supported. I was thinking only in the background can be converted to pdf png up.

First, tell us about the code jsp interface.

echarts.init thisChart = var (document.getElementById ( 'myChart'));
. $ ( '# activeResourcesExportBtn') ON ( 'the Click', function () {
var chartExportUrl = 'ISMS / ActiveResource / export.do';
var picBase64Info = thisChart.getDataURL (); // Get echarts FIG base64 encoding, the format is png.
$ ( '# chartForm') Find ( 'INPUT [name = "base64Info"]') Val (picBase64Info);.. // the assigned to the input frame encoding
$ ( '# chartForm') attr ( 'action', chartExportUrl) .attr ( 'method', 'post');. // set submitted to the url
$ ( '# chartForm') attr . ( 'action', chartExportUrl) .attr ( 'method', 'post'); // set submission to 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>


The main role is to obtain the above front-end code echarts FIG base64-encoded and then input the input value to a frame, the form is submitted to the background by the form. Here is the background code.

@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"));Set your browser to block pop-up download, front end submission form by form, I use ajax no effect.

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;
}

int getPercent2 Private (H a float, a float W) {
int P = 0;
a float P2 = 0.0f;
P2 = 530. / W * 100;
P = Math.round (P2);
return P;
}
// read the input stream output stream
Private void Copy (BufferedInputStreaminput, BufferedOutputStream The outputString) {
byte [] = But new new byte [1024];
the try {
the while (! input.read () = -. 1) {
int = input.read by (But);
outputString. Write (But, 0, by);
outputString.flush ();
}
} the catch (IOException E) {
e.printStackTrace ();
}
}

the above code is the code controller layer, the background is the main processing logic. Before using the code should be poured itext package, it should be used to generate itex pdf file. Most of the code is io things flow, not described in detail. hope that it can help us.


Original link: https: //blog.csdn.net/qq_22778121/article/details/54175358

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

echarts export charts (including background)

Demand: Returns the background rear view showing animation chart on FIG., Then the user can press the results stored in the mobile terminal of FIG.
Process: Firstly echarts generate charts, 2s to animate length, after which getDataURL echarts method for generating replacement image to form a base64 img tag cover echarts chart.
The main problem: encountered problems downloading echarts picture cross-domain
solution: server settings picture header Access-Control-Allow-Origin: *, js set img.crossOrigin = 'anonymous'

index.html page two layers
a first layer is img, for displaying the background image in FIG. And the final result
of the second layer is a div, used to display a graph echarts
<img v-show = "showImgLabel " style = "z-index : 2; "ID =" result_img "V-Cloak: the src =" result_img_url ">
<div V-Show =" showChartLabel "style =" Z-index:. 1; "ID =" result_charts "V-Cloak> </ div >
------------------------------------------------- -------------------------------------------------- -------------------------------------------------- ----------------------------------------
JS Code
vue_this.result_img_url = resultImg // background FIG URL
var = {} // Option echarts CI
vue_this.showImgLabel to false =
vue_this.showChartLabel to true =
var resultImgDiv = document.getElementById ( 'result_img_div')
Var width = resultImgDiv.offsetWidth
// div The background image size setting size
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)
the setTimeout (function () {
var resultBase64 = myChart.getDataURL ({
type: 'PNG',
pixelRatio: 2, // magnify the download, then compressed to the same size to generate display images to resolve ambiguities in the mobile terminal.
the backgroundColor: '#fff'
})
vue_this.result_img_url = resultBase64
// using absolute positioning and z-index so as to charts bottom , covering effect achieved
// If implemented in effect replaced by v-show or v-if, the page will appear instantly jitter
document.getElementById ( 'result_charts'). style.position = 'Absolute'
vue_this.showImgLabel to true =
},2000)
}
--------------------------------------------------------------------------------------------------------------------
Image transfer method 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

 

Guess you like

Origin www.cnblogs.com/aliswell2king/p/11756977.html