DEV Community

Usman Aziz
Usman Aziz

Posted on • Updated on • Originally published at blog.groupdocs.com

Document Viewer in ASP.NET Core MVC for 140+ Document Formats

The online document viewer applications have become popular after the grown usage of digital documents, especially in the content management systems. The reason behind this popularity is you can view a multitude of document formats without purchasing or installing dedicated software programs. Considering the importance of document viewers, I thought to write an article on how to create a universal document viewer application.

This document viewer will be an ASP.NET Core MVC application and it will target the .NET Core framework. For the document rendering at the backend, we’ll use GroupDocs.Viewer for .NET API – a powerful file viewer API which supports over 140 document types including PDFWordExcelPowerPointVisioCADOutlook, and many other popular formats.

Why .NET Core?

.NET Core is a valuable addition to the .NET ecosystem by Microsoft. It makes it possible to develop cross-platform applications without any additional efforts required by the developers. This is why I have selected .NET Core to be the targetted framework.

Steps to Create Document Viewer in ASP.NET Core

1. Create a new project in Visual Studio.

2. Select .NET Core from the project types and ASP.NET Core Web Application from templates.
Alt Text

3. Select Web Application (Model-View-Controller) and click Ok button.
Alt Text

4. Install GroupDocs.Viewer from NuGet.
Alt Text

5. Open Views/Home/Index.cshtml file and replace its content with the following:

@{
    ViewData["Title"] = "Home Page";
}
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script>
    function ViewDocument(file) {
        $("#loader").fadeIn();
        var data = { FileName: file };
        $.ajax({
            type: "POST",
            url: '/Home/OnPost',
            data: data,
            dataType: "text"
        }).done(function (data) {
            var folderName = file.replace(".", "_");
            $("#content").empty();
            for (var i = 1; i <= data; i++) {
                $("#content").append("<img src='Content/" + folderName + "/page-" + i + ".png'/>");
            }
            $("#loader").fadeOut();
        })
    }
</script>
<script type="text/javascript">
    $(window).load(function () {
        $("#loader").fadeOut(1000);
    });
</script>
<div class="row">
    <div class="col-md-3">
        <div class="sidenav">
            <div id="loader"></div>
            <h2 style="padding-left:15px">Files</h2>
            @if (ViewBag.lstFiles != null)
            {
                @foreach (string file in ViewBag.lstFiles)
                {
                    <a href="#" onclick="ViewDocument('@file')">@file</a>
                }
            }
        </div>
    </div>
    <div class="col-md-9">
        <h2>Preview</h2>
        <div id="content"></div>
    </div>
</div>
Enter fullscreen mode Exit fullscreen mode

6. Open Controllers/HomeController.cs and replace the content of the class with the following code.

public class HomeController : Controller
{
    private readonly IHostingEnvironment _hostingEnvironment;
    private string projectRootPath;
    private string outputPath;
    private string storagePath;
    List<string> lstFiles; 

    public HomeController(IHostingEnvironment hostingEnvironment)
    {
        _hostingEnvironment = hostingEnvironment;
        projectRootPath = _hostingEnvironment.ContentRootPath;
        outputPath = Path.Combine(projectRootPath, "wwwroot/Content");
        storagePath = Path.Combine(projectRootPath, "storage");
        lstFiles = new List<string>(); 
    }

    public IActionResult Index()
    {
        var files = Directory.GetFiles(storagePath);
        foreach (var file in files)
        {
            lstFiles.Add(Path.GetFileName(file));
        }
        ViewBag.lstFiles = lstFiles; 
        return View();
    }
    [HttpPost]
    public IActionResult OnPost(string FileName)
    {
        int pageCount = 0;
        string imageFilesFolder = Path.Combine(outputPath, Path.GetFileName(FileName).Replace(".", "_"));
        if (!Directory.Exists(imageFilesFolder))
        {
            Directory.CreateDirectory(imageFilesFolder);
        }
        string imageFilesPath = Path.Combine(imageFilesFolder, "page-{0}.png");
        using (Viewer viewer = new Viewer(Path.Combine(storagePath, FileName)))
        {
      //Get document info
            ViewInfo info = viewer.GetViewInfo(ViewInfoOptions.ForPngView(false));
            pageCount = info.Pages.Count;
      //Set options and render document
            PngViewOptions options = new PngViewOptions(imageFilesPath);
            viewer.View(options);
        } 
        return new JsonResult(pageCount);
    } 

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
}
Enter fullscreen mode Exit fullscreen mode

7. Append the following styles in the wwwroot/css/site.css file.

.sidenav {
    width: 300px;
    position: fixed;
    z-index: 1;
    left: 0px;
    background: #eee;
    overflow-x: hidden;
    padding: 8px 0;
}
.sidenav a {
    padding: 6px 8px 6px 16px;
    text-decoration: none;
    font-size: 15px;
    color: #2196F3;
    display: block;
}
.sidenav a:hover {
        color: #064579;
    }
.main {
    margin-left: 140px; /* Same width as the sidebar + left position in px */
    font-size: 15px; /* Increased text to enable scrolling */
    padding: 0px 10px;
}
@media screen and (max-height: 450px) {
    .sidenav {
        padding-top: 15px;
    }
        .sidenav a {
            font-size: 20px;
        }
}
#loader {
    position: fixed;
    left: 0px;
    top: 0px;
    width: 100%;
    height: 100%;
    z-index: 9999;
    background: url('../../images/Loading.gif') 50% 50% no-repeat rgb(249,249,249);
}
Enter fullscreen mode Exit fullscreen mode

8. Build the application and run in your favorite browser.
Alt Text

Download

The complete source code of the application is available here in the Download section.

Cheers!

See Also

Top comments (3)

Collapse
 
barrett777 profile image
Ben Barrett

I wish I knew before I began how expensive GroupDocs is. From the tone of the beginning I thought this would be a free or cheap option

Collapse
 
gleamtech profile image
GleamTech

Hi Ben,
We also offer an ASP.NET Core Document Viewer (and Converter) named DocumentUltimate. I recommend you to give it a try; it's easier to implement and it has a reasonable price:
gleamtech.com/documentultimate

Collapse
 
usmanaziz profile image
Usman Aziz

Yes, GroupDocs.Viewer is a paid API but it is worth paying for the features it provides and the formats it supports. You can also request a temporary license: purchase.groupdocs.com/temporary-l....