Skip to main content
A newer version of this page is available. .

Dockerize an Office File API Application (.NET Core)

  • 4 minutes to read

This tutorial describes how to create an ASP.NET Core Web API application with Office File API and add this application to a Docker container.

View Example: Dockerize an Office File API .NET Core Application

Prerequisites

  1. .NET Core SDK 3.1.

  2. Docker.

  3. A code editor. This tutorial uses Visual Studio Code.

  4. Postman.

Create an Application

  1. Create a folder for you project (DocumentConversionWebApi in this example) and open it in Visual Studio Code.

  2. Click View -> Terminal in Visual Studio Code’s main menu to open the integrated terminal.

  3. Use the dotnet new command to create a new Web API application:

    dotnet new webapi -o DocumentConversionWebApi
    cd DocumentConversionWebApi
    

    The image below shows the created project’s structure.

    Office_WebApi_Project_Structure

    Note

    The ASP.NET Core Web API project template contains WeatherForecast API. Delete the files WeatherForecast.cs and Controllers/WeatherForecastController.cs to remove this API from your project.

  4. Obtain your NuGet feed URL and install the DevExpress.Document.Processor NuGet package.

    Important

    You need a license for the DevExpress Office File API Subscription or DevExpress Universal Subscription to use this package in production code.

    # The -s key specifies the package source (DevExpress NuGet feed)
    dotnet add package DevExpress.Document.Processor -v 20.2.10 -s https://nuget.devexpress.com/{your-feed-authorization-key}/api
    
  5. Implement the API controller to handle HTTP requests. In the Controllers folder, create a ConvertFileController.cs file with the code below. See the PostConvertFile action method implementation. This method handles the HTTP POST request and converts uploaded files to HTML.

    using System;
    using System.IO;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    using DevExpress.Spreadsheet;
    using DevExpress.XtraRichEdit;
    using DevExpress.XtraSpreadsheet.Export;
    
    namespace DocumentConversionWebApi.Controllers {
        [Route("[controller]")]
        [ApiController]
        public class ConvertFileController : ControllerBase {
            [HttpPost]
            public async Task<IActionResult> PostConvertFile(IFormFile file) {
                if (file != null) {
                    try {
                        using (var stream = new MemoryStream()) {
                            await file.CopyToAsync(stream);
                            stream.Seek(0, SeekOrigin.Begin);
                            switch (Path.GetExtension(file.FileName)) {
                                case ".rtf":
                                case ".doc":
                                case ".docx":
                                case ".txt":
                                case ".mht":
                                case ".odt":
                                case ".xml":
                                case ".epub":
                                case ".html":
                                    return new FileStreamResult(ConvertWordDocument(stream), "text/html");
                                case ".xlsx":
                                case ".xlsm":
                                case ".xlsb":
                                case ".xls":
                                case ".xltx":
                                case ".xltm":
                                case ".xlt":
                                case ".csv":
                                    return new FileStreamResult(ConvertSpreadsheetDocument(stream), "text/html");
                            }
                        }
                    }
                    catch (Exception e) {
                        return StatusCode(500, e.Message + Environment.NewLine + e.StackTrace);
                    }
                }
                return new BadRequestResult();
            }
    
            Stream ConvertWordDocument(Stream inputStream) {
                using (RichEditDocumentServer server = new RichEditDocumentServer())
                {
                    server.LoadDocument(inputStream);
                    MemoryStream resultStream = new MemoryStream();
                    server.Options.Export.Html.EmbedImages = true;
                    server.SaveDocument(resultStream, DevExpress.XtraRichEdit.DocumentFormat.Html);
                    resultStream.Seek(0, SeekOrigin.Begin);
                    return resultStream;
                }
            }
            Stream ConvertSpreadsheetDocument(Stream inputStream) {
                using (Workbook workbook = new Workbook())
                {
                    workbook.LoadDocument(inputStream);
                    MemoryStream resultStream = new MemoryStream();
                    HtmlDocumentExporterOptions options = new HtmlDocumentExporterOptions();
                    options.EmbedImages = true;
                    options.AnchorImagesToPage = true;
                    workbook.ExportToHtml(resultStream, options);
                    resultStream.Seek(0, SeekOrigin.Begin);
                    return resultStream;
                }
            }
        }
    }
    

Create a Dockerfile

  1. Create a Dockerfile in your project folder. This file contains instructions required to build a Docker image and deploy it inside a container. Add the following commands to your Dockerfile:

    FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build-env
    WORKDIR /app
    
    # Copy the .csproj file and restore the project's dependencies
    COPY *.csproj ./
    # Specify your DevExpress NuGet feed URL to install the DevExpress.Document.Processor package
    RUN dotnet add package DevExpress.Document.Processor -s https://nuget.devexpress.com/{your-feed-authorization-key}/api
    RUN dotnet restore
    
    # Copy project files and build the application
    COPY . ./
    RUN dotnet publish -c Release -o /app/publish
    
    # Build runtime image
    FROM mcr.microsoft.com/dotnet/core/aspnet:3.1
    WORKDIR /app
    
    # Install the latest version of the libgdiplus library to use System.Drawing in the application
    RUN apt update
    RUN apt install -y libgdiplus libc6 libc6-dev
    RUN apt install -y fontconfig libharfbuzz0b libfreetype6
    
    # (Optional step) Install the ttf-mscorefonts-installer package to use Microsoft TrueType core fonts in the application
    RUN echo "deb http://ftp.debian.org/debian/ stretch contrib" >> /etc/apt/sources.list
    RUN apt-get update
    RUN apt-get install -y ttf-mscorefonts-installer  
    
    COPY --from=build-env /app/publish .
    # Define the entry point for the application
    ENTRYPOINT ["dotnet", "DocumentConversionWebApi.dll"]
    

    Note

    For applications targeting .NET 5 on MacOS, specify the DevExpress.Document.Processor package version directly:

    RUN dotnet add package DevExpress.Document.Processor -v 20.2.10 -s https://nuget.devexpress.com/{your-feed-authorization-key}/api
    
  2. Add a .dockerignore file to your project. Exclude the following folders from the build context to increase the build performance:

    bin\
    obj\
    

Build and Run the Docker Image

Use the following terminal commands to build and run your Docker image:

docker build -t documentconversionwebapi .
docker run -d -p 8080:80 documentconversionwebapi

Test the Application

Use Postman to test the created Web API application.

  1. Run Postman and create a new request. Select the POST method in the drop-down list and enter the following URL in the URL input field:

    http://localhost:8080/ConvertFile

    Office_Postman_Select_Method_Type

  2. Add a Request Body to the created POST request. Switch to the Body tab and select form-data.

    Office_Postman_Select_Body_Type

  3. Specify a key-value pair to send a file to the server.

    • Type file in the Key cell and select File in the cell’s drop-down list:

    Office_Postman_Select_Key_Type

    • Click Select Files in the Value cell and select a document you want to convert to HTML.

    Office_Postman_Select_File

  4. Click Send to upload the selected file to the server and convert it to HTML.

    Office_Postman_Send_File

  5. Click Preview to see the result.

    Office_Postman_Result