Live Chat Icon For mobile
Live Chat Icon

How to Use Report Viewer with Syncfusion Blazor Components

Banner Image

Howdy! As you know, in a real-time scenario, a web application contains not only information but also various business analytics reports and modern UI components. In this blog, we are going to create a real-time sales tracker application in Blazor with all of these elements.

With our Bold Reports Embedded platform, you can easily embed reporting components in your project to create, bind data to, view, and export pixel-perfect, paginated reports.

Syncfusion Blazor is our comprehensive, lightweight, and responsive native Blazor UI components for the web. These components can be easily included in your web applications.

The web application we’re making in this blog includes the Report Viewer from Bold Reports and a couple of Syncfusion Blazor components.

Prerequisites

Create a Blazor server application

  1. Open Visual Studio 2019 and click Create a new project.
  2. Select Blazor App and then click Next.
  3. Change the project name to BlazorSalesTracker and select the Blazor Server App template.
  4. Click Create to initialize the project.
Blazor Server Application
Blazor Server Application

Initialize the Syncfusion Blazor components

In this section, we are going to initialize the Syncfusion Blazor components in the previously created Blazor server application.

NuGet package

Install the following NuGet packages to render Blazor components.

Package Purpose
Syncfusion.Blazor Supports 50+ UI components.

Initialize Syncfusion Blazor Components

For this blog, I have integrated the Sidebar and Accordion components from the Syncfusion Blazor UI library. You can use any of the components from the Syncfusion Blazor suite in your application. Refer to the documentation to learn more.

Blazor Server Application with Syncfusion Blazor Controls
Blazor Server Application with Syncfusion Blazor Components

Integration of Report Viewer component

Let’s initialize the Report Viewer in the previously created Blazor application, which already has the two Syncfusion Blazor components.

NuGet packages

Install the following NuGet packages in the created Blazor application. These are used for processing the RDL reports.

Package Purpose
BoldReports.Net.Core Creates web API service to process reports.
System.Data.SqlClient This should be referenced in the project when the RDL report renders visual data from a SQL Server or SQL Azure data source based on the RDL design. The package version should be higher than 4.1.0.
Microsoft.AspNetCore.Mvc.NewtonsoftJson ASP.NET Core MVC features that use Newtonsoft.Json. Includes input and output formats for JSON and JSON Patch. The package version should be higher than 3.1.2.

Compatibility

We are using both the Syncfusion Blazor and Bold Reports components in a single application, so we need to use compatibility themes to avoid UI conflicts. For more information, refer to the documentation.

CSS

<link rel=”stylesheet” href=”https://cdn.syncfusion.com/ej2/styles/compatibility/material.css” />

<link href=”https://cdn.boldreports.com/2.3.39/content/bold.widgets.core.compatibility.min.css”   rel=”stylesheet” />

<link href=”https://cdn.boldreports.com/2.3.39/content/material/bold.theme.compatibility.min.css”   rel=”stylesheet” />

Create reporting controller

This is where the reports are processed for rendering.

  • Create an empty API controller by right-clicking the Data folder, selecting Add –> Controller, and then naming it BoldReportsAPIController.cs.
Create Empty Controller
Create Empty Controller
  • Include your already created .rdl or .rdlc reports in the path wwwroot\Resources\. Here we have used a sales-order-detail.rdl report, which can be downloaded here. You can also add reports from the Bold Reports installation location (C:\Users\Public\Documents\Bold Reports\Embedded Reporting Tools\Samples\ASP.NET\Resources\Report). For more information, refer to the samples and demos section of the Bold Reports documentation.
  • Replace the following code in BoldReportsAPIController.cs. To learn more about the controller actions, refer to the documentation ReportViewer service.
using BoldReports.Web.ReportViewer;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using System.Collections.Generic;

namespace BlazorReportingTools.Data
{
    [Route("api/{controller}/{action}/{id?}")]
    [ApiController]
    public class BoldReportsAPIController : ControllerBase, IReportController
    {
        // Report Viewer requires a memory cache to store the information of consecutive client requests and
        // the rendered Report Viewer in the server.
        private IMemoryCache _cache;

        // IHostingEnvironment used with sample to get the application data from wwwroot.
        private IWebHostEnvironment _hostingEnvironment;

