Hot questions for Using JasperReports in servlets

Question:

I want to open a new tab when I run index.jsp file in a web application . And I have used Show.java (a servlet) to perform that . The current situation is when I click the Print button in index.jsp , the content page which I want to open in a new tab is displaying on the current tab . I want to do it using servlet response and not using javascript or jquery .

This is the I've written in index.jsp file ,

<form action="Show">            
    <input type="submit" value="Print"/>
</form>

<%@page import="net.sf.jasperreports.engine.export.JRPdfExporter" %>

<%
   JRPdfExporter export = (JRPdfExporter)request.getAttribute("exportIndentObject");
   if (export != null){
         JRPdfExporter export1 = (JRPdfExporter) session.getAttribute("exportIndentObject");
         export1.exportReport();
    }%>

This is Show.java which I use to keep content,

String param ="Terance";     
  Map<String, Object> map = new HashMap<String, Object>();
  map.put("param", param);                
  JRPdfExporter jRPdfExporter = new  JRPdfExporter();                                                                       jRPdfExporter.setParameter(JRPdfExporterParameter.PDF_JAVASCRIPT,                                      this.print();");

  String jsaperFile="C:\\Users\\user\\Desktop\\Terance\\Jasper\\JasperReport\\src\\java\\jasper\\Report.jrxml";
System.out.println(jsaperFile);
try
                    {
                        String report=JasperCompileManager.compileReportToFile(jsaperFile);

                        File file=new File(report);
                        if(!file.exists()){
                            throw new JRException("Cannot find the given file .");
                        }

                        JasperPrint jasperPrint=JasperFillManager.fillReport(report, map);
                        byte[] exportReportToPdf = JasperExportManager.exportReportToPdf(jasperPrint);

                        ServletOutputStream sout = response.getOutputStream();
                        response.setContentType("application/pdf;");

                        jRPdfExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
                        jRPdfExporter.setParameter(JRExporterParameter.OUTPUT_WRITER, sout);
                        jRPdfExporter.setParameter(JRPdfExporterParameter.PDF_JAVASCRIPT, "this.print();");

                        request.setAttribute("exportIndentObject", jRPdfExporter);

                        response.setContentType("application/pdf");
                        response.setHeader("Content-disposition","inline; filename=\"myReport.pdf\"");        


                        sout.write(exportReportToPdf);      
                        sout.flush();
                        sout.close();              

                    } catch (JRException ex)
                    {
                        ex.printStackTrace();
                    }

When I use response.redirect(); , I couldn't get even the index.jsp file in browser .


Answer:

Only for all or none:

<form ... target="_blank">

So maybe place the print button outside the original form and have its own form tags.

Question:

My application is running in a tomcat server, and I have already developed a method to download a pdf file using jasper. What i need to do is, download that certain pdf to a location inside the server. I tried and I am not sure how to do it.

            jasperReport = JasperCompileManager.compileReport(absolutePathToIndexJSP);
            JasperPrint gh = JasperFillManager.fillReport(jasperReport,parameters, JRdataSource);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            Exporter exporter = new Exporter();
            String downloadFileName = "";


            downloadFileName = "Fund-Transfer-Report-" + reportGenerateDate + ".pdf";
                response.setHeader("Content-Disposition", "attachment; filename=" + downloadFileName);
                response.setContentType("application/pdf");
                exporter.exportPdf(response, gh, baos);

And this go to an exporter method as below,

public void exportPdf(HttpServletResponse response, JasperPrint jp, ByteArrayOutputStream baos) throws JRException, IOException {

    //OutputStream ouputStream = new FileOutputStream(new File("C:/JasperReports/Account_Report.pdf"));
    //Get response output stream to download report file
    OutputStream ouputStream = response.getOutputStream();

    // Create a JRPdfExporter instance
    JRPdfExporter pdfExporter = new JRPdfExporter();

    // Here we assign the parameters jp and baos to the exporter
    pdfExporter.setParameter(JRExporterParameter.JASPER_PRINT, jp);
    pdfExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);

    pdfExporter.exportReport();

    ouputStream.write(baos.toByteArray());
    ouputStream.flush();
    ouputStream.close();
  }

What this does is normaly download the pdf to the download folder. I need to be able to download it to a location in the server. Please advice.


Answer:

You can use JasperExportManager to save the generated pdf to a specific location in server

JasperExportManager.exportReportToPdfFile(jasperPrint, exportPath);

eg:

String exportDir = System.getProperty("jboss.server.config.dir") +"/jasperreport/export";
String exportPath = exportDir + "/reportName.pdf";
JasperReport jasperReport = CompileManager.compileReport(jrxmlFilePath, mainReportName);
JasperPrint jasperPrint =JasperFillManager.fillReport(jasperReport, parameters, jsonDataSource);
JasperExportManager.exportReportToPdfFile(jasperPrint, exportPath);

