Create Blazor Document Viewer and Report Designer (WebAssembly) Application from Microsoft Template in Visual Studio
- 8 minutes to read
Tip
To create a Blazor Reporting application, use preconfigured DevExpress templates that allow you to create an application with minimal effort and maximum efficiency. For more information, review the following help topics:
Prerequisites
- .NET 6.0 or later SDK.
- Visual Studio 2022 with the ASP.NET and web development workload.
Create a New Project
This section describes how to create a new Blazor project. If you want to add DevExpress Blazor components to an existing application, go to Step 2.
Click Create a new project on Visual Studio’s start page, select the Blazor WebAssembly Standalone App template, and click Next.
Specify the project name and location, and click Next.
Select the desired framework and click Create.
Obtain Your NuGet Feed Credentials
Make sure your DevExpress account has access to Blazor UI Components. This product line is a part of Universal, DXperience, and ASP.NET subscriptions. Refer to the following page for additional information: DevExpress Subscriptions.
Use your DevExpress credentials to log into nuget.devexpress.com.
Obtain your NuGet feed credentials and copy them to the clipboard.
You can find the same URL on the Download Manager page.
Create a DevExpress NuGet Source
In Visual Studio, select Tools → NuGet Package Manager → Package Manager Settings.
Navigate to NuGet Package Manager → Package Sources. Click the plus sign at the top right corner to add a new NuGet package source. Use the following package settings:
Name:
DevExpress
Source: DevExpress NuGet Gallery (
https://nuget.devexpress.com/api
) if you use the feed key to authenticate. Otherwise, use the NuGet Feed URL (https://nuget.devexpress.com/{your feed authorization key}/api
).
Click OK.
Note
Make sure the
nuget.org
package source is also enabled.Select Tools → NuGet Package Manager → Manage NuGet Packages for Solution.
If you registered the DevExpress NuGet feed with an authorization key, the login form is displayed when you invoke the NuGet Package Manager window for the first time. Enter your credentials as follows:
- User name:
DevExpress
Password: your authorization key
- User name:
Refer to the following topic for more information: Install NuGet Packages in Visual Studio, VS Code, and Rider.
Install NuGet Packages
In the NuGet Package Manager dialog, open the Browse tab, and install the following NuGet packages:
- DevExpress.Drawing.Skia
- SkiaSharp.Views.Blazor
- SkiaSharp.NativeAssets.WebAssembly
- HarfBuzzSharp.NativeAssets.WebAssembly
- DevExpress.Blazor.Reporting.JSBasedControls
- Json data source uses the System.Text.Json processing library. Set the
DevExpress.DataAccess.Native.Json.JsonLoaderHelper.ProcessingLibrary
property toNewtonsoftJson
to use the Newtonsoft.Json library instead. Then, install the Newtonsoft.Json NuGet package.
In the Solution Explorer, right-click the project and select Edit Project File. Add the following line to the application project file:
<ItemGroup>
...
<NativeFileReference Include="$(HarfBuzzSharpStaticLibraryPath)\2.0.23\*.a" />
...
</ItemGroup>
Build the project.
Register DevExpress Resources
Register the DevExpress.Blazor namespace in the _Imports.razor file:
@using DevExpress.Blazor.Reporting @using DevExpress.Blazor
Register services required for Blazor Reporting by calling the
AddDevExpressBlazorReportingWebAssembly
method in the Program.cs file:using BlazorApp1; using Microsoft.AspNetCore.Components.Web; using Microsoft.AspNetCore.Components.WebAssembly.Hosting; using DevExpress.Blazor.Reporting; var builder = WebAssemblyHostBuilder.CreateDefault(args); builder.RootComponents.Add<App>("#app"); builder.RootComponents.Add<HeadOutlet>("head::after"); builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) }); builder.Services.AddDevExpressBlazorReportingWebAssembly(configure => { configure.UseDevelopmentMode(); }); await builder.Build().RunAsync();
Add a Document Viewer to the Page
Create a new file (DocumentViewer.razor) in the Pages folder. Use the following code snippet to generate a page with a Report Viewer component:
@page "/documentviewer" <DxDocumentViewer ReportName="TestReport"> </DxDocumentViewer>
Add a navigation link to the Shared\NavMenu.razor page:
<div class="nav-item px-3"> <NavLink class="nav-link" href="documentviewer"> <span class="oi oi-list-rich" aria-hidden="true"></span> Document Viewer </NavLink> </div>
Add a Report Designer to the Page
Create a new file (ReportDesigner.razor) in the Pages folder. Use the following code snippet to generate a page with a Report Viewer component:
@page "/reportdesigner" <DxReportDesigner ReportName="TestReport"> </DxReportDesigner>
Add a navigation link to the Shared\NavMenu.razor page:
<div class="nav-item px-3"> <NavLink class="nav-link" href="reportdesigner"> <span class="oi oi-list-rich" aria-hidden="true"></span> Report Designer </NavLink> </div>
Add Code to Load Fonts
Before the application can run in a browser, register fonts to ensure that the Skia library can use them to draw report content.
This example implements a custom service that loads fonts: FontLoader
.
Create the Services folder in the project. Create a new class file
FontLoader.cs
with the following content:using DevExpress.Drawing; public static class FontLoader { public async static Task LoadFonts(HttpClient httpClient, List<string> fontNames) { foreach(var fontName in fontNames) { var fontBytes = await httpClient.GetByteArrayAsync($"fonts/{fontName}"); DXFontRepository.Instance.AddFont(fontBytes); } } }
Add a
LoadFonts
method call to theMainLayout.razor
page:// ... @code { [Inject] HttpClient Http { get; set; } List<string> RequiredFonts = new() { "arial.ttf", "arialbd.ttf" }; protected async override Task OnInitializedAsync() { await FontLoader.LoadFonts(Http, RequiredFonts); await base.OnInitializedAsync(); } }
Copy the necessary font files (
arial.ttf
,arialbd.ttf
) to the wwwroot/fonts folder.
Add Code to Load Reports
Reporting components require a service that translates names to report instances. This example implements a custom service with the IReportProviderAsync interface to perform this task.
Add the CustomReportProvider.cs class file to the Services folder. Copy and paste the following content into the file:
using DevExpress.XtraReports.Services; using DevExpress.XtraReports.UI; public class CustomReportProvider : IReportProviderAsync { private readonly HttpClient _httpClient; public CustomReportProvider(HttpClient httpClient) { _httpClient = httpClient; } public Task<XtraReport> GetReportAsync(string id, ReportProviderContext context) { return ReportsFactory.GetReport(id, _httpClient); } }
The
ReportsFactory
class loads a report instance from a file. Add aReportsFactory.cs
class with the following code to your project:using DevExpress.XtraReports.UI; public static class ReportsFactory { public static readonly Dictionary<string, XtraReport> Reports = new() { ["EmptyReport"] = new XtraReport() }; public async static Task<XtraReport> GetReport(string reportName, HttpClient _httpClient) { var reportBytes = await _httpClient.GetByteArrayAsync($"reports/{reportName}.repx"); MemoryStream reportStream = new MemoryStream(reportBytes); return XtraReport.FromXmlStream(reportStream); } }
Register the
CustomReportProvider
service at application startup:builder.Services.AddDevExpressBlazorReportingWebAssembly(configure => { configure.UseDevelopmentMode(); }); // ... builder.Services.AddScoped<IReportProviderAsync, CustomReportProvider>(); // ... await builder.Build().RunAsync();
Create a Report
Use Microsoft Visual Studio, Visual Studio Code, or Report Designer on any supported platform to create a simple report bound to the JSON data source and save it to the TestReport.repx
file.
Use the following JSON data URI:
https://raw.githubusercontent.com/DevExpress-Examples/DataSources/master/JSON/customers.json
When prompted for the JSON connection name, type JsonConnection1
.
For more information, review the following help topics:
The following procedure shows you how to create a report in the Microsoft Visual Studio environment. To ensure that all the necessary templates are available in Visual Studio, DevExpress Reporting v24.1 must be installed before proceeding with this section.
- Press Ctrl+Shift+A or select PROJECT | Add New Item… in the main menu.
Select the DevExpress Report item and proceed to the Report Wizard to create a
TestReport
report bound to theEmployees
data source:
Upon completion, the wizard generates a TestReport.cs file and adds it to the project. Visual Studio Report Designer opens the newly created report.
Save the report to the
TestReport.repx
file:Copy the
TestReport.repx
file to the wwwroot/reports folder in your Blazor Webassembly project.
Add JSON Connection Provider
The connection string is not stored in the .repx file for security reasons. Only the connection name is saved. At runtime, the Document Viewer and Report Designer components query the CustomDataSourceWizardJsonDataConnectionStorage
service to retrieve the connection by name. Do the following to be able to use JSON connections in your application:
Add a service that implements the IDataSourceWizardJsonConnectionStorage interface. For this, add a
CustomDataSourceWizardJsonDataConnectionStorage.cs
class with the following code to your project:using DevExpress.DataAccess.Json; using DevExpress.DataAccess.Web; using DevExpress.DataAccess.Wizard.Services; public class CustomDataSourceWizardJsonDataConnectionStorage : IDataSourceWizardJsonConnectionStorage { public static JsonDataConnection GetDefaultConnection() { var uriJsonSource = new UriJsonSource() { Uri = new Uri(@"https://raw.githubusercontent.com/DevExpress-Examples/DataSources/master/JSON/customers.json"), }; return new JsonDataConnection(uriJsonSource) { StoreConnectionNameOnly = true, Name = "JsonConnection1" }; } public static List<JsonDataConnection> GetConnections() { var connections = new List<JsonDataConnection> { GetDefaultConnection() }; return connections; } bool IJsonConnectionStorageService.CanSaveConnection => false; bool IJsonConnectionStorageService.ContainsConnection(string connectionName) { return GetConnections().Any(x => x.Name == connectionName); } IEnumerable<JsonDataConnection> IJsonConnectionStorageService.GetConnections() { return GetConnections(); } JsonDataConnection IJsonDataConnectionProviderService.GetJsonDataConnection(string name) { var connection = GetConnections().FirstOrDefault(x => x.Name == name); if (connection == null) throw new InvalidOperationException(); return connection; } void IJsonConnectionStorageService.SaveConnection(string connectionName, JsonDataConnection connection, bool saveCredentials) { } }
Add a service that implements the IJsonDataConnectionProviderFactory interface:
using DevExpress.DataAccess.Json; using DevExpress.DataAccess.Web; public class CustomJsonDataConnectionProviderFactory : IJsonDataConnectionProviderFactory { public IJsonDataConnectionProviderService Create() { return new WebDocumentViewerJsonDataConnectionProvider(CustomDataSourceWizardJsonDataConnectionStorage.GetConnections()); } } public class WebDocumentViewerJsonDataConnectionProvider : IJsonDataConnectionProviderService { readonly List<JsonDataConnection> jsonDataConnections; public WebDocumentViewerJsonDataConnectionProvider(List<JsonDataConnection> jsonDataConnections) { this.jsonDataConnections = jsonDataConnections; } public JsonDataConnection GetJsonDataConnection(string name) { var connection = jsonDataConnections.FirstOrDefault(x => x.Name == name); if (connection == null) throw new InvalidOperationException(); return connection; } }
Register services at application startup:
builder.Services.AddDevExpressBlazorReportingWebAssembly(configure => { configure.UseDevelopmentMode(); }); // ... builder.Services.AddScoped<IReportProviderAsync, CustomReportProvider>(); builder.Services.AddScoped<IDataSourceWizardJsonConnectionStorage, CustomDataSourceWizardJsonDataConnectionStorage>(); builder.Services.AddScoped<IJsonDataConnectionProviderFactory, CustomJsonDataConnectionProviderFactory>(); // ... await builder.Build().RunAsync();
Result
Run the project and see the result. The Document Viewer displays a tabular report with data from the Employees
data source:
The Report Designer displays a tabular report layout bound to the Employees
data source: