2008年4月29日 星期二

這是用jasper2.0.4最新版的實做

1.取出datasource
List sourceList = dao.rundata();
if(sourceList.size() < sourcelist =" java.util.Collections.EMPTY_LIST;
}

2.實作一個Map物作來存放變數
Map par = new HashMap();
par.put("par1", "par1-test1");
par.put("par2", "test2");

3.取出jasper檔案
File jasperFile= new File( config.getServletContext().getRealPath("/report/price.jasper"));

4.將.jasper File轉成jasperReport
JasperReport jr = (JasperReport) net.sf.jasperreports.engine.util.JRLoader.loadObject(jasperFile);

5.將sourceList 轉成 JRDataSource
net.sf.jasperreports.engine.JRDataSource jrds = new net.sf.jasperreports.engine.JREmptyDataSource();
jrds = new net.sf.jasperreports.engine.data.JRMapCollectionDataSource(sourceList);

6.從指定的jasperReport 檔案compiled成report design loaded
net.sf.jasperreports.engine.JasperPrint jp= JasperFillManager.fillReport(jr, par,jrds);

7.Exports the generated report object received as parameter into PDF format and returns the binary content as a byte array.
byte[] bytes = net.sf.jasperreports.engine.JasperExportManager.exportReportToPdf(jp);

8.將byte array透過response輸出成PDF
.
.
(略)
response.setHeader("Content-Disposition", "inline;filename=test.pdf");
response.reset();
if (bytes != null && bytes.length != 0) {
response.setContentLength(bytes.length);
ServletOutputStream os = response.getOutputStream();
os.write(bytes, 0, bytes.length);
} else {
throw new IllegalStateException("fail to create pdf file");
}
response.flushBuffer();
.(略)
.

沒有留言: