How to Create a Document Viewer in ASP.NET C#
Tags: dotnet, webdev, documentviewer, fileviewer
Published: 2019-09-05 17:05:58

If you are searching for how to create a document viewer in ASP.NET then you have landed on the right place because, in this post, I will show you how you can create a simple and generic document viewer in ASP.NET using C# by following a few steps.

It will be a generic document viewer based on [GroupDocs.Viewer for .NET](https://products.groupdocs.com/viewer/net) API that supports viewing PowerPoint presentations, Excel spreadsheet, Word processing, and PDF documents, and various popular [file formats](https://docs.groupdocs.com/display/viewernet/Supported+Document+Formats).

So let’s begin.

**Requirements**

* Visual Studio 2015 or later
* .NET 2.0 or later
* GroupDocs.Viewer for .NET v19.8 or later

**Solution’s Overview**

We are going to create the document viewer in ASP.NET Webforms with C# at the backend. The front end of the application will be created in HTML using Bootstrap for styling. In addition, AJAX calls will be used to communicate with the server-side code and GroupDocs.Viewer for .NET will be used to render the document pages into images.

**Step 1 - Create a project**

* Open Visual Studio and create a new ASP.NET Web Application project.
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/nz8owi13mmojqx8utmrv.png)
* Select Empty from the template list and click OK.
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/kbqquxmiwbyx7has76el.png)

**Step 2 - Add dependencies and folders**

* Right-click on the project in Solution Explorer and select Manage NuGet Packages.
* Search GroupDocs.Viewer and install the package.
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/xkhthselyww6kam209ep.png)
* Create 2 new folders - **output** and **storage** in the project’s root folder. The storage folder will contain the document to be viewed and the output folder will be used to save the rendered images.

**Step 3 - Write the code**

* Right-click on the project in Solution Explorer, create a new Web Form and save it as _index.aspx_.
* Add the following script inside the _head_ tag to add the Bootstrap’s CSS and the JQuery:

```javascript
<link href="Content/bootstrap.min.css" type="text/css" rel="stylesheet" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
```
* Insert the following HTML inside the _body_ tag. This HTML will create the page navigation buttons and an iframe to display the pages.

