Hot questions for Using JasperReports in javascript

Question:

I'm trying to compile a JasperDesign to create a report programmatically. Since I need to include a Conditional Style in Javascript, I set the JasperDesign language accordingly:

val jasperDesign = new JasperDesign
jasperDesign.setLanguage("javascript")

Note that I'm using Scala 2.11 on Java 8, running on Play for Scala 2.5

Since JasperReports 6.4.3 (the version I'm using) has a dependency on rhino 1.7.6, I added it to the classpath:

libraryDependencies += "org.mozilla" % "rhino" % "1.7.6"

The problem is that whenever I compile the JasperDesign I get an exception. This happens even when I don't include a Javascript Conditional Style:

java.lang.NoSuchMethodError: org.mozilla.javascript.ContextFactory.enterContext()Lorg/mozilla/javascript/Context; at net.sf.jasperreports.compilers.JavaScriptClassCompiler.compileUnits(JavaScriptClassCompiler.java:124) at net.sf.jasperreports.engine.design.JRAbstractCompiler.compileReport(JRAbstractCompiler.java:203) at net.sf.jasperreports.engine.JasperCompileManager.compile(JasperCompileManager.java:357) at net.sf.jasperreports.engine.JasperCompileManager.compileToStream(JasperCompileManager.java:326) at net.sf.jasperreports.engine.JasperCompileManager.compileReportToStream(JasperCompileManager.java:599)

If I remove jasperDesign.setLanguage("javascript") I have no compilation errors. What is missing here? Is there a conflict between Nashorn and Rhino?


Answer:

My solution was to take the rhino 1.7.6 jar and manually put it in the application lib folder. Play loaded it from there with no issues.

Question:

One of the project requirements for my new java web project is to have dynamic charts that will load really fast.

While in discussion , it was asked if we could implement charts without using images ie without loading jpg, png files etc. Also files like pdf cannot be used.

Basically my question is

  1. Can charts be implemented in jsp/javascript without using images,pdf etc ? ie even api's used should not provide end result as image,or pdf etc.

  2. I did not say no right away , as I have implemented charts in console applications in C on screen. Can we do something like that on a webpage ? ie show a graph by drawing on screen dots,lines,circles etc.But it should be possible inside a div ?

PS : Comments and answer from Lucien Stals helped to understand that the technology i was looking for was svg.

I am looking for some nudging in the right direction from some of the experienced java , javascript programmers in SO.


Answer:

Many JavaScript chart libraries exist that render in HTML5 on your page. You can probably find one that meets other requirements or wishes of your team, since each have feature areas in which they excel. http://www.zingchart.com has also been adding many ways to include them in your charts if you decide to go with something other than vanilla JavaScript (jQuery, Angular, etc). Full disclosure: I'm on the ZingChart team. I can help you weigh the pro's and con's if you find a few that catch your interest.

Question:

I'm trying to download excel file by using Jasper Report 6.2.2

Here is my Spring Controller:

@RequestMapping(value = "/downloadExcel", method = RequestMethod.POST)
    @ResponseBody
    public void downloadMyReportExcelFile(@RequestBody ExcelFilter excelFilter, HttpServletResponse response) {
        try {

            reportExportBo.downloadReportFile(response, excelFilter);


        } catch (Throwable e) {
            LOGGER.error("Unknown error at REST Service", e);
        }
    }

and also here is my downloadReportFile method codes:

    @Override
        public void downloadReportFile(HttpServletResponse response, ExcelFilter excelFilter) {

            List<myClassObject> myObjectList= objectRecordBo.myData(excelFilter);

            InputStream is = this.getClass().getClassLoader().getResourceAsStream("/my_reports.jrxml");

            ExcelExporter exporter = new ExcelExporter();

            String fileName = "my_exported_report.xls";

            JasperDesign jd = JRXmlLoader.load(is);
            JasperReport jr = JasperCompileManager.compileReport(jd);

            JasperPrint jprint = JasperFillManager.fillReport(jr, null, new JRBeanCollectionDataSource(myObjectList));

            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

            JRXlsExporter xlsExporter = new JRXlsExporter();
            xlsExporter.setExporterInput(new SimpleExporterInput(jprint));
            xlsExporter.setExporterOutput(new SimpleOutputStreamExporterOutput(response.getOutputStream()));

            SimpleXlsReportConfiguration xlsReportConfiguration = new SimpleXlsReportConfiguration();
            xlsReportConfiguration.setOnePagePerSheet(false);
            xlsReportConfiguration.setRemoveEmptySpaceBetweenRows(true);
            xlsReportConfiguration.setDetectCellType(false);
            xlsReportConfiguration.setWhitePageBackground(false);
            xlsExporter.setConfiguration(xlsReportConfiguration);

            xlsExporter.exportReport();

my_reports.jrxml is suitable for myObjectList, columns and variables are same.

Also here is my javascript function;

function downloadService(url, paramData, fileName, $http) {

return $http.post(url, paramData, {responseType:'Content-Type'}).then(function (response) {
    var blob = new Blob([response.data], {type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
    var objectUrl = URL.createObjectURL(blob);
    var a = document.createElement("a");
    a.style = "display: none";
    a.href = objectUrl;
    a.download = fileName + '.xls' ;
    document.body.appendChild(a);
    a.click();
    setTimeout(function () {
        document.body.removeChild(a);
        window.URL.revokeObjectURL(objectUrl);
    }, 100);
}, function (response) {
    //TODO
    });
}

After calling downloadService method, i got excel downloaded but it is not readable

What do i wrong?

EDITED:

By the way when i'm using in html side;

<a style="float:right; " href="service/downloadExcel">{{ 'EXPORT_EXCEL' | translate}}</a>

and Spring controller is GET and no any @RequestBody, it works fine. But I need to pass parameters with JSON Object, so i can not use it.


Answer:

I solved my problem.

First I set Header and Content Type of Response, before JasperDesign.

...
if (list != null && list.size() > 0) {
                response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

                JasperDesign jd = JRXmlLoader.load(reportStream);
                JasperReport jr = JasperCompileManager.compileReport(jd);
...

Also I updated my ajax service as;

...
return $http.post(newUrl, paramData, {responseType: 'arraybuffer'}).then(function (response) {
            var blob = new Blob([response.data], {type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=UTF-8'});
....

Thanks for helping guys...

Question:

I'm new in JasperReports. So,I have successfully created the report function as I want, I have 3 parameters, which consist of date and 2 strings. So far, it's going very well when the query is having a result (not empty). But if the query is empty, the pdf created will be plain white blank.

So, what I wanna do is, I want to validate it, whenever it's going to generate a plain white pdf, I don't want to show the blank pdf, instead I want to show some error message. Is this possible?

Here is my code, using javascript in JSP.

<%
    Connection conn = null;
    try{
        Class.forName("oracle.jdbc.OracleDriver");
        conn = DriverManager.getConnection("jdbc:oracle:thin:@333.0.0.1:3333:sample", "asd", "asd");
    } catch (Exception e){
        e.printStackTrace();
    }

    String method_param = request.getParameter("method");
    if(method_param.equals("default")){
        method_param = "%";
    }

    String date_param = request.getParameter("date");
    if(date_param == ""){
        date_param = "%";
    }

    String status_param = request.getParameter("status");
    if(status_param.equals("default")){
        status_param = "%";
    }


    Map parameters = new HashMap();
    parameters.put("method_param", method_param);
    parameters.put("date_param", date_param);
    parameters.put("status_param", status_param);

    JasperPrint jasperPrint = JasperFillManager.fillReport("C:/myaddress/lalala/WEB-INF/reports/Reports.jasper", parameters, conn);
    OutputStream outputStream = response.getOutputStream();
    JRExporter exporter = new JRPdfExporter();
    response.setContentType("application/pdf");
    response.setHeader("Content-Disposition", "inline; filename=\"report.pdf\"");
    exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
    exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, outputStream);
    exporter.exportReport(); 

      if (outputStream != null)
        {
          try
          {
            outputStream.close();
          }
          catch (IOException ex){
            ex.printStackTrace();
          }
        }


%>

It worked well, but I just want to avoid the blank pdf.


Answer:

There is a predefined variable called REPORT_COUNT provided by jasper report. It contains the total number of records present in the report.

You can make use of this variable to show a appropriate message such as 'No records found'.

Thanks