Products Technologies Demo Docs Blog Support Company

This blog post contains outdated information.

The cited code snippets may be workarounds, and be part of the official API in the meantime.

Using the Document Viewer in a Blazor Server App with .NET 8

This article shows how to use the Document Viewer in a Blazor Server application with .NET 8. The Document Viewer is a powerful, web-based document viewer that can be easily integrated into any Blazor application.

Using the Document Viewer in a Blazor Server App with .NET 8

Creating a Razor component using Interop JavaScript integrates and initializes the TX Text Control Document Viewer in Blazor. This sample uses the JSRuntime and DotNetObjectReference classes to communicate between the viewer and the server-side ServerTextControl class in .NET code.

Due to the many changes in .NET 8, applications built with TX Text Control in Blazor require some modifications compared to older .NET versions. Before .NET 8, the entire Blazor application ran in either Blazor WASM or Blazor Server. NET 8 allows you to control the rendering mode by component. This is a big advantage because you can now use the TX Text Control, which requires server-side rendering, with WASM applications.

There are 4 render modes available for .NET 8 components:

  • Static server-side
    Requests are routed to a Razor Component which returns static HTML.
  • Interactive Server
    Components are more interactive when run through Blazor Server. Interactive DOM modification is dynamic.
  • Interactive WASM
    The component will be executed on the client side (in the browser) and not on the server side.
  • Interactive Auto
    The component uses the Blazor Server for the initial request and then uses the Blazor WASM for subsequent requests.

TX Text Control requires server-side rendering and an update after creation, so this example uses Interactive Server mode.

Data Flow

An illustration of the data flow in this concept is shown in the diagram below. By initializing it with JavaScript, the Text Control Razor component dynamically adds the TX Text Control Document Viewer to the page. The JSRuntime is used to create an object reference to the created JavaScript file. The JavaScript API of the TX Text Control is invoked by this object reference.

TX Text Control in Blazor

Creating the Application

Make sure that you downloaded the latest version of Visual Studio 2022 that comes with the .NET 8 SDK.

  1. In Visual Studio 2022, create a new project by choosing Create a new project.

  2. Select Blazor Web App as the project template and confirm with Next.

    Creating the .NET 8 project

  3. Choose a name for your project and confirm with Next.

  4. In the next dialog, choose .NET 8 (Long-term support) as the Framework. Select Server as the Interactive render mode and choose Per page/component as the Interactivity location. Confirm with Create.

    Creating the .NET 8 project

Adding the NuGet Package

  1. In the Solution Explorer, select your created project and choose Manage NuGet Packages... from the Project main menu.

    Package Source

    Select either Text Control Offline Packages or nuget.org as the Package source. Packages in the official Text Control NuGet profile are frequently updated.

    Browse and install the following packages:

    • TXTextControl.Web.DocumentViewer
    • TXTextControl.TextControl.ASP.SDK

    ASP.NET Core Web Application

Configure the Application

  1. Open the Program.cs file located in the project's root folder.

    Before the var app = builder.Build(); entry, insert the following code:

    builder.Services.AddControllers();

    Before the app.Run(); line, insert the following code:

    app.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");

Creating the Interop JavaScript

  1. Create a new folder scripts in your wwwroot folder, create a new JavaScript file and name it txdocumentviewer.js. Paste the following content into the file you have just created.

    var dotNetObject;
    
    export function loadDocument(document, name) {
            // load the document back into the editor (TXTextControl)
            TXDocumentViewer.loadDocument(document, name);
    };

Creating the Razor Component

This step creates a new Razor component named TXDocumentViewer.razor that initializes both the .NET object reference and the JavaScript object reference.

  1. Select the project in the Solution Explorer and choose New Item... from the Project main menu. Select Razor Component, name it TXDocumentViewer.razor and confirm with Add.

  2. Paste the following code into the newly created file:

    @using Microsoft.AspNetCore.Components.Web
    @using Microsoft.JSInterop
    @inject IJSRuntime JsRuntime
    @inject NavigationManager Navigator
    
    <script src="@(BasePath)TextControl/GetResource?Resource=minimized.tx-viewer.min.js"></script>
    <script src="@(BasePath)TextControl/GetResource?Resource=minimized.tx-viewer-component.min.js"></script>
    
    <tx-document-viewer
            id="viewer1"
            settings='{"documentData":"VGV4dCBDb250cm9s", "dock":1, "basePath":"@(BasePath?.TrimEnd('/'))"}'>
    </tx-document-viewer>
    
    @code
    {
            [Parameter]
            public string? BasePath { get; set; }
    
            private DotNetObjectReference<TXDocumentViewer> DotNetReference => DotNetObjectReference.Create(this);
            private IJSObjectReference? _txdocumentviewer;
    
            protected override async Task OnAfterRenderAsync(bool firstRender)
            {
                    if (firstRender)
                    {
                            _txdocumentviewer = await JsRuntime.InvokeAsync<IJSObjectReference>("import", "./scripts/txdocumentviewer.js");
                    }
            }
    
            [JSInvokable("LoadDocumentFromFile")]
            public void LoadDocumentFromFile(string filename)
            {
                    // check if the file exists
                    if (!System.IO.File.Exists(filename))
                    {
                            return;
                    }
    
                    // load the file into a byte array
                    byte[] bDocument = System.IO.File.ReadAllBytes(filename);
    
                    // invoke the JS function 'loadDocument' to load back to the modified document
                    _txdocumentviewer?.InvokeVoidAsync("loadDocument", new object[] { Convert.ToBase64String(bDocument), filename });
            }
    
    }

