In this article I will explain with an example, how to upload and display PDF files from Database inside View in ASP.Net MVC.
This article will also illustrate how to insert PDF file in SQL Server Database Table in ASP.Net MVC.
The PDF File will be displayed in Browser using the PDF.js JavaScript plugin.
 
 
PDF.js plugin
The PDF file will be displayed (rendered) in Browser using PDF.js JavaScript plugin.
The following files of PDF.js JavaScript plugin will be used.
1. pdf_viewer.min.css
2. pdf.min.js
3. pdf.worker.min.js
 
 
Database

Display PDF files from Database in View in ASP.Net MVC

This article makes use of a table named tblFiles whose schema is defined as follows.
Note: You can download the database table SQL by clicking the download link below.
          Download SQL file
 
 
Namespaces
You will need to import the following namespaces.
using System.IO;
using System.Configuration;
using System.Data.SqlClient;
using System.Collections.Generic;
 
 
Model
The following Model class consists of the following properties needed for inserting and populating the records of the Files from database.
public class FileModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string ContentType { get; set; }
    public byte[] Data { get; set; }
}
 
 
Controller
The Controller consists of three Action methods.
Action method for handling GET operation
Inside this Action method, the GetFiles method is called.
Inside the GetFiles method, the records from the tblFiles table are fetched using DataReader and generic list of FileModel class objects is populated.
Finally, the generic list of FileModel class objects is returned to the View.
 
Action method for handling POST operation for uploading Files
This Action method gets called when a File is selected and the Upload Button is clicked, and it gets the uploaded file in the HttpPostedFileBase parameter.
Note: In case the HttpPostedFileBase parameter is appearing NULL, then please refer the article, ASP.Net MVC: HttpPostedFileBase always returns NULL.
 
The uploaded file is converted to an Array of Bytes using BinaryReader class and finally is inserted into the database table.
After successful insert of the File, the GetFiles method is called and the generic list of FileModel class objects is returned to the View.
 
Action method for sending Binary File from Database to jQuery AJAX function
When the View Link inside the HTML Table (Grid) is clicked, then the ID of the particular file is sent to this Action method and using the File ID, the File’s binary data is fetched from the database.
Note: The following Action method performs File display and hence the return type is set to JsonResult.
 
Note: Here files are being downloaded using AJAX and file size can be large, hence the MaxJsonLength value needs to be set to the Maximum value. For more details, please refer my article ASP.Net MVC Error: The length of the string exceeds the value set on the maxJsonLength property.
 
Finally, JSON is returned back to the jQuery AJAX function.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View(GetFiles());
    }
 
    [HttpPost]
    public ActionResult Index(HttpPostedFileBase postedFile)
    {
        byte[] bytes;
        using (BinaryReader br = new BinaryReader(postedFile.InputStream))
        {
            bytes = br.ReadBytes(postedFile.ContentLength);
        }
        string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            string query = "INSERT INTO tblFiles VALUES (@Name, @ContentType, @Data)";
            using (SqlCommand cmd = new SqlCommand(query))
            {
                cmd.Connection = con;
                cmd.Parameters.AddWithValue("@Name", Path.GetFileName(postedFile.FileName));
                cmd.Parameters.AddWithValue("@ContentType", postedFile.ContentType);
                cmd.Parameters.AddWithValue("@Data", bytes);
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }
 
        return View(GetFiles());
    }
 
    [HttpPost]
    public JsonResult GetPDF(int fileId)
    {
        byte[] bytes;
        string fileName, contentType;
        string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "SELECT Name, Data, ContentType FROM tblFiles WHERE Id=@Id";
                cmd.Parameters.AddWithValue("@Id", fileId);
                cmd.Connection = con;
                con.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    sdr.Read();
                    bytes = (byte[])sdr["Data"];
                    contentType = sdr["ContentType"].ToString();
                    fileName = sdr["Name"].ToString();
                }
                con.Close();
            }
        }
        JsonResult jsonResult = Json(new { FileName = fileName, ContentType = contentType, Data = bytes });
        jsonResult.MaxJsonLength = int.MaxValue;
 
        return jsonResult;
    }
 
    private static List<FileModel> GetFiles()
    {
        List<FileModel> files = new List<FileModel>();
        string constr = ConfigurationManager.ConnectionStrings["Constring"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT Id, Name FROM tblFiles"))
            {
                cmd.Connection = con;
                con.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        files.Add(new FileModel
                        {
                            Id = Convert.ToInt32(sdr["Id"]),
                            Name = sdr["Name"].ToString()
                        });
                    }
                }
                con.Close();
            }
        }
        return files;
    }
}
 
 
View
Inside the View, in the very first line the FileModel class is declared as IEnumerable which specifies that it will be available as a Collection.
The View consists of an HTML Form which has been created using the Html.BeginForm method with the following parameters.
ActionName – Name of the Action. In this case the name is Index.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
 