Question:

There are more then 100 reports in application. I would like to integrate them in large web application.

I found the idea here : http://jasperreports.sourceforge.net/sample.reference/webapp/index.html.

So, I would like to create Servlet which will return pdf, html or xlsx formats of reports. I've already done that by example for one Report class. Moreover, my servlet returns type which it receives from parameter.

However, I can not realize writing (with mapping etc) for each report class. How can I avoid that by using same servlets for different reports (different classes). In this case - MyDataExample.

Here it is :

public class ServletExample extends HttpServlet {

@Override
public void doGet(HttpServletRequest req,
                  HttpServletResponse resp)
        throws ServletException, IOException {

    MyDataExample masterData = new MyDataExample(new ReportParameters(Long.valueOf(req.getParameter("id")), 2, DatabaseConnection.getConnection(), null));
    JasperPrint print = masterData.build();

    req.getSession().setAttribute(BaseHttpServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, print);

    String outputType = req.getParameter("outputType");
    Exporter exporter;
    switch (outputType) {
        case "html":
            try {
            PrintWriter out = resp.getWriter();
            resp.setContentType("text/html");
            req.getSession().setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, print);

            exporter = new HtmlExporter();
            exporter.setExporterInput(new SimpleExporterInput(print));
            SimpleHtmlExporterOutput output = new SimpleHtmlExporterOutput(out);
            output.setImageHandler(new WebHtmlResourceHandler("/reports/image?image={0}"));
            exporter.setExporterOutput(output);

                exporter.exportReport();
            } catch (JRException e) {
                e.printStackTrace();
            }
            break;
        case "pdf":
            resp.setContentType("application/pdf");
            exporter = new JRPdfExporter(DefaultJasperReportsContext.getInstance());
            exporter.setExporterInput(new SimpleExporterInput(print));
            try (OutputStream outputStreams = resp.getOutputStream()) {
                exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(outputStreams));
                exporter.exportReport();
            } catch (JRException e) {
                e.printStackTrace();
            }
              }
            break;
        case "xlsx":
            resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            exporter = new JRXlsxExporter(DefaultJasperReportsContext.getInstance());
            exporter.setExporterInput(new SimpleExporterInput(print));
            try (OutputStream outputStream = resp.getOutputStream()) {
                exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(outputStream));
                SimpleXlsReportConfiguration configuration = new SimpleXlsReportConfiguration();
                configuration.setOnePagePerSheet(false);
                configuration.setWhitePageBackground(false);
                exporter.setConfiguration(configuration);
                exporter.exportReport();
            } catch (JRException e) {
                e.printStackTrace();
            }
            break;
        default:
            throw new RuntimeException("Unknown type selected");
    }

  }
}

Answer:

So, I found that everything was easy, just refresh the page because your browser can cache the page. So, you could get different instances by using different values of same parameter, for example:

 if(req.getParameter("className").equals("A"))
    classObject = new A();
    else
    classObject = new B();

This example works perfect, also you can automate this actions by creating class example according to its name by using reflection.

Question:

How Can I export a jasperReport to pptx???

I try this but don't work...

The servlet return a pptx file, but the file can not be open

        JasperPrint jasperPrint = JasperFillManager.fillReport(reporte, parametros, new JREmptyDataSource());
        String fileName = "informeDemo.pptx";
        JRPptxExporter exporter = new JRPptxExporter();
        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, fileName);
        exporter.exportReport();

        File f = new File(fileName);

        response.setContentType("application/vnd.openxmlformats-officedocument.presentationml.presentation"); //Tipo de fichero.
        response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\""); //Configurar cabecera http

        InputStream in = new FileInputStream(f);
        out = response.getOutputStream();

        int bit = 256;
        while ((bit) >= 0) {
            bit = in.read();
            out.write(bit);
        }

        out.flush();
        out.close();
        in.close();

Answer:

Here's do it following way:

                JasperPrint jasperPrint = JasperFillManager.fillReport(reporte, parametros, new JREmptyDataSource());
                String fileName = "informeDemo.pptx";
                JRPptxExporter exporter = new JRPptxExporter();
                exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
                exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, fileName);
                ByteOutputStream bos=new ByteOutputStream();  // note bos will contain jasperPrint as byte data
                exporter.setParameter(JRExporterParameter.OUTPUT_STREAM,bos);
                exporter.exportReport();

                response.setContentType("application/vnd.openxmlformats-officedocument.presentationml.presentation"); //Tipo de fichero.
                response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\""); //Configurar cabecera http
                response.setCharacterEncoding("UTF-8");
                response.getOutputStream().write(bos.getBytes()); //note bos is written to response's output stream.
                bos.flush();
                bos.close();
                response.flushBuffer();

Hope this helps you.

Question:

Help me out i have an issue with the jasper report over a servlet, error is mentioned below

