//path to jrxml file in servlets
ServletContext context = getServletContext();
String s1 = context.getRealPath("") + "path from webinf folder to jrxml file";
File jrxml = new File(s1);
//Compiling Jasper Report
JasperReport jasperReport;
jasperReport = JasperCompileManager.compileReport(jrxml);
//passing parameter and filling report with datasource
Map param = new HashMap();
param.put("ecode", ecode);
JasperPrint jasperprint = JasperFillManager.fillReport(jaspereport, param, "datasource");
//viewing report in jasper viewer
jasperReport.viewReport(jasperprint,true);
//Exporting Report to PDF Format and saving pdf file on server side
String pdfPath = getServletContext().getRealPath("path from webinf folder");
JRPdfExporter exporterPDF = new JRPdfExporter();
exporterPDF.setParameter(JRExporterParameter.JASPER_PRINT, jasperprint);
exporterPDF.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, pdfPath);
exporterPDF.exportReport();
//Saving PDF File on Client Side
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "inline;filename=reportPDF.pdf");
JRPdfExporter exporterPDF = new JRPdfExporter();
exporterPDF.setParameter(JRExporterParameter.JASPER_PRINT, jasperprint);
exporterPDF.setParameter(JRExporterParameter.OUTPUT_STREAM, response.getOutputStream());
exporterPDF.exportReport();
//Exporting Excel file on client side
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "inline;filename=reportXls.xls");
JRXlsExporter exporterXLS = new JRXlsExporter();
exporterXLS.setParameter(JRExporterParameter.JASPER_PRINT, jasperprint);
exporterXLS.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, true); exporterXLS.setParameter(JRXlsExporterParameter.IS_AUTO_DETECT_CELL_TYPE, true); exporterXLS.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, false); exporterXLS.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, true);
exporterXLS.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, response.getOutputStream());
exporterXLS.exportReport();
//Exporting to RTF format and open in word on client side
response.setContentType("application/vnd.ms-word");
response.setHeader("Content-Disposition", "inline;filename=reportRTF.rtf");
JRRtfExporter exporterRTF = new JRRtfExporter();
exporterRTF.setParameter(JRExporterParameter.JASPER_PRINT, jasperprint);
PrintWriter out = response.getWriter();
exporterRTF.setParameter(JRExporterParameter.OUTPUT_WRITER, out);
exporterRTF.exportReport();