Office File API – How to Convert Documents (DOCX, XLSX, PDF) within Your Blazor Server Apps

Office-Inspired Products
06 August 2020

As you may already know, our Office File API allows you to read, edit and print rich-text documents, spreadsheets, and PDF files inside your .NET solutions.

This post will explain how to use our Office File API (v19.2 and higher) within server-side Blazor apps. To help demonstrate what’s possible, we’ll create a simple Blazor Server application and use our File API to convert Excel and Word documents to PDF.

Prerequisites

Step 1: Create a Blazor Server App

Create a new project in Visual Studio and select the Blazor App template.

Specify project name and location. In the next window, select Blazor Server App and click Create.

Install the DevExpress Document Processor NuGet Package

Visit nuget.devexpress.com to obtain the DevExpress NuGet feed URL. Register your feed URL as a package source in the NuGet Package Manager and install the DevExpress.Document.Processor package.

If you are new to NuGet Packages, please refer to the following installation guide: Install NuGet Packages.

Step 2: Use the DevExpress Office File API to Convert Documents to PDF

  1. Open the _Imports.razor file and add the following namespaces:

    @using DevExpress.XtraRichEdit
    @using DevExpress.Spreadsheet
  2. Create a new Files folder within your project. This folder will store the documents to be converted.

  3. Open the Index.razor file. Create two buttons and handle their click events. These buttons call the following methods:

    @page "/"
    
    <button class="btn btn-primary" @onclick="() => ConvertRichTextDocument(docxFile)">Export DOCX to PDF</button>
    <button class="btn btn-primary" @onclick="() => ConvertSpreadsheetDocument(xlsxFile)">Export XLSX to PDF</button>
    
    @code {
        string docxFile = "Files/FirstLook.docx";
        string xlsxFile = "Files/InvestmentPortfolio.xlsx";
    
        void ConvertRichTextDocument(string path)
        {
            RichEditDocumentServer server = new RichEditDocumentServer();
            server.LoadDocument(path);
            using (var s = new System.IO.MemoryStream())
            {
                server.ExportToPdf(s);
            }
        }
    
        void ConvertSpreadsheetDocument(string path)
        {
            Workbook workbook = new Workbook();
            workbook.LoadDocument(path);
            using (var s = new System.IO.MemoryStream())
            {
                workbook.ExportToPdf(s);
            }
        }
    }

Step 3: Download PDF Files to the Browser

In our example, we will use JavaScript interop to download PDF files on the client.

  1. Create the wwwroot/js/exportToPdf.js file with the following JavaScript function:

    function exportToPdf(filename, base64Content) {
        var link = document.createElement('a');
        link.download = filename;
        link.href = "data:application/pdf;base64," + base64Content;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
  2. Embed the script in the Pages/_Host.cshtml page before the closing </body> tag.

    <script src="js/exportToPdf.js"></script>
  3. Inject an instance of the IJSRuntime object into the Index.razor page.

    @page "/"
    @inject IJSRuntime JS
  4. Call the exportToPdf JavaScript function asynchronously within the ConvertRichTextDocument and ConvertSpreadsheetDocument methods to download generated PDF files.

    void ConvertRichTextDocument(string path)
    {
        RichEditDocumentServer server = new RichEditDocumentServer();
        server.LoadDocument(path);
        using (var s = new System.IO.MemoryStream())
        {
            server.ExportToPdf(s);
            JS.InvokeAsync<object>("exportToPdf", "docx.pdf", Convert.ToBase64String(s.ToArray()));
         }
    }
    
    void ConvertSpreadsheetDocument(string path)
    {
        Workbook workbook = new Workbook();
        workbook.LoadDocument(path);
        using (var s = new System.IO.MemoryStream())
        {
            workbook.ExportToPdf(s);
            JS.InvokeAsync<object>("exportToPdf", "xlsx.pdf", Convert.ToBase64String(s.ToArray()));
        }
    }

The Final App

Run the application and click the Export DOCX to PDF and Export XLSX to PDF buttons to generate and download PDF files.

Your Feedback Matters

As always, we welcome your feedback. Please take a moment to answer the following survey questions so we can better understand your requirements regarding use of our Office File API in Blazor.

Showcase Your Apps on DevExpress.com

Highlight your business app and share your development experiences with the DevExpress community. To include your app in our upcoming App Showcase, please forward an application screenshot to clientservices@devexpress.com and tell us which DevExpress products you currently use within your organization.
4 comment(s)
Sven Glöckner 1
Sven Glöckner

Thanks for this update. 

However we're using a different approach for downloading files - I'd like to describe:

  • Create Web API controller in your Blazor server-side App
  • Create a method to return FileContentResult, example:​
	... using memory stream to read file ..
return File(ms.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "MyExcelFile.xlsx");
  • Create simple html anchor link to download file:
<a class="btn btn-sm btn-secondary" target="_blank" href="api/Export/@(nameof(MyWebApiController.DownloadFile))">Download File</a>

This way, we don't need JS Interop as it can be very cumbersome concerning big files. 

6 August 2020
Gosha
Gosha

Sven,

good point!

6 August 2020
Jacek Kosiński
Jacek Kosiński
can you prepare example how to run this in docker?
6 August 2020
Alex B.G. (DevExpress)
Alex B.G. (DevExpress)

@Jacek Kosiński
Thank you for your idea. We will prepare an example with docker, Bla
zor and Office file API as we get closer to our v20.2 release.

On a side note: If you have not had the chance to read the following article, I’d definitely suggest it:  Dockerize an Office File API Application (.NET Core). This article describes a WebAPI application, but it contains steps that will be common to a Blazor server application (sections “Create a Dockerfile” and “Build and Run the Docker Image”).

 

8 August 2020

Please login or register to post comments.