```html
<div class="navbar navbar-inverse navbar-fixed-top">
	<div class="container">
		<div class="navbar-header">
			<a class="navbar-brand" runat="server" href="~/index.aspx">Viewer</a>
		</div>
	</div>
</div>
<div class="container body-content">
	<div align="center" style="margin-top: 5%"> 
		<a href="#" id="btnPrevious" class="previous round">&#8249;</a>
	  <strong>  Page:
		<asp:Label runat="server" ID="lblCurrentPage" Text="1"></asp:Label>
		of
		<asp:Label runat="server" ID="lblTotalPages"></asp:Label></strong> 
		<a href="#" id="btnNext" class="next round">&#8250;</a>
	</div>
	<div align="center">
		<iframe src="" name="container" id="container" scrolling="no" align="center" frameborder="1"
			width="750px" height="450px" style="margin-top: 2%;  overflow: hidden;" frameborder="0"
			allowfullscreen sandbox></iframe>
	</div>
	<hr />
	<footer>
		<p>&copy; <%: DateTime.Now.Year %> - GroupDocs</p>
	</footer>
</div>
```
* Below the above-mentioned HTML, add the following JavaScript inside the _body_ tag. This JavaScript contains the functions for the next and the previous buttons as well as the AJAX call to fetch the pages.
```javascript
<script>
	$(document).ready(function () {
		// call for the first time
		Navigate(1);
		$('#btnNext').click(function () {
			var currentPage = getCurrentPageNumber();
			var totalPages = getTotalPages();
			if ((currentPage + 1) <= totalPages) {
				Navigate(currentPage + 1);
				$('#<%=lblCurrentPage.ClientID%>').html(currentPage + 1)
			}
		});
		$('#btnPrevious').click(function () {
			var currentPage = getCurrentPageNumber();
			var totalPages = getTotalPages();
			if ((currentPage - 1) >= 1) {
				Navigate(currentPage - 1);
				$('#<%=lblCurrentPage.ClientID%>').html(currentPage - 1)
			}
		});
	});
	function getCurrentPageNumber()
	{
		return parseInt($('#<%=lblCurrentPage.ClientID%>').html());            
	}
	function getTotalPages()
	{
		return parseInt($('#<%= lblTotalPages.ClientID %>').html());
	}
	function Navigate(value) {
		$.ajax({
			type: "POST",
			url: "index.aspx/GetPage",
			data: '{value: "' + value + '" }',
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function (response) {
				var $iframe = $('#container');
				$iframe.attr('src', response.d);
			},
			failure: function (response) {
				alert("Filed: " + response.d);
			}
		});
	}
</script>
```
* Open _index.aspx.cs_ and replace the code with following:
```csharp
using GroupDocs.Viewer;
using GroupDocs.Viewer.Caching;
using GroupDocs.Viewer.Options;
using GroupDocs.Viewer.Results;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
namespace DocumentViewer
{
    public partial class index : System.Web.UI.Page
    {
        static string OutputPath;
        static string DocumentName = "sample.pptx";
        static string StorageFolder;
        static string CachePath;
        static FileCache cache;
        static ViewerSettings settings;
 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // Set output directories
                OutputPath = Server.MapPath("~/output/"); 
                // Set storage folder where the source document is located
                StorageFolder = Server.MapPath("~/storage");
                // Set the cache path to keep the rendered images
                CachePath = Path.Combine(OutputPath, "cache");
                // Set cache
                cache = new FileCache(CachePath);
                settings = new ViewerSettings(cache);
                // Get document info
                GetDocumentInfo();
            }
        }
 
        private void GetDocumentInfo()
        {
            try
            {
                using (Viewer viewer = new Viewer(Path.Combine(StorageFolder, DocumentName)))
                {
                    ViewInfo info = viewer.GetViewInfo(ViewInfoOptions.ForPngView(false));  
                    lblTotalPages.Text = info.Pages.Count.ToString();
                }
 
            }
            catch
            {
                // Do something
            }
        }
 
        [System.Web.Services.WebMethod]
        public static string GetPage(string value)
        {
            int PageNumber = Convert.ToInt32(value);
            string PageFilePathFormat = Path.Combine(OutputPath, "img{0}.png");
            using (Viewer viewer = new Viewer(Path.Combine(StorageFolder, DocumentName)))
            {
                PngViewOptions options = new PngViewOptions(PageFilePathFormat);
                options.Width = 750;
                options.Height = 450; 
 
                viewer.View(options, PageNumber);
            } 
 
            return Path.Combine(@"output", string.Format("img{0}.png", PageNumber));
 
        } 
    }
}
```

**Step 4 - Build solution and run**
* Build the solution.
* View _index.aspx_ in your favorite browser.

**The Output**
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/clvj4cmwng82slj6aax6.gif)

That’s it.

You can download the complete ready-to-run source code from the [GitHub](https://github.com/usmanazizgroupdocs/document-viewer).

### You will love you read:
* [Connect to SMTP Server using Python](https://blog.aspose.com/2021/12/16/connect-to-smtp-server-using-python/)
* [Convert HTML Files to Word Document in Java](https://blog.aspose.com/2021/11/29/convert-html-to-word-in-java/)
* [Extract Images from Word Documents in Python](https://blog.aspose.com/2021/11/19/extract-images-from-word-in-python/)
* [How to Read Excel Files in Java](https://blog.aspose.com/2021/11/10/how-to-read-excel-files-in-java/)
* [How to Read Excel Files in C#](https://blog.aspose.com/2021/10/10/how-to-read-excel-files-in-csharp/)
* [Read Data in Excel Files using Python](https://blog.aspose.com/2021/12/09/read-excel-files-using-python/)



Cheers!