views:

475

answers:

2

hello friends i am new to jasperreport and dont know how to call jasper file from servlet me and my jasper file contains pie chart also plese help

A: 

Here is a dummy report created within a Servlet file.

It is the same as it would be in normal Java class.

Just make sure you have the imports for your jasper report classes at the top of the file.

The bellow example builds a report from an XML datasource.

public class JasperServlet extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        try {
            String reportFile = "myJasperReport.jrxml";
            File outputFile = new File("Report.pdf");
            HashMap hm = new HashMap();

            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory
                    .newDocumentBuilder();
            Document document = documentBuilder.parse(new File("myXml.xml"));

            // Compile the report
            JasperReport report = JasperCompileManager
                    .compileReport(reportFile);
            JRXmlDataSource xml = new JRXmlDataSource(document, "/xml/root");
            // Fill the report
            JasperPrint print = JasperFillManager.fillReport(report, hm, xml);
            // Create an Exporter
            JRExporter exporter = new JRPdfExporter();
            exporter.setParameter(JRExporterParameter.OUTPUT_FILE, outputFile);
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
            // Export the file
            exporter.exportReport();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Gordon
+1  A: 

You can prepare the Jasper file and stream it to the client.

bytes[] byteStream = JasperRunManager.runReportToPdf("myJasperReport.jasper",paramMap,databaseConn);

OutputStream outStream = servletResponse.getOutputStream();
response.setHeader("Content-Disposition","inline, filename=myReport.pdf");
response.setContentType("application/pdf");
response.setContentLength(byteStream.length);
outStream.write(bytes,0,bytes.length);
medopal