Jump to content
We've recently updated our Privacy Statement, available here ×
  • This documentation is an older version of JasperReports Server Visualize.js Guide. View the latest documentation.

    The report function runs reports on JasperReports Server and displays the result in a container that you provide. This chapter describes how to render a report in Visualize.js.

    The report function also supports more advanced customizations of hyperlinks and interactivity that are described in subsequent chapters:

    API Usage - Hyperlinks
    API Usage - Interactive Reports

    This chapter contains the following sections:

    Report Properties
    Report Functions
    Report Structure
    Rendering a Report
    Getting the Embed Code of a Report
    Setting Report Parameters
    Saving a Report
    Rendering Multiple Reports
    Resizing a Report
    Setting Report Pagination
    Creating Pagination Controls (Next/Previous)
    Creating Pagination Controls (Range)
    Exporting From a Report
    Exporting Data From a Report
    Refreshing a Report
    Canceling Report Execution
    Discovering Available Charts and Formats

    Report Properties

    The properties structure passed to the report function is defined as follows:

    Report Functions

    The report function exposes the following functions:

    Report Structure

    The Report Data structure represents the rendered report object manipulated by the report function. Even though it is named "data," it does not contain report data, but rather the data about the report. For example, it contains information about the pages and bookmarks in the report.

    The report structure also contains other components described elsewhere:

    The definitions of hyperlinks and how to work with them is explained in Customizing Links
    Details of the Jaspersoft Interactive Viewer and Editor (JIVE UI) are explained in Interacting With JIVE UI Components.

    Rendering a Report

    To run a report on the server and render it in Visualize.js, create a report object and set its properties. The server and resource properties determine which report to run, and the container property determines where it appears on your page.

    The following code example shows how to display a report that the user selects from a list.

    The HTML page that displays the report uses a static list of reports in a drop-down selector, but otherwise needs only a container element.

    Getting the Embed Code of a Report

    As of JasperReports Server 7.9, the server can provide the code to embed any report displayed in the report viewer. This lets you browse the repository, preview a report, and get its basic embed code. You can paste this code directly in your application, and then edit it for your needs. You can also open the report's embed code in JSFiddle to see the effect of your edits in real time, then copy the final code from JSFiddle.

    To copy the embed code of a report:

    1. Log into JasperReports Server and browse the repository to find the report you want to embed.
    2. Run the report to view its output in the server's report viewer.
    3. Click the js-Viewer-icon-EmbedCode.png.f66fd393cd05e67c9e66d2e007e818b1.png
    4. The Report Embed Code dialog shows you the Visualize.js code and a preview of the report as it is currently saved. Select Copy Code to copy the entire code block to your clipboard. You can also highlight selected parts of the code and use Ctrl-C (Command-C on Mac OS), for example if you want only the main function.

    The Embed Code of a Report

    js-Report-GetEmbedCode.png.baaabaa02b9dba2dd6c43f5bfb2b5287.png

    The code sample includes comments where you can enter credentials for authentication. You should also change the name of the container to match the one in your application.

    5. Alternatively, select Open in JSFiddle to load the same code into a new Fiddle, an online JavaScript viewer and interactive editor. This lets you modify the JavaScript or HTML, and add CSS if desired, then see the results in real time.

    Before or after copying the embed code, you can fine-tune the report within the viewer, for example sorting a table colum or changing the chart type. Save your changes to make them available to others. Visualize.js always displays the latest saved version of a report, as determined by the repository URL in the embed code.

    When displayed through Visualize.js, a report with a chart includes the js-Viewer-icon-ChartSelector.png.0648f085c9c7ea78b42a78fc22f4156b.png icon in the top left corner that allows users to switch between chart types, though not all chart types work with the data in a given report. This selector changes the chart in the user's current session, but the changes can't be saved. For every new session, Visualize.js displays the default appearance of the chart in the report.

    Setting Report Parameters

    To set or change the parameter values, update the params object of the report properties and invoke the run function again.

    The example above is trivial, but the power of Visualize.js comes from this simple code. You can create any number of user interfaces, database lookups, or your own calculations to provide the values of parameters. Your parameters could be based on 3rd party API calls that get triggered from other parts of the page or other pages in your app. When your reports can respond to dynamic events, they are seamlessly embedded and much more relevant to the user.

    Here are further guidelines for setting parameters:

    If a report has required parameters, you must set them in the report object of the initial call, otherwise you'll get an error. For more information, see Catching Report Errors.
    Parameters are always sent as arrays of quoted string values, even if there is only one value, such as ["USA"] in the example above. This is also the case even for single value input such as numerical, boolean, or date/time inputs. You must also use the array syntax for single-select values as well as multi-select parameters with only one selection. No matter what the type of input, always set its value to an array of quoted strings.
    The following values have special meanings:
         "" – An empty string, a valid value for text input and some selectors.
         "~NULL~" – Indicates a NULL value (absence of any value), and matches a field that has a NULL value, for example if it has never been initialized.
         "~NOTHING~" – Indicates the lack of a selection. In multi-select parameters, this is equivalent to indicating that nothing is deselected, thus all are selected. In a single-select non-mandatory parameter, this corresponds to no selection (displayed as ---). In a single-select mandatory parameter, the lack of selection makes it revert to its default value.

    Saving a Report

    Once you change the report parameters, you can save the new report in the repository. You can invoke the report.save function without parameters to overwrite the current report. You can also specify a new name or a new folder to save as a different report. The authenticated user must have write permission to the report or to the folder.

    The following schema describes the parameters to the report.save function:

    Rendering Multiple Reports

    JavaScript Example:

    visualize({    auth: { ...    }}, function (v) {    var reportsToLoad = [        "/public/Samples/Reports/AllAccounts",        "/public/Samples/Reports/01._Geographic_Results_by_Segment_Report",        "/public/Samples/Reports/Cascading_Report_2_Updated",        "/public/Samples/Reports/07g.RevenueDetailReport"    ];    $.each(reportsToLoad, function (index, uri) {        var container = "#container" + (index + 1);        v(container).report({            resource: uri,            success: function () {                console.log("loaded: " + (index + 1));            },            error: function (err) {                alert(err.message);            }        });    });});[/code]                    

    Associated HTML:

    Associated CSS:

    Resizing a Report

    When rendering a report, by default it is scaled to fit in the container you specify. When users resize their window, reports will change so that they fit to the new size of the container. This section explains several ways to change the size of a rendered report.

    To set a different scaling factor when rendering a report, specify its scale property:

    container – The report is scaled to fully fit within the container, both in width and height. If the container has a different aspect ratio, there will be white space in the dimension where the container is larger. This is the default scaling behavior when the scale property is not specified.
    width – The report is scaled to fit within the width of the container. If the report is taller than the container, users will need to scroll vertically to see the entire report.
    height – The report is scaled to fit within the height of the container. If the report is wider than the container, users will need to scroll horizontally to see the entire report.
    Scale factor – A decimal value greater than 0, with 1 being equivalent to 100%. A value between 0 and 1 reduces the report from its normal size, and a value greater than 1 enlarges it. If either or both dimensions of the scaled report are larger than the container, users will need to scroll to see the entire report.

    In every case, the entire report is scaled in both directions by the same amount, you cannot change the aspect ratio of tables and crosstab elements.

    For example, to initialize the report to half-size (50%), specify the following scale:

    var report = v.report({    resource: "/public/Sample",    container: "#reportContainer",    scale: 0.5});[/code]                    

    You can also change the scale after rendering, in this case to more than double size (250%):

    Alternatively, you can turn off the container resizing and modify the size of the container explicitly:

    To make the Report Viewer responsive, an additional property is introduced in Visualize.js that is reportContainerWidth. You need to set the value of this property to the width of the report container. Then this value is passed to the report execution process as REPORT_CONTAINER_WIDTH built-in parameter value.

    visualize({    auth: {...    }}, function(v) {     let reportConfig = {         resource: "/public/ResponsiveReport",         container: "#container",         reportContainerWidth: getContainerWidth(),         events: {               responsiveBreakpointChanged: function(error) {                    if (error) {                        console.log(error);                        } else {                         report.destroy();	                  // rerun report                                     reportConfig.reportContainerWidth = getContainerWidth();                         report = v.report(reportConfig);                            }                       }                    },                    error: (e) => console.error(e.message || e)            };            let report = v.report(reportConfig);            function getContainerWidth() {                  return document.getElementById("container").clientWidth;                    } });				[/code]                    

    Setting Report Pagination

    To set or change the pages displayed in the report, update the pages object of the report properties and invoke the run function again.

    The pages object of the report properties also supports bookmarks by specifying the anchor property. You can also specify both pages and bookmarks as shown in the example below. For more information about bookmarks, see Providing Bookmarks in Reports.

    Creating Pagination Controls (Next/Previous)

    Again, the power of Visualize.js comes from these simple controls that you can access programmatically. You can create any sort of mechanism or user interface to select the page. In this example, the HTML has buttons that allow the user to choose the next or previous pages.

    Associated HTML:

    Creating Pagination Controls (Range)

    JavaScript Example:

    Associated HTML:

    Exporting From a Report

    To export a report, invoke its export function and specify the outputFormat property. You MUST wait until the run action has completed before starting the export. The following export formats are supported:

    "pdf", "xlsx", "xls", "rtf", "csv", "xml", "odt", "ods", "docx", "json", "pptx"

    For CSV and JSON output, see Exporting Data From a Report. Note that the HTML output of a report is not available through Visualize.js.

    The following sample exports 10 pages of the report to a paginated Excel spreadsheet:

    The following sample exports the part of report associated with a named anchor:

    The following example creates a user interface for exporting a report:

    visualize({    auth: { ...    }}, function (v) {    var $select = buildControl("Export to: ", v.report.exportFormats),        $button = $("#button"),        report = v.report({            resource: "/public/Samples/Reports/5g.AccountsReport",            container: "#container",            success: function () {                button.removeAttribute("disabled");            },            error: function (error) {                console.log(error);            }        });    $button.click(function () {                console.log($select.val());                report.export({            //export options here                    outputFormat: $select.val(),            //exports all pages if not specified            //pages: "1-2"        }, function (link) {           var url = link.href ? link.href : link;           window.location.href = url;        }, function (error) {            console.log(error);        });    });    function buildControl(name, options) {        function buildOptions(options) {            var template = "<option>{value}</option>";            return options.reduce(function (memo, option) {                return memo + template.replace("{value}", option);            }, "")        }        var template = "<label>{label}</label><select>{options}</select><br>",            content = template.replace("{label}", name)                .replace("{options}", buildOptions(options));        var $control = $(content);        $control.insertBefore($("#button"));        //return select        return $($control[1]);    }});[/code]                    

    Associated HTML:

    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script><!-- Provide the URL to visualize.js --><script src="http://bi.example.com:8080/jasperserver-pro/client/visualize.js"></script><button id="button" disabled>Export</button><!-- Provide a container for the report --><div id="container"></div>[/code]                    

    Exporting Data From a Report

    You can also request the raw data of the report in CSV or JSON format.

    The following example shows how to export data in CSV format. CSV output is plain text that you must parse to extract the values that you need.:

    The following example shows how to export data in JSON format. By its nature, JSON format can be used directly as data within your JavaScript.

    Refreshing a Report

    JavaScript Example:

    visualize({    auth: { ...    }}, function (v) {        var alwasyRefresh = false;        var report = v.report({        //skip report running during initialization        runImmediately: !alwasyRefresh,        resource: "/public/viz/usersReport",        container: "#container1",     });        if (alwasyRefresh){        report.refresh();    }        $("button").click(function(){           report            .refresh()            .done(function(){console.log("Report Refreshed!");})            .fail(function(){alert("Report Refresh Failed!");});    });   });[/code]                    

    Associated HTML:

    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script><script src="http://bi.example.com:8080/jasperserver-pro/client/visualize.js"></script><button>Refresh</button><div id="container1"></div>[/code]                    

    Canceling Report Execution

    To stop a running report, call its cancel function:

    The following example is more complete and creates a UI for a spinner and cancel button for a long-running report.

    var spinner = createSpinner();visualize({    auth: { ...    }}, function (v) {       var button = $("button");        var report = v.report({        resource: "/public/Reports/Slow_Report",        container: "#container",        events: {            changeTotalPages : function(){               spinner.remove();             }        }    });    button.click(function () {        report            .cancel()            .then(function () {                spinner.remove();                 alert("Report Canceled!");            })            .fail(function () {                alert("Can't Cancel Report");            });    });});function createSpinner() {    var opts = {        lines: 17, length: 3, width: 2, radius: 3, corners: 0.6, rotate: 0, direction: 1,        color: '#000', speed: 1, trail: 60, shadow: false, hwaccel: false, zIndex: 2e9,        top: 'auto', left: 'auto', className: 'spinner'    };    var container = $("#spinner");    var spinner = new Spinner(opts).spin(container[0]);    return container;}[/code]                    

    Associated HTML:

    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script><script src="http://fgnass.github.io/spin.js/spin.js"></script><script src="http://bi.example.com:8080/jasperserver-pro/client/visualize.js"></script><div id="spinner"></div><button>Cancel</button><div id="container"></div>[/code]                    

    Discovering Available Charts and Formats

    You can write code to discover and display the types of charts and export formats that can be specified. The following example reads the exportFormats, chart.types, and table.column.types of the given report and dynamically creates a selection dialog for each:

    visualize({    auth: {        name: "jasperadmin",        password: "jasperadmin",        organization: "organization_1"    }}, function (v) {        buildControl("Report export formats", v.report.exportFormats);    buildControl("Chart types", v.report.chart.types);     buildControl("Report table column types", v.report.table.column.types);});function buildControl(name, options) {        function buildOptions(options) {            var template = "<option>{value}</option>";            return options.reduce(function (memo, option) {                return memo + template.replace("{value}", option);            }, "")        }        console.log(options);        if (!options.length){        console.log(options);    }    var template = "<label>{label}</label><select>{options}</select><br>",        content = template.replace("{label}", name)                .replace("{options}", buildOptions(options));    $("#container").append($(content));}[/code]                        


    User Feedback

    Recommended Comments

    There are no comments to display.



    Guest
    This is now closed for further comments

×
×
  • Create New...