Form for Uploading the File
This Form consists of an HTML FileUpload and a Submit Button.
When the Submit Button is clicked, the Index Action method for handling POST operation will be called.
 
Displaying the PDF Files
For displaying the files, an HTML Table is used. A loop will be executed over the Model which will generate the HTML Table rows with the File records.
 
PDF.js JavaScript Implementation
First, the JavaScript and CSS files are inherited for the PDF.js JavaScript plugin.
When the View Anchor Link is clicked, the FileId is fetched from the rel attribute and then a jQuery AJAX call is made to the Controller’s Action Method.
Inside the Success event handler of the jQuery AJAX function, the Binary Data of the PDF file is fetched and passed to the LoadPdfFromBlobfunction.
Inside the LoadPdfFromBlob function, first the count of the pages of the PDF are read and then a loop is executed and the RenderPage function is called for each PDF page.
Inside the RenderPage function, a HTML5 Canvas element is created and the PDF page is rendered on the HTML5 Canvas.
@model IEnumerable<Display_PDF_Database_MVC.Models.FileModel>
 
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <style type="text/css">
        body { font-family: Arial; font-size: 10pt; }
        table { border: 1px solid #ccc; border-collapse: collapse; }
        table th { background-color: #F7F7F7; color: #333; font-weight: bold; }
        table th, table td { padding: 5px; border: 1px solid #ccc; }
        #pdf_container { background: #ccc; text-align: center; display: none; padding: 5px; height: 820px; overflow: auto; }
    </style>
</head>
<body>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        <input type="file" name="postedFile" />
        <input type="submit" id="btnUpload" value="Upload" />
    }
    <hr/>
    <table id="tblFiles" cellpadding="0" cellspacing="0">
        <tr>
            <th style="width:120px">File Name</th>
            <th style="width:80px"></th>
        </tr>
        @foreach (var file in Model)
        {
            <tr>
                <td>@file.Name</td>
                <td><a class="view" href="javascript:;" rel='@file.Id'>View PDF</a></td>
            </tr>
        }
    </table>
    <hr/>
    <div id="pdf_container"></div>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.6.347/pdf.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.6.347/pdf_viewer.min.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript">
        $(function () {
            $("[id*=tblFiles] .view").click(function () {
                var fileId = $(this).attr("rel");
                $.ajax({
                    type: "POST",
                    url: "/Home/GetPDF",
                    data: "{fileId: " + fileId + "}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (r) {
                        LoadPdfFromBlob(r.Data);
                    }
                });
            });
        });
 
        var pdfjsLib = window['pdfjs-dist/build/pdf'];
        pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.6.347/pdf.worker.min.js';
        var pdfDoc = null;
        var scale = 1; //Set Scale for zooming PDF.
        var resolution = 1; //Set Resolution to Adjust PDF clarity.
 
        function LoadPdfFromBlob(blob) {
            //Read PDF from BLOB.
            pdfjsLib.getDocument({ data: blob }).promise.then(function (pdfDoc_) {
                pdfDoc = pdfDoc_;
 
                //Reference the Container DIV.
                var pdf_container = document.getElementById("pdf_container");
                pdf_container.innerHTML = "";
                pdf_container.style.display = "block";
 
                //Loop and render all pages.
                for (var i = 1; i <= pdfDoc.numPages; i++) {
                    RenderPage(pdf_container, i);
                }
            });
        };
        function RenderPage(pdf_container, num) {
            pdfDoc.getPage(num).then(function (page) {
                //Create Canvas element and append to the Container DIV.
                var canvas = document.createElement('canvas');
                canvas.id = 'pdf-' + num;
                ctx = canvas.getContext('2d');
                pdf_container.appendChild(canvas);
 
                //Create and add empty DIV to add SPACE between pages.
                var spacer = document.createElement("div");
                spacer.style.height = "20px";
                pdf_container.appendChild(spacer);
 
                //Set the Canvas dimensions using ViewPort and Scale.
                var viewport = page.getViewport({ scale: scale });
                canvas.height = resolution * viewport.height;
                canvas.width = resolution * viewport.width;
 
                //Render the PDF page.
                var renderContext = {
                    canvasContext: ctx,
                    viewport: viewport,
                    transform: [resolution, 0, 0, resolution, 0, 0]
                };
 
                page.render(renderContext);
            });
        };
    </script>
</body>
</html>
 
 
Screenshot

Display PDF files from Database in View in ASP.Net MVC

 
 
Browser Compatibility

The above code has been tested in the following browsers only in versions that support HTML5.

Internet Explorer  FireFox  Chrome  Safari  Opera 

* All browser logos displayed above are property of their respective owners.

 
 
Downloads