Jump to content
We've recently updated our Privacy Statement, available here ×
  • Using Custom Visualization Component in the JasperReports Server


    spatnaik_1
    • Features: Charts Version: v7.9.0 Product: JasperReports® Server

    Introduction

    Currently in Jasper Studio we have only limited Chart options, but now with CVC you can create different variants. If you want some charts which along with displaying proper data also look good to your eyes with CVC coming into picture you can create varieties of reports like a Radial chart and also include animations to the chart.

    Custom Visualization Component or popularly known as CVC is nothing but a very powerful and flexible feature which allows the use of Javascript to create custom visualizations in reports.

    The CVC allows rendering an SVG image generated by using JavaScript code. We can use any advanced javascript libraries such as D3, Raphael, JQuery in CVC to create custom visualizations and animations in the report.

    When the javascript libraries and the modules provided by the user are joined together by CVC which acts as a bridge between the two, visualization is being produced. 

    In case the report is exported to HTML, the JavaScript code is executed directly inside the final document. This allows us to take full advantage of the browser functionalities. When the report is exported to other file formats (such as PDF), the component takes care of rendering the SVG image produced by the JavaScript code, behaving like a regular image element. If the script does not produce SVG images, but more complex HTML, the visualization can be rendered as a PNG image when exported to formats different from HTML.

    In this guide we are going through the following:

    • Properties

    • CVC Samples already available in Jaspersoft Studio

    • Creating your own CVC report

    • Publishing the CVC report into Jasperreports Server

    • Executing the CVC report in Jasper Reports Server

    Properties

    There are the common properties that can be used with any custom visualization component:

    • script - the location of the JavaScript file implementing the component

    • module - (optional) the name of the JavaScript module to be loaded by using RequireJs (if not specified, the base name of the JavaScript file without extensions will be assumed as name of the module)

    • css - (optional) the location of a CSS file eventually used by the component

    • renderAsPng - (optional) a boolean value that can be used when the content produced is not an SVG image

     

    Each custom visualization is composed of one or more JavaScript files that are combined and optimized by using RequireJs.

    converted-image.png.389f9db4f03e1c16a05089583c6fb272.png

    CVC Samples already available in Jaspersoft Studio

     

    Currently in Jasper Studio, we have the following CVC available for use:

    • Figures:

    A d3.js based visualization to represent a quantity by using figures.

    converted-image.png.d2fc117cb3fba2d2497e8c73db1286b0.png

    • Radial Progress:

    A d3.js based visualization to display a percentage value with a circle.

    converted-image.png.ea62dbb7de52dd2b22120acfcae05c17.png

    • Sparkline:

    A d3.js based minimalist line chart which displays data coming from a sub-dataset.

    converted-image.png.3568416168b3fa7df7d1f4ba4edca05f.png

    Apart from the above, we could also build our own CVC report by defining appropriate Javascript modules which we will be doing in our next section. Before starting, it is important to keep in mind that Custom Visualization Components are not able to stretch, which means that the allocated space in the report for the component is defined at design time and will not change based on what is rendered.

     

    Creating your own CVC report

    Here in this guide we'll be making use of D3 libraries to create a Radial bar chart CVC report.

    First things first, following are the prerequisites before we start creating CVCs:

    • PhantomJS(or Chromium) should be available and configured in Jasper Studio. This helps in rendering your JavaScript module's visual component.

    Step by step process:

    • Open Jasper Studio.

    • Let's create a CVC Project -> File -> New -> Others… -> Custom Visualization Component and provide an appropriate name for the project and the module.

    converted-image.png.23b5c1da6c30af98e648242d104d2f1b.png

    • Make sure to accept the licenses as Jaspersoft Studio is not packaged along with the D3 licenses.

    converted-image.png.c0ad1668d8eb802bed9ce6d1e935ea5d.png

    converted-image.png.3ce99322f8aece88723d88d2c1b570d2.png

    • The CVC Project structure should be something like this:

    converted-image.png.310b68260751668e56aae92da6ecb7c1.png

    • Now as you can see we have created a CVC Project successfully. It already has all the sample files in it which makes our work pretty easier. A couple of changes and then our CVC will be ready.

    • If we take a look at the sample jrxml file, we can see it already has a Custom Visualization Component embedded inside. This CVC points to Javascript file, Javascript module and a CSS file which is optional.

    converted-image.png.18208d1f1a262bf2448866419f27435f.png

    •  Here we shall make use of the radialBar chart D3 and jquery libraries for creating the CVC. And we already have a d3.min.js file available, so we need not worry about the D3 library,

    • In order to generate the RequireJS module we have a build.js file included which is required to create a minified/optimised version of the library. So make sure if there are any external libraries (here in our case we are using d3.min.js) used for creating CVC, it should be included as a reference in the build.js file. 

    Let's quickly add the appropriate entries in the build.js file:

    ({
        //optimize: 'none', // Uncomment this property to disable the uglify of the libraries
        baseUrl: '',
        paths: {
    'd3': 'd3.min' ,
    'CVC': 'CVC'
    },
    
    wrap: {
            start: "(function(root){nnvar define = root.define;nn",
            end: "nn}(typeof __visualize__ != 'undefined' ? __visualize__ : (typeof __jrio__ != 'undefined' ? __jrio__ : window)));"
        },
       
        name: "CVC",
        out: "CVC.min.js"
    })

     

     

     

    • In order to be able to style individually each SVG in our report, we need to reference an element id. The element id available in the instanceData object is the element id of the DIV containing the SVG, and is generated at run time, so it cannot be hardcoded in the static css file. For this reason, the css provided with the component is processed by the component itself, which replace the occurrences of /*eleid*/ with something like #element123456 (which is the css syntax to reference a specific element id). Now let's look into the CVC.css file

    /*elid*/svg {
      display: block;
    }
    
    
    //defining the font style
    /*elid*/svg text {
      font-size: 11px;
      font-family: Helvetica, Arial, sans-serif;
    }

     

     

    • Next thing we should be taking care is the Javascript file i.e here in our example is CVC.js file. In order to render the CVC report as per our requirement, this file has to be modified accordingly. Make sure the required external libraries are defined:

     

    define('CVC',['d3'], function (d3) {
    
    return function (instanceData) {
    
    var width = instanceData.width,
    height = instanceData.height,
    barHeight = height / 2 - 40;
     
    var formatNumber = d3.format("s");
    
    var color = d3.scale.ordinal()
    
    
    //defining an array of colors. We will use this to give a //color gradient to our bars.  .range(["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69","#fccde5","#d9d9d9","#bc80bd","#ccebc5","#ffed6f"]);
    
    
    // append the svg object
    var svg = d3.select("#" + instanceData.id).append("svg")
        .attr("id", instanceData.id + "svg")
        .attr("width", width)
        .attr("height", height)
        .append("g")
        .attr("transform", "translate(" + width/2 + "," + height/2 + ")");
    
    
    //making use of the Foodmart datasource
    const data = instanceData.series[0].map(function(serie) {
               
                return {
                    name: serie.name,
                    value: serie.value,
                }
            });
      data.sort(function(a,b) { return b.value - a.value; });
    
      var extent = d3.extent(data, function(d) { return d.value; });
      var barScale = d3.scale.linear()
          .domain(extent)
          .range([0, barHeight]);
    
      var keys = data.map(function(d,i) { return d.name; });
      var numBars = keys.length;
    
      var x = d3.scale.linear()
          .domain(extent)
          .range([0, -barHeight]);
    
      var xAxis = d3.svg.axis()
          .scale(x).orient("left")
          .ticks(3)
          .tickFormat(formatNumber);
         
      var circles = svg.selectAll("circle")
              .data(x.ticks(3))
            .enter().append("circle")
              .attr("r", function(d) {return barScale(d);})
              .style("fill", "none")
              .style("stroke", "black")
              .style("stroke-dasharray", "2,2")
              .style("stroke-width",".5px");
    
      var arc = d3.svg.arc()
          .startAngle(function(d,i) { return (i * 2 * Math.PI) / numBars; })
          .endAngle(function(d,i) { return ((i + 1) * 2 * Math.PI) / numBars; })
          .innerRadius(0);
     
      var segments = svg.selectAll("path")
              .data(data)
            .enter().append("path")
              .each(function(d) { d.outerRadius = 0; })
              .style("fill", function (d) { return color(d.name); })
              .attr("d", arc);
    
      segments.transition().ease("elastic").duration(0)
              .attrTween("d", function(d,index) {
                var i = d3.interpolate(d.outerRadius, barScale(+d.value));
               
    svg.append("circle")
          .attr("r", barHeight)
          .classed("outer", true)
          .style("fill", "none")
          .style("stroke", "black")
          .style("stroke-width","1.5px");
    
      var lines = svg.selectAll("line")
          .data(keys)
        .enter().append("line")
          .attr("y2", -barHeight - 20)
          .style("stroke", "black")
          .style("stroke-width",".5px")
          .attr("transform", function(d, i) { return "rotate(" + (i * 360 / numBars) + ")"; });
    
      svg.append("g")
        .attr("class", "x axis")
        .call(xAxis);
    
      // Labels
      var labelRadius = barHeight * 1.025;
    
      var labels = svg.append("g")
          .classed("labels", true);
    
      labels.append("def")
            .append("path")
            .attr("id", "label-path")
            .attr("d", "m0 " + -labelRadius + " a" + labelRadius + " " + labelRadius + " 0 1,1 -0.01 0");
    
      labels.selectAll("text")
            .data(keys)
          .enter().append("text")
            .style("text-anchor", "middle")
            .style("font-weight","bold")
            .style("fill", function(d, i) {return "#3e3e3e";})
            .append("textPath")
            .attr("xlink:href", "#label-path")
            .attr("startOffset", function(d, i) {return i * 100 / numBars + 50 / numBars + '%';})
            .text(function(d) {return d.toUpperCase(); });
    
    return function(t) { d.outerRadius = i(t); return arc(d, index); };
    });
    };
    
    });

     

     

    Explanation of what we are doing here:

    The first step is including the modules as defined in the build.js file and here we have included [‘d3’] modules. 

    If we take a look into the code, it contains the settings defined on how you want to color the bars of the radial chart. Also, currently in our report we have made use of the Foodmart Datasource.

    We have a svg component defined and attached to an instanceData.

    • Let’s go to the next part where we are configuring a Data adapter. Right click on the CVC project select New-> Data Adapter. Provide a name and click on ‘Next’.

    converted-image.png.6b471234a4179e8b3e9553753ff253c5.png

    • Select ‘Database JDBC Connection’ and click on Next.

    converted-image.png.5477d1bc8ee41e4a1aecbc1561f23c3d.png

    • Provide all the correct details as mentioned below and click on the Finish button. Remember to provide the correct Hostname and Username/Password.

    converted-image.png.551436bf8d8aa0ac99754cf1945ab6bd.png

    • Now open CVC_sample.jrxml report. Click on converted-image.png.44d33898783c245422cb01d37667b422.png and provide the following sql query in the Dataset and Query Dialog:

    SELECT brand_name,
    MAX(cases_per_pallet) as cases_per_pallet
    FROM product
    GROUP BY brand_name
    ORDER BY brand_name ASC
    LIMIT 10

     

     

    • Click on ‘Read Fields’ and then click on the Ok button. Now click on the Custom Visualization component element in the report and navigate to Data tab in the Properties section.

    converted-image.png.6a93868dd6903360638ccf43e1de95e8.png

    • Click on ‘Add’ button and check the ‘Use Dataset’ checkbox as below:

    converted-image.png.309bf8cd742a68788ca9deea1657c891.png

    • Now navigate to ‘Items’ tab and include the following properties by clicking on Add button and then click OK button to save the changes:

    converted-image.png.29eb0185fea9c921d48b95801bb1d43c.png

    • As we are ready with all the required libraries, javascript files and the dataset. But only modifying the scripts and configuring the dataset should not be sufficient. Moving to the Next and the most important part is compiling the build.js which in turn recreates a new version of the CVC.min.js based on the changes made.  

    • For that right click on build.js file and click ‘Build Component’. Navigate to Custom Visualization Component console (Under ‘Display Selected Console’ select Custom Visualization Component console). This is pretty important as we can see the appropriate messages as well if there are any compilation errors in the Javascript.

    • Wait for the compilation to complete and once done we should see something like this in the console:

    converted-image.png.af6c852664d146796bbb44d5ceac04de.png

    • As all our components are ready and modified as per our requirement. We should now be able to preview the CVC report i.e “CVC_sample.jrxml”. Make sure the preview format is selected as HTML as all the CVCs are rendered in the same format.

    This is how our report should look like:

    converted-image.png.d3b463963fdc4e2e361c410a0a6247fb.png

    Similarly, we could also create different types of CVC reports by making use of any external libraries.

     

    Publishing the CVC report into Jasperreports Server

    Lets publish the same CVC report into Jasperreports Server and execute it.

    • First step towards publishing the report should be creating a Server connection in the Studio. Navigate to Repository explorer and right click on ‘Servers’ and select ‘Create JasperReports Server Connection’. Fill the required details as below:

    converted-image.png.ffeaa3140dece432cbcd4e90b2e5177e.png

    • Once the Server creation is done we can now publish our CVC report into Jasper Reports Server easily.

    • Open the jrxml report which in our case is “CVC_sample.jrxml”. Click on the converted-image.png.b17ccf9962938496ed69260bdb7ad79a.png icon available in the top right corner.

    • Select the server created above and expand the folder structure. Select an appropriate folder to publish the report. Here, we want to publish the report in /public folder:

    converted-image.png.991e086d74644968d45d42c12e7a1412.png

    • Click on Next. In the next tab we should be able to see the required resources also getting published along with the report.

    converted-image.png.be32fb01b7f0d9f37088ecf5300a20bc.png

    • Click Next. Select the Foodmart datasource while publishing and then click the Finish button. 

    converted-image.png.d3b3494bb37bf2e39878b37ed999ecac.png

    • We should see a success message after the CVC report is published.

     

    Executing the CVC report in Jasper Reports Server

    • Once the report is successfully published. Login to Jasper Reports Server with valid credentials and navigate to the /public folder in the repository. The report should be available there. Execute the report.

    converted-image.png.5a6240a5a176345e103aa1275032fb83.png

    • We can also try to achieve embedding the CVC report. In the report viewer, click on the ‘Get Embed code’ icon. You should be able to preview the report successfully.

    • We can also try including the CVC report into the Dashboard. Create a dashboard and add the CVC report published in the /public folder.

    converted-image.png.062a069d0114e552d0180bd33f88d2bc.png

    Example of one more Radial chart variant:

    • Grouped Radial Stacked Bar Chart:

     

    converted-image.png.333e1200b723332da65ed129218e0711.png

     

    cvc_0.zip

    cvc_1.zip


    User Feedback

    Recommended Comments

    There are no comments to display.



    Create an account or sign in to comment

    You need to be a member in order to leave a comment

    Create an account

    Sign up for a new account in our community. It's easy!

    Register a new account

    Sign in

    Already have an account? Sign in here.

    Sign In Now

×
×
  • Create New...