此片段达到的效果是:访问此请求,浏览器将打开新的界面并显示pdf文件预览,在文件预览界面可以下载该pdf文件。
1、jsp界面代码
<input type="button" class="btn btn-info" onclick="getVerPdf();" target="_blank" value="导出为pdf文件" />
2、js代码
1
2
3
4
|
function getVerPdf() {
window.open( '/pms/jsp/version/getPrdVerListPdf?page='
+ $( "#getPage" ).html() + '&key=' + $( "#select" ).val());
}
|
3、java代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
/**
*
* 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();
}
}
}
}
}
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。