java web将数据导出为pdf格式文件代码
16lz
2021-09-22
此片段达到的效果是:访问此请求,浏览器将打开新的界面并显示pdf文件预览,在文件预览界面可以下载该pdf文件。
1、jsp界面代码
<input type="button" class="btn btn-info" onclick="getVerPdf();" target="_blank" value="导出为pdf文件" />
2、js代码
function getVerPdf() {
window.open(‘/pms/jsp/version/getPrdVerListPdf?page=’
+ $("#getPage").html() + '&key=' + $("#select").val());
}
3、java代码
/*
* Purpose :将产品版本列表导出为pdf格式
*
* @param req
* 请求
* @param resp
* 应答
* @param page
* 当前页数
*/
@RequestMapping(value = "getPrdVerListPdf")
public void getPrdTypeList(HttpServletRequest req, HttpServletResponse resp, Integer page, String key) {
resp.setContentType("application/pdf");
// 弹框选择保存路径和文件名
// resp.setHeader("content-disposition",
// "attachment;filename=PrdVerList.pdf");
// 得到当前页的数据
List<Version> verList = prdVersionSer.getAllPrdVersion(key);
if (verList.size() == 0) {
// 如果没有数据,则返回主界面并显示提示消息
req.setAttribute("getFileMsg", "没有符合条件的信息!");
req.setAttribute("select", key);
try {
req.getRequestDispatcher("/jsp/version/ver_list.jsp").forward(req, resp);
} catch (Exception e) {
e.printStackTrace();
}
} else {
// 如果有数据,则显示pdf文件
JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(verList);
String reportPath = null;
Map<String, Object> map = new HashMap<String, Object>();
if (key != "") {
map.put("prdName", verList.get(0).getPrdName());
} else {
map.put("prdName", "");
}
reportPath = req.getServletContext().getRealPath("/reports/prdVerListByPrdName.jasper");
InputStream is = null;
try {
is = new FileInputStream(reportPath);
JasperRunManager.runReportToPdfStream(is, resp.getOutputStream(), map, ds);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
更多相关文章
- php生成PDF格式文件并且加密
- php在线生成ico文件的代码
- PHP生成RSS文件类实例
- Laravel的安装和了解
- adminlte框架后台模板分块
- 婚恋网后台资源路由的建立与使用 控制器文件建立
- c# 的判断文件夹是否存在/判断文件是否存在
- 补0817:域名空间内类实现自动加载,use的作用 及 mysql数据库DDL,D
- PHP文件上传函数封装