DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Usman Aziz
Usman Aziz

Posted on • Updated on

How to Create a Document Viewer in ASP.NET C#

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 API that supports viewing PowerPoint presentations, Excel spreadsheet, Word processing, and PDF documents, and various popular file 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
  • Select Empty from the template list and click OK. Alt Text

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
  • 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:
<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>
Enter fullscreen mode Exit fullscreen mode
  • Insert the following HTML inside the body tag. This HTML will create the page navigation buttons and an iframe to display the pages.
<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>
Enter fullscreen mode Exit fullscreen mode
  • 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.
<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>
Enter fullscreen mode Exit fullscreen mode
  • Open index.aspx.cs and replace the code with following:
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));

        } 
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 4 - Build solution and run

  • Build the solution.
  • View index.aspx in your favorite browser.

The Output
Alt Text

That’s it.

You can download the complete ready-to-run source code from the GitHub.

You will love you read:

Cheers!

Top comments (1)

Collapse
 
keizzmann profile image
The_KeizzmannπŸ˜πŸŽΉπŸŽΉπŸ’»

Nice work

Please can you recommend a curriculum for asp.net webforms for beginners

Super Useful CSS Resources

A collection of 70 hand-picked, web-based tools which are actually useful.
Each will generate pure CSS without the need for JS or any external libraries.