Any function of the referenced txdocumentviewer.js JavaScript file can be called using the created IJSObjectReference _txdocumentviewer. The DotNetObjectReference<TXDocumentViewer> points to this Razor component. This is passed to the JavaScript functions to save and reload the document.

Consuming the TXDocumentViewer Razor Component

In this step, we are going to use the Razor component we have created on a page.

  1. Find the Home.razor page in the Pages folder and replace the content with the following code:

    @page "/"
    @rendermode InteractiveServer
    
    @inject NavigationManager Navigator;
    
    <div style="width: 800px; height: 600px;">
            <TXDocumentViewer 
                    BasePath=@Navigator.BaseUri
                    @ref="_txdocumentviewer">
            </TXDocumentViewer>
    </div>
    
    <button @onclick="LoadDocment">Load Document</button>
    
    @code {
            private TXDocumentViewer? _txdocumentviewer;
    
            // insert a table using the client-side API
            private void LoadDocment()
            {
                    _txdocumentviewer?.LoadDocumentFromFile("App_Data/demo.tx");
            }
    }
  2. Select the project in the Solution Explorer and choose New Folder from the Project main menu. Name it App_Data and copy the following file into it:

    demo.tx

    In the Solution Explorer, set the Copy to Output Directory property to Copy always.

Compile and start the application.

Text Control in Blazor Server

Button: Loading a Document

The LoadDocument() method is called in the .NET code of Home.razor when the button is clicked.

private void LoadDocment()
{
  _txdocumentviewer?.LoadDocumentFromFile("App_Data/demo.tx");
}

This calls the LoadDocumentFromFile() method of the TXDocumentViewer.Razor component where a server-side file is loaded into a byte array.

[JSInvokable("LoadDocumentFromFile")]
public void LoadDocumentFromFile(string filename)
{
        // check if the file exists
        if (!System.IO.File.Exists(filename))
        {
                return;
        }

        // load the file into a byte array
        byte[] bDocument = System.IO.File.ReadAllBytes(filename);

        // invoke the JS function 'loadDocument' to load back to the modified document
        _txdocumentviewer?.InvokeVoidAsync("loadDocument", new object[] { Convert.ToBase64String(bDocument), filename });
}

This calls the JavaScript function loadDocument() in the txdocumentviewer.js JavaScript file:

export function loadDocument(document, name) {
        // load the document back into the editor (TXTextControl)
        TXDocumentViewer.loadDocument(document, name);
};

Text Control in Blazor Server

For your own testing, you can download and try this sample from our GitHub repository.

Stay in the loop!

Subscribe to the newsletter to receive the latest updates.

GitHub

Download and Fork This Sample on GitHub

We proudly host our sample code on github.com/TextControl.

Please fork and contribute.

Download ZIP

Open on GitHub

Open in Visual Studio

Requirements for this sample

  • TX Text Control .NET Server 32.0 SP2 or better
  • Visual Studio 2022

Related Posts

ASP.NETBlazorDocument Viewer

Handling Electronic Signatures in a Blazor Web App using .NET 8

This article shows how to create a Blazor Web App that uses the TX Text Control Document Viewer to display documents and how to handle electronic signatures using the TX Text Control signature API.


AngularASP.NETBlazor

Building an ASP.NET Core Backend (Linux and Windows) for the Document Editor…

This article shows how to create a backend for the Document Editor and Viewer using ASP.NET Core. The backend can be hosted on Windows and Linux and can be used in Blazor, Angular, JavaScript, and…


ASP.NETBlazorASP.NET Core

TX Text Control Document Editor and Viewer for Blazor Released

We are very happy to announce the immediate availability of TX Text Control packages for Blazor. This article gives an overview of the available packages and how to use them.


ASP.NETBlazorASP.NET Core

Getting Started: Document Viewer for Blazor in ASP.NET Core

This article shows how to integrate the Document Viewer for Blazor into an ASP.NET Core application running on Windows and Linux. The Document Viewer is a powerful and flexible component to…


ASP.NETBlazorASP.NET Core

Announcing Our Work on a Blazor Component for Document Editing and Viewing

We are pleased to announce our work on a Blazor document editing and viewing component. This component will be part of our upcoming release and will provide an easy upgrade path from Web Forms to…