        public BoldReportsAPIController(IMemoryCache memoryCache, IWebHostEnvironment hostingEnvironment)
        {
            _cache = memoryCache;
            _hostingEnvironment = hostingEnvironment;
        }
        //Get action for getting resources from the report
        [ActionName("GetResource")]
        [AcceptVerbs("GET")]
        // Method will be called from Report Viewer client to get the image src for Image report item.
        public object GetResource(ReportResource resource)
        {
            return ReportHelper.GetResource(resource, this, _cache);
        }

        // Method will be called to initialize the report information to load the report with ReportHelper for processing.
        public void OnInitReportOptions(ReportViewerOptions reportOption)
        {
            string basePath = _hostingEnvironment.WebRootPath;
            // Here, we have loaded the sales-order-detail.rdl report from the application folder wwwroot\Resources. sales-order-detail.rdl should be in the wwwroot\Resources application folder.
            System.IO.FileStream reportStream = new System.IO.FileStream(basePath + @"\resources\" + reportOption.ReportModel.ReportPath + ".rdl", System.IO.FileMode.Open, System.IO.FileAccess.Read);
            reportOption.ReportModel.Stream = reportStream;
        }

        // Method will be called when report is loaded internally to start the layout process with ReportHelper.
        public void OnReportLoaded(ReportViewerOptions reportOption)
        {
        }

        [HttpPost]
        public object PostFormReportAction()
        {
            return ReportHelper.ProcessReport(null, this, _cache);
        }

        // Post action to process the report from the server based on json parameters and send the result back to the client.
        [HttpPost]
        public object PostReportAction([FromBody] Dictionary<string, object> jsonArray)
        {
            return ReportHelper.ProcessReport(jsonArray, this, this._cache);
        }
    }

}
  • To request the report processing unit properly, we changed the router API attribute to include the controller and action names using [Route(“api/{controller}/{action}/{id?}”)].
  • To invoke this web API with the controller and action, include that information in the endPoint routing in the Startup.cs file.
app.UseEndpoints(endpoints =>
{
  endpoints.MapControllers();
  endpoints.MapBlazorHub();
  endpoints.MapFallbackToPage("/_Host");
});
  • Bold Reports processes the data between client and server using Newtonsoft.Json. Since we need to enable the Newtonsoft.Json features in our Blazor application, we need to include the following code section in the Startup.cs file’s ConfigureServices method.
public void ConfigureServices(IServiceCollection services)
{
      services.AddRazorPages();
      services.AddServerSideBlazor();
      services.AddSyncfusionBlazor();
      services.AddControllers().AddNewtonsoftJson();
}

Initialize the Report Viewer

In this section, we are going to integrate Bold Reports JavaScript components by creating an interop file to initialize the Report Viewer with basic parameters.

  • Create a Data/BoldReportOptions.cs class with the following code to hold the RDL report rendering properties.

[Data/BoldReportOptions.cs]

namespace BlazorReportingTools.Data
{
    public class BoldReportViewerOptions
    {
        public string ReportName { get; set; }
        public string ServiceURL { get; set; }
    }
}
  • Create a boldreports-interop.js file inside the wwwroot/scripts folder and use the following code snippet to invoke the Bold Report Viewer JavaScript component.
// Interop file to render the Bold Report Viewer component with properties.
window.BoldReports = {
    RenderViewer: function (elementID, reportViewerOptions) {
        $("#" + elementID).boldReportViewer({
            reportPath: reportViewerOptions.reportName,
            reportServiceUrl: reportViewerOptions.serviceURL            
        });
    }
}

Scripts order

As discussed in the compatibility section, we are using both Bold Reports and Syncfusion Blazor components, so we need to follow a certain order of script and stylesheet references to properly render the components in  ./Pages/_Host.cshtml. Refer to the documentation for the orders of script and stylesheet references.

<link rel="stylesheet" href="https://cdn.syncfusion.com/ej2/styles/compatibility/material.css" />
@* BoldReports Styles *@
<link href="https://cdn.boldreports.com/2.3.39/content/bold.widgets.core.material.compatibility.min.css" rel="stylesheet" />
<link href="https://cdn.boldreports.com/2.3.39/content/material/bold.theme.compatibility.min.css" rel="stylesheet" />

<link href="css/site.css" rel="stylesheet" />

@*Dependent scripts*@
<script src="https://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js" type="text/javascript"></script>
<script src="https://cdn.syncfusion.com/js/assets/external/jsrender.min.js"></script>

@* Syncfusion Essential JS 2 Scripts *@
<script src="https://cdn.syncfusion.com/blazor/18.3.40/syncfusion-blazor.min.js"></script>

@* BoldReports Scripts *@
<script src="https://cdn.boldreports.com/2.3.39/scripts/common/bold.reports.common.min.js"></script>
<script src="https://cdn.boldreports.com/2.3.39/scripts/common/bold.reports.widgets.min.js"></script>

<!--Used to render the chart item. Add this script only if your report contains the chart report item.-->
<script src="https://cdn.boldreports.com/2.3.39/scripts/data-visualization/ej.chart.min.js"></script>

<!-- Report Viewer component script-->
<script src="https://cdn.boldreports.com/2.3.39/scripts/bold.report-viewer.min.js"></script>

<!-- Blazor interop file -->
<script src="~/scripts/boldreports-interop.js"></script>

Manual Script Reference

To use the manual scripts in the application, register the Syncfusion Blazor service in Startup.cs by enabling true for services.AddSyncfusionBlazor().

public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
....
....
services.AddSyncfusionBlazor(true);
}
}

