Search code examples
razor.net-corechartsreportjsreport

How to add Charts in JSReport AspNetCore Razor View


I have used JsReport AspNetCore razor views to generate Excel and PDF reports. So far, Generating reports with data has not been a problem. But, now I have to include a chart in every report generated.

I tried including ChartJS to show a chart but after rendering the report the chart doesn't appear in the Excel or PDF file. I Have used Chartjs to display charts in web view. It doesn't cause any problems in web view. It's just that I call ajax to get data from API after the view has loaded. When the JsReportPipeline renders it, the API doesn't get called.

How to solve this problem? To add chart in a report using razor views.


Solution

  • This is likely because the chart pdf printing started before the chart was fully rendered.

    For this case jsreport chrome-pdf recipe provides print trigger feature which lets you postpone pdf print. To enable it from asp.net controller you can use this snipped.

    [MiddlewareFilter(typeof(JsReportPipeline))]
    public async Task<IActionResult> ChartWithPrintTrigger()
    {
        HttpContext.JsReportFeature()
            .Recipe(Recipe.ChromePdf)
            .Configure(cfg =>
            {
                cfg.Template.Chrome = new Chrome
                {
                    WaitForJS = true
                };
            });
    
        return View("Chart", new { });
    }
    

    and in your HTML invoke the trigger when the chart is painted

    var myChart = new Chart(ctx, {
        type: 'line',
        data: {
           ...
        },
        options: {
            animation: {
                onComplete: function () {             
                    window.JSREPORT_READY_TO_START = true
                }
            }
        }
    });
    

    A full example can be found here https://github.com/jsreport/jsreport-dotnet-aspnetcore

    The html-to-xlsx recipe doesn't convert charts from the source html/js to the excel. The only way to add excel with this recipe is inserting the produced excel table into prepared xlsx template that displays chart based on the inserted table.

    The documentation is here and an example here.