1 前提
上一篇文章中说了如何将图表数据生成pdf文件
https://blog.csdn.net/zzqtty/article/details/82589748
,这一篇文章说下如何进行下载,。
本来打算是将pdf中柱状图和饼图的生成实现的,但是采用jfree生成的图片太丑,与echats生成的格式差距太远。还可以采用后台调用浏览器进行渲染截图的操作实现。但是与理想的效果差距太远。这里就不讲了。
2 pdf的下载和预览实现
@RequestMapping(value = "/download_read_pdf/{rd}/{name}",method = RequestMethod.GET)
public ResultData download(HttpServletResponse response,
@PathVariable String rd, @PathVariable String name) throws IOException {
// System.out.println("filePath:" + filePath);
String path = "C://pdf/"+name + ".pdf" ;
File file = new File(path);
// File f = new File(filePath);
if(!file.exists()){
//先得到文件的上级目录,并创建上级目录,在创建文件
file.getParentFile().mkdir();
try {
//创建文件
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
BufferedInputStream br = new BufferedInputStream(new FileInputStream(file));
byte[] bs = new byte[1024];
int len = 0;
response.reset(); // 非常重要
if (rd.equals("read")) { // 在线打开方式
URL u = new URL("file:///" + path);
String contentType = u.openConnection().getContentType();
response.setContentType(contentType);
response.setHeader("Content-Disposition", "inline;filename="
+ name + ".pdf");
// 文件名应该编码成utf-8,注意:使用时,我们可忽略这句
} else {
// 纯下载方式
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment;filename="
+ name + ".pdf");
}
OutputStream out = response.getOutputStream();
while ((len = br.read(bs)) > 0) {
out.write(bs, 0, len);
}
out.flush();
out.close();
br.close();
return new ResultData("下载成功!");
}
代码都很简单,可以直接复制。
谦卑-----记录