- jasperreports-1.2.5.jar
- itext-1.3.1.jar
- commons-javaflow-20060411.jar
นี้เป็นตัวอย่าง File JSP ที่จะใช่แสดง Output ออกมาเป็น PDF file
โดย Parameter ที่ต้องการคือ
- ReportName - ชื่อ File ของ Report ไม่ต้องมีนามสกุล
- DataSource - ใช้ในกรณีที่เป็นการ Connect โดยใช้ JRDataSourceProvider
- http://localhost:8080/iReport1/ExportReport.jsp?ReportName=EmployeeList แบบใช้ JDBC Connection
- http://localhost:8080/iReport1/ExportReport.jsp?
ReportName=EmployeeList&DataSource=data.factory.EmployeeReport
แบบ JRDataSourceProvider
<%@page import="java.util.*"%>
<%@page import="data.connect.DBConnect"%>
<%@page import="java.sql.Connection"%>
<%@page import="net.sf.jasperreports.engine.*"%>
<%@page import="net.sf.jasperreports.engine.data.JRAbstractBeanDataSourceProvider"%>
<%@page import="net.sf.jasperreports.engine.data.JRBeanCollectionDataSource"%>
<%@page import="net.sf.jasperreports.engine.export.*"%>
<%
String dataSource = request.getParameter("DataSource");//DataSource
String sReportPath = getServletContext().getRealPath("/Reports/"
+ request.getParameter("ReportName") + ".jrxml");
//Mapping Query String to Report's Parameter
Map<String, Object> parameters = new HashMap<String, Object>();
Enumeration eParaName = request.getParameterNames();
if (eParaName != null){
while (eParaName.hasMoreElements()) {
Object obj = eParaName.nextElement();
parameters.put(obj.toString(), request.getParameter(obj.toString()));
}
}
//Compile Report jrxml --> jasper
JasperReport jasperReport = JasperCompileManager.compileReport(sReportPath);;
JasperPrint jasperPrint=null;
try {
if (dataSource == null) { //Check Data Source Type
//Get Data from Connection
//Create connection to Database
Connection connection=DBConnect.getMySqlConnection();
jasperPrint =
JasperFillManager.fillReport(jasperReport, parameters, connection);
}
else{
//Get Data from Data Source Class
JRAbstractBeanDataSourceProvider dsf
= (JRAbstractBeanDataSourceProvider)Class.forName(dataSource).newInstance();
JRBeanCollectionDataSource ds = (JRBeanCollectionDataSource)dsf.create(jasperReport);
if (ds != null) {
jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, ds);
}
}
//Stream output to PDF file
ServletOutputStream sosStream = response.getOutputStream();
JRExporter exporter = new JRPdfExporter();//PDF Export
exporter.setParameter( JRExporterParameter.JASPER_PRINT, jasperPrint );
//Set Stream header
response.setHeader (
"Content-Disposition", "attachment;filename=\""
+request.getParameter("ReportName")+".pdf\"");
exporter.setParameter( JRExporterParameter.OUTPUT_STREAM, sosStream);
exporter.exportReport();
sosStream.close();
}
catch (Exception ex1){
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex1.getMessage());
ex1.printStackTrace();
return;
}
%>