Document Viewer in ASP.NET Core MVC for 140+ Document Formats
Tags: webdev, dotnet, csharp
Published: 2019-11-21 07:38:59

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**](https://docs.microsoft.com/en-us/aspnet/core/mvc/overview?view=aspnetcore-2.0) application and it will target the [**.NET Core**](https://en.wikipedia.org/wiki/.NET_Core) framework. For the document rendering at the backend, we’ll use [**GroupDocs.Viewer for .NET**](https://blog.groupdocs.com/category/viewer/) API – a powerful [**file viewer**](https://en.wikipedia.org/wiki/File_viewer) API which supports over 140 document types including **PDF**, **Word**, **Excel**, **PowerPoint**, **Visio**, **CAD**, **Outlook**, 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](https://thepracticaldev.s3.amazonaws.com/i/a3396ngyjxdhn273ru7m.png)

**3.** Select **Web Application (Model-View-Controller)** and click Ok button.
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/478cnwmgwaz1unxp839a.png)

**4.** Install **GroupDocs.Viewer** from NuGet.
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/ukq206f42hevadq6xwrz.png)

**5.** Open **Views/Home/Index.cshtml** file and replace its content with the following:
```html
@{
    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>
```

**6.** Open **Controllers/HomeController.cs** and replace the content of the class with the following code.
```csharp
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 });
	}
}
```
**7.** Append the following styles in the **wwwroot/css/site.css** file.
```css
.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);
}
```

**8.** Build the application and run in your favorite browser.
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/c7xugrlywxrkwueoqcz2.gif)

### Download
The complete source code of the application is available [here](https://blog.groupdocs.com/2019/11/21/document-viewer-in-asp-net-core-mvc-csharp/) in the Download section.

Cheers!

## See Also
* [Create and Edit PowerPoint Files in ASP.NET](https://blog.aspose.com/2021/09/09/create-edit-powerpoint-files-in-asp-net/)
* [Generate Thumbnails for Presentations in Java](Generate Thumbnails for PowerPoint PPTX or PPT using Java)
* [Create SmartArt in PowerPoint Presentations using C#](https://blog.aspose.com/2021/09/22/create-smartart-in-powerpoint-using-csharp/)
* [Convert PowerPoint Presentations to SVG in Java](https://blog.aspose.com/2021/07/22/convert-powerpoint-to-svg-in-java/)