Document Viewer Capabilities in ASP.NET Core 7.0

Introduction

In this article, we are going to cover how to implement Document Viewer in Asp.Net Core 7.0 application using visual studio community 2022. 

What is GroupDocs.Viewer ?

GroupDocs.Viewer is a document viewing and rendering library developed by GroupDocs, a company that specializes in providing .NET and Java APIs for document manipulation and conversion. GroupDocs.Viewer is designed to help developers integrate document viewing capabilities into their applications, allowing users to view various types of documents directly within the application's interface without needing to download or open them with external software.

  • Let's start the building of the document viewer.
  • import the bootstrap 5 cdn in _Layout.html.

Install the GroupDocs.Viewer from Nuget Package.

  1. Create a new ASP.NET CORE MVC project.
  2. Name the project: DocumentViewer.Application.
  3. Create a new controller in DocumentViewer.Application project.
public class DocViewerController : Controller
{
    private readonly IHostingEnvironment _hostingEnvironment;
    private string projectRootPath;
    private string outputPath;
    private string storagePath;
    List<string> lstFiles;

    public DocViewerController(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);
    }
}

At the heart of this code is a method marked with the [HttpPost] attribute, which indicates that it responds to HTTP POST requests. The method takes a parameter called FileName, representing the name of the uploaded file. The method returns an IActionResult, allowing various types of responses to be returned, such as JSON, views, or redirects.

The code begins by preparing a folder to store the generated PNG images. The folder's name is constructed based on the FileName parameter, with any dots in the filename replaced by underscores. If the folder does not already exist, the code creates it using the Directory.CreateDirectory method.

using block is used to create a Viewer object by combining the storage path and the FileName parameter. This Viewer object is used to work with the document file.

A PngViewOptions object is created and configured with the imageFilesPath pattern for saving images. The viewer's View method is then called with the created options. This step actually renders the document's pages as PNG images and saves them to the specified folder.

the method returns a JSON response containing the pageCount variable, which represents the total number of pages in the document. This JSON response can be used by the client or caller to access this information.

Now create an Index.cshtml.

we are using Ajax call in this index.cshtml.

@{
}


<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: '/DocViewer/OnPost',
            data: data,
            dataType: "text"
        }).done(function (data) {
            var folderName = file.replace(".", "_");
            $("#content").empty();
            for (var i = 1; i <= data; i++) {
                $("#content").append("<img class='img-fluid' src='Content/" + folderName + "/page-" + i + ".png'/>");

            }
            $("#loader").fadeOut();
        })
    }
</script>
<script type="text/javascript">
    $(window).load(function () {
        $("#loader").fadeOut(1000);
    });
</script>
<div class="container">
    <div class="row">
        <div class="col-md-3">
            <div class="sidenav bg-light p-3">
                <div id="loader"></div>
                <h2 class="ps-3">Files</h2>
                @if (ViewBag.lstFiles != null)
                {
                    @foreach (string file in ViewBag.lstFiles)
                    {
                        <a href="#" onclick="ViewDocument('@file')" class="d-block">@file</a>
                    }
                }
            </div>
        </div>
        <div class="col-md-9">
            <h2>Preview</h2>
            <div id="content" class="border p-3"></div>
        </div>
    </div>
</div>

Output:

Image preview

 

Document file preview

Conclusion

GroupDocs.Viewer is a software development tool that provides APIs and libraries for viewing and rendering various types of documents and files within applications. It allows developers to integrate document viewing capabilities into their applications without the need for the users to install the native applications that created those documents. The tool supports a wide range of document formats, including PDF, Microsoft Office (Word, Excel, PowerPoint), images, AutoCAD files, and more.


Similar Articles