Initialize Razor page and inject IJSRuntime

  • Create an empty Razor page: Pages/Report.razor
  • Inject IJSRuntime and invoke this JavaScript interop with the sales-order-detail.rdl report and the created BoldReportsAPI URL in the Pages/Report.razor file to visualize the report using our viewer.

[Pages/Report.razor]

@page "/ReportViewer"

@using Microsoft.JSInterop
@using Microsoft.AspNetCore.Components
@inject IJSRuntime JSRuntime
@using BlazorReportingTools.Data;
@code {
    // ReportViewer options
    BoldReportViewerOptions viewerOptions = new BoldReportViewerOptions();

    // Used to render the Bold Report Viewer component in Blazor page.
    public async void RenderReportViewer()
    {
        viewerOptions.ReportName = "sales-order-detail";
        viewerOptions.ServiceURL = "/api/BoldReportsAPI";
        await JSRuntime.InvokeVoidAsync("BoldReports.RenderViewer", "report-viewer", viewerOptions);
    }
    // Initial rendering of Bold Report Viewer
    protected override void OnAfterRender(bool firstRender)
    {
        RenderReportViewer();
    }
}
  • Finally, include the navigation to the ‘Report’ view page(./Pages/Report.razor) in the sidebar(./Shared/MainLayout.razor).
@using Syncfusion.Blazor.Navigations
@inherits LayoutComponentBase

<div id="wrapper">
<div class="col-lg-12 col-sm-12 col-md-12">
...
...
<SfSidebar Width="300px" EnableGestures="true">
<ChildContent>
<div class="sidebar-header header-cover">
...
...
</div>
<div class="main-menu">
<div>
<SfAccordion>
<AccordionItems>
<AccordionItem Header="Activity Stream">
...
...
</AccordionItem>

<AccordionItem Header="Report Viewer">
<ContentTemplate>
<SfAccordion>
<AccordionItems>
<NavLink href="/ReportViewer">
<AccordionItem Header="Sales Report"></AccordionItem>
</NavLink>
</AccordionItems>
</SfAccordion>
</ContentTemplate>
</AccordionItem>
</AccordionItems>
</SfAccordion>
</div>
</div>
</ChildContent>
</SfSidebar>
<div class="sidebar-content">
@Body
</div>
</div>
</div>

Run the application

Build and run the project by pressing F5 or by clicking the start button. The application will be launched in the default system browser and the output will look like the following report.

Sales Report rendered with Syncfusion Blazor Controls
Sales Report Rendered with Syncfusion Blazor Components

You can also export the report in PDF, Excel, Word, HTML, PowerPoint, XML, and CSV formats. To learn more about all the options available in the Report Viewer, refer to our documentation.

Conclusion

In this blog, we learned how to use the Bold Reports Report Viewer component with a web application containing Syncfusion Blazor components. To explore further, I recommend you check our sample reports and documentation. You can also download the Blazor Server application we created from GitHub.

If you have any questions, please post them in the comments section below. You can also contact us through our contact page or, if you already have an account, you can log in to submit your support question. Feel free to check out the Bold Reports Embedded demos and documentation to explore the available tools and their various customization features.

Bold Reports now comes with a 15-day free trial with no credit card information required. We welcome you to start a free trial and experience Bold Reports for yourself. Give it a try and let us know what you think!

Stay tuned to our official TwitterFacebookLinkedInPinterest, and Instagram pages for announcements about new releases.

Leave a Reply