Saturday, 11 June 2016

Sample code for download and view PDF Files in ASP.NET MVC


In this post we are going to see how to view or download PDF files in ASP.NET MVC, Normally in applications we have reports and files to be viewed in PDF format, sometimes we need to download the files, Now we are going to see various ways of viewing a PDF file and downloading option in MVC.

In ASP.NET MVC we have action result which is used to server the file content to the client browser,  FilePathResult is used to display the content of the PDF file in the browser.

Steps to do:
1. Create a MVC Project 
2. Create a Folder PdfFiles
3.  Place your PDF files
4. Start writing your Controller logic.

Here for View , we will do three different ways one with passing File path, another one with passing File Content, another one is embedding as inline PDF using Ajax.

Controller Logic:

HomeController

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ViewPDF.Models;

namespace ViewPDF.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            FileInfo []info = new DirectoryInfo(Server.MapPath("/PdfFiles")).GetFiles();
            return View(info.ToList());
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        public FileResult ViewPDF(string name)
        {
            return File(name, "application/pdf");
        }

        public FileResult DownloadPDF(string name)
        {
           
            byte[] pdfByte = FileContent(name);
            return File(pdfByte, "application/pdf", name.Substring(name.LastIndexOf("\\")+1));
        }

        public FileResult PDFDisplay(string name)
        {           
            byte[] pdfByte = FileContent(name);
            return File(pdfByte, "application/pdf");
        }

        public PartialViewResult PDFInlineView(string name)
        {            
            PDFModel model = new PDFModel() {FilePath = name };
            return PartialView("PDFView",model);
        }

        private  byte[] FileContent(string path)
        {            
            FileStream stream = null;           
            try
            {
                stream = System.IO.File.OpenRead(path);
                byte[] bytes = new byte[stream.Length];
                stream.Read(bytes, 0, Convert.ToInt32(stream.Length));
                return bytes;
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                    stream.Dispose();
                }
            }

        }

    }
}



create a model class to pass the model to async operation, we need a virtual path to process in async operation
 public class PDFModel
    {
        private string _virtualFilepath;

        public string FilePath {
            set {
               _virtualFilepath= "../PdfFiles/" + 
                 value.Substring(value.LastIndexOf("\\") + 1  );
            }
            get { return _virtualFilepath; }
        }
    }


HTML Logic:

index.cshtml

@using System.IO

@{
    ViewBag.Title = "Home Page";
}

@model IEnumerable<FileInfo>


<div class="panel">
   
    <table class="table table-condensed">
        <thead>
            <tr>
                <td>FileName</td>
                <td>View</td>
                <td>Download</td>
                <td>View2</td>
                <td>Inline view</td>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model)
            {


                <tr class="">
                    <td class="col-lg-1"> 
                       <label>@item.Name <span>@item.Length</span></label>
                    </td>
                    <td class="col-lg-1">
                      <button class="btn btn-info btn-sm"                                                             @Html.ActionLink("View""ViewPDF"new { name = item.FullName })
                      </button>
                   </td>
                    <td class="col-lg-1">
                      <button class="btn btn-info btn sm">
                    @Html.ActionLink("Download""DownloadPDF"new { name = item.FullName })
                      </button>
                    </td>
                    <td class="col-lg-1">
                     <button class="btn btn-info btn-sm">                                                         @Html.ActionLink("View2""PDFDisplay"new { name = item.FullName })
                     </button>
                    </td>
                    <td class="col-lg-1">
                      <button class="btn btn-info btn-sm">                                                           @Ajax.ActionLink("InlineView""PDFInlineView"
                        new { name = item.FullName }, 
                        new AjaxOptions { UpdateTargetId = "pdfInline" })
                      </button>    
                    </td>
                </tr>
            }
        </tbody>

    </ul>

   
    <div id="pdfInline">

    </div>

</div>





pdfview.cshtml

@model ViewPDF.Models.PDFModel

<h4>PDF inline View....</h4>


<object style="height:500px;width:800px" data="@Model.FilePath" type="application/pdf">
    <p>It appears that you don't have Adobe Reader or PDF support in this web browser. 
    <a href="@Model.FilePath">Click here to download the PDF</a>. Or 
    <a href="http://get.adobe.com/reader/" target="_blank">click here to install Adobe Reader</a>.
    </p>
    <embed src="@Model.FilePath" type="application/pdf" />
</object>




Output:
                                             When you click the View button it will display the PDF file in the browser.




When you click the download button it will download the PDF files





If the browser doesn't support the inline view it will display a information like below





Ajax - Async operation of Viewing PDF as Inline



From this post you can learn how to create a application to View and Download PDF files in ASP.NET MVC

No comments:

Post a Comment