在项目原有包基础上加入JAR包主要有jasperreport-5.0.1.jar,iText-2.1.7.jar,groovy-1.8.6.jar,iTextAsian.jar,commons-digester.jar
使用iReport绘制好模版步骤不再详述,网上也有很多,只说绘制模版需要注意的问题。
1、如果输出为中文要设置属性PDF FONT:STSong-Light
PDF Embedded勾选
PDF Encoding:UniGB-UCS2-H (Chinese Simplified)
2、Parameter参数指传递后台Map<String, Object>中的值,Field字段传递为后台List中值
本例使用JAVABEAN作为source。
首先创建需要的JAVABEAN
public class Case{
private String id;
private String name;
private String code;
private String phone;
private String mobile;
public Case(){
}
public Case(String id, String name, String code, String phone, String mobile){
this.id = id;
this.name = name;
this.code = code;
this.phone = phone;
this.mobile = mobile;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
}
然后编写简单导出的方法
public void exportPDF() throws Exception{
String filename = this.genFileName();
String path = "D:/work/pic/";
List <Case> list = new ArrayList<Case>();//对应iReport里设置的field
Case c=new Case("1","dsf","33","33","33");//设置测试数据
list.add(c);
try {
Map<String, Object> parameters = new HashMap<String, Object>();//对应iReport里设置的parameter
parameters.put("caseno", "C2021");
parameters.put("caseName", "sdf");
parameters.put("tel", "13333333333");
JasperReportExportPDF jrePDF=new JasperReportExportPDF();
ServletActionContext.getResponse().setContentType("application/pdf");//设置类型
ServletActionContext.getResponse().addHeader("Content-disposition","attachment;filename="+ encodeFileName(filename + ".pdf"));
OutputStream out = ServletActionContext.getResponse().getOutputStream();
JRDataSource jrDataSource = new JRBeanCollectionDataSource(list);添加source
JasperReport jasperReport = (JasperReport) JRLoader.loadObject("D:/jasperReport/report1.jasper");//加载模版
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters,jrDataSource);
byte[] bytes = JasperExportManager.exportReportToPdf(jasperPrint);
if (bytes != null && bytes.length > 0) {
out.write(bytes, 0, bytes.length);
}
out.flush();
out.close();
//show elapsed time
} catch (JRException e) {
e.printStackTrace();
}
}
//处理文件名的方法
private String encodeFileName(String fileName) throws Exception {
return new String(fileName.getBytes("gbk"), "ISO-8859-1");
}
private String genFileName(){
return new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
}