SEVERE: Allocate exception for servlet JaspersJob_servlet java.lang.ClassNotFoundException: net.sf.jasperreports.engine.JRRuntimeException at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526) at java.lang.Class.getDeclaredConstructors0(Native Method) at java.lang.Class.privateGetDeclaredConstructors(Unknown Source) at java.lang.Class.getConstructor0(Unknown Source) at java.lang.Class.newInstance(Unknown Source) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1149) at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:827) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:129) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489) at java.lang.Thread.run(Unknown Source)

Servlet code:

 package jasper_job_Print;

 import java.io.File;
 import java.io.IOException;
 import java.io.PrintWriter;
 import java.sql.*;

 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import net.sf.jasperreports.engine.*;
 import net.sf.jasperreports.engine.design.JRDesignQuery;
 import net.sf.jasperreports.engine.export.JRPdfExporter;
 import net.sf.jasperreports.engine.util.JRLoader;

 public class JaspersJob_servlet extends HttpServlet {

 private static final long serialVersionUID = -3478873702336546526L;

 protected void service(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
Connection con=null;
File reportFile = null;
JasperPrint jasperPrint = null;
ResultSet rs=null;
Statement statement = null;
    try {
        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/cloudinterdataset",                                                      "root","cosmos123");
        reportFile = new File("C:\\abd\\JasperJava\\report10.jasper");
        String sql1 = "SELECT * FROM userdetails "
                + "ORDER BY Lastname ";
        statement = con.createStatement();
        rs = statement.executeQuery(sql1);
        if (!reportFile.exists())
            throw new JRRuntimeException(
                    "File WebappReport.jasper not found. The report design must be compiled first.");
    } catch(Exception e) {
        System.out.println("Exception : "+e);
    }

    try {
        JRResultSetDataSource resultSetDataSource = new
                JRResultSetDataSource(rs);
        System.out.println("Filling Jasper PDF report...");
        JasperReport jasperReport = (JasperReport) JRLoader
                .loadObject(reportFile.getPath());
        jasperPrint = JasperFillManager.fillReport(jasperReport,null,resultSetDataSource);
        System.out.println("Done!");
        if (jasperPrint != null)
        {
            JRExporter exporter = null;
            exporter = new JRPdfExporter();

            exporter.setParameter(JRExporterParameter.JASPER_PRINT,
                    jasperPrint);
            exporter.setParameter(JRExporterParameter.OUTPUT_STREAM,
                    response.getOutputStream());

            exporter.exportReport();
        } else {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head>");
        out.println("<title>JasperReports </title>");
        out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"../stylesheet.css\"    title=\"Style\">");
        out.println("</head>");
        out.println("<body bgcolor=\"white\">");
        out.println("<span class=\"bold\">Empty response.</span>");
        out.println("</body>");
        out.println("</html>");
        }
    } catch(Exception e) {
        System.out.println("Exception :"+e);
    }
}

}


Answer:

Is a very simple solution i did not put the Jar Files in my project lib. Its working now, just got time to post my answer

Question:

I am writing a java servlet that should generate a jasper report. I have stored the jrxml under the WebContent folder in a folder named jrxml (WebContent/jrxml/theFile.jrxml). First I used the following code to generate the report:

InputStream input = new FileInputStream(new File("/jrxml/employeesList.jrxml"));
JasperDesign jasperDesign = JRXmlLoader.load(input);
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);

However, I kept getting a "No such file or directory" error message. So I then used the following code which I took from Accessing properties file in a JSF application programmatically :

String path = "/jrxml/employeesList.jrxml";
ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream input = loader.getResourceAsStream(path);
JasperDesign jasperDesign = JRXmlLoader.load(input);
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);

Now I no longer get a "No such file or directory" error message, but instead I get "net.sf.jasperreports.engine.JRException: java.net.MalformedURLException" exception, and according to the stack trace it is being cause by the fourth command (JRXmlLoader.load(input)). Can someone please tell me what I'm doing wrong?

Thanks


Answer:

If you want to load a file in your WebContent folder you have to use ServletContext.html#getRealPath to get the actual path of the file in the filesystem, so you can try the following.

String path = getServletContext().getRealPath("/jrxml/employeesList.jrxml");
InputStream input = new FileInputStream(new File(path));
JasperDesign jasperDesign = JRXmlLoader.load(input);
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);

OTOH

If ClassLoader is used your resource should be in classpath (i.e. WEB_INF\classes or in any of the jars in WEB-INF\lib)

Question:


Answer:

Don't pass the object rather give the link of your Servlet behind the Download option i.e. PDF,CSV,Excel.

When someone will click on it. Either it will get downloaded or streamed as you wish.

Question:


Answer:

I got the web application running. The problem was with the jar file placement. For a web-app, all the jars should be placed within the WEB-INF/lib directory for Tomcat to read/recognize the jars.

I Kindly request the Admins to CLOSE the question. Cheers.