Highlight HTML Table Alternate Rows

Sometime we have to highlight the alternate rows of html table to get the attention of user on important data. There are many ways to highlight the alternate rows but easiest way is using the CSS style selector which does not required any scripting code such as JavaScript or jQuery.

The CSS provides the nth-child() selector which supports the odd and even keyword also its supports the arithmetic operators

Syntax

:nth-child(number) {
  css declarations;
}

Use of selector

 we can use :nth-child selector as follows along with the html tags

//odd keyword
th:nth-child(odd) {
  background: red;
}
//even keyword
p:nth-child(even) {
  background: blue;
}
//arithmetic operator
p:nth-child(4n+0) {
  background: blue;
}

Example

Let's consider we have employee table and we want to highlight the alternate rows

Step 1: Create the CSS Style 

Define the following stylesheet in the head section of your HTML page using the nth-child selector for table

<style>
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td, th {
  border: 2px solid #DFFF00;
  text-align: left;
  padding: 8px;
}
tr:nth-child(even) {
  background-color: #DFFF00;
}
</style>

Step 2: Create the HTML Table

<h2>Employee</h2>

<table>
  <tr>
    <th>Name</th>
    <th>City</th>
    <th>Address</th>
  </tr>
 
 <tr>
    <td>Vithal Wadje</td>
    <td>Latur</td>
    <td>India</td>
  </tr>
   <tr>
    <td>Sudhir Wadje</td>
    <td>Pune</td>
    <td>India</td>
  </tr>
 <tr>
    <td>Vishal</td>
    <td>New York</td>
    <td>USA</td>
  </tr>
  <tr>
    <td>Kapil</td>
    <td>London</td>
    <td>UK</td>
  </tr>
</table>

The output of the above code will be look like as follows


Summary

Hope this article is useful to learn how to highlight HTML table alternate rows using the CSS, if you have any suggestion then please send using the comment box.

Convert HTML String To PDF Using Aspose.PDF API

In today's modern application reporting part is very important to fulfill the clients complicated requirements . However in today's client based technologies applications like pure HTML or ASP.NET MVC application using Reporting server such as SSRS or other is very risky in terms of performance and maintenance so the best way to deal with this problems is to make Invoice or reporting template in HTML format and convert it into the PDF or other format as per requirements with the help of Aspose.Pdf etc.
In MVC application there is often need to convert HTML to PDF format So in this article we will learn how to convert HTML to PDF using Aspose.PDF for .NET . So lets learn step by step how to achieve this task in easy way.
We will cover following points about Aspose.PDF for .NET with sample ASP.NET MVC application including
  • What is Aspose.PDF ?
  • Aspose.Pdf features.
  • Creating ASP.NET MVC application to use Aspose.PDF. 
  • Add reference of Aspose.Pdf for .NET APIs from NuGet package manager using visual studio 2015.
  • Purchase or get the temporary license of  Aspose.Pdf for .NET product.
  • Applying and how to Aspose.Pdf license in .NET project.
  • Ensuring Aspose.Pdf license is applied or not .
  • How to convert HTML to PDF using Aspose.Pdf for .NET APIs .
What is Aspose.PDF?
Aspose.Pdf for .NET is a set of PDF APIs for document creation and manipulation that enables your .NET applications to read, write and manipulate existing PDF documents without using Adobe Acrobat. It also allows you to create forms and manage form fields embedded in a PDF document.
This APIs are written in managed C# and it allows developers to add PDF Creation and manipulation functionality to their Microsoft .NET application.
Following are the some key and incredible features of Aspose.Pdf APIs.
  • PDF compression options.
  • Table creation and manipulation.
  • Support for graph objects.
  • Extensive hyperlink functionality.
  • Extended security controls.
  • custom font handling.
  • Integration with data sources.
  • Add or remove bookmarks.
  • Create table of contents.
  • Add , update , delete extract or insert pages.
  • Transform pages to image.
  • Print Pdf documents.
So lets demonstrate preceding explanation with practically by creating one simple ASP.NET MVC application
Step 1: Create an MVC Application. Now let us start with a step by step approach from the creation of a simple MVC application as in the following:
  1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
  2. "File", then "New" and click "Project", then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click OK. After clicking, the following window will appear:
 Step 2 : Add The Reference of Aspose.PDF into project
Now the next step is to add the reference of Aspose.PDF APIs into our created MVC Project. Here are the steps:
  1. Right click on Solution ,find Manage NuGet Package manager and click on it.
  2. After as shown into the image and type in search box "Aspose.PDF".
  3. Select Aspose.PDF as shown into the image .
  4. Choose version of Aspose.PDF APIs and click on install button.

After successfully installation of Aspose.PDF APIs into ASP.NET MVC project , The added reference of Aspose.PDF APIs will be look like as follows into our created MVC application solution as

In preceding image you can see that Aspose.Pdf APIs is successfully installed in our project.
Step 3: Create Model Class
Now let us create the model class file named InvoiceModel.cs by right clicking on model folder as in the following screenshot:

Note:
It is not mandatory that Model class should be in Models folder, it is just for better readability; you can create this class anywhere in the solution explorer. This can be done by creating different folder names or without folder name or in a separate class APIs .
InvoiceModel.cs class file code snippet:
using System.ComponentModel.DataAnnotations;

namespace ConvertHTMLToPDFUsingAspose.Models
{
    public class InvoiceModel
    {
        [Display(Name ="Customer Name")]
        public string CustomerName { get; set; }
        [Display(Name = "Transaction Ref.")]
        public string TransactionRef { get; set; }
        [Display(Name = "Transaction Date")]
        public string TransactionDate { get; set; }
        [Display(Name = "Transaction Amount")]
        public string TransactionAmount { get; set; }
        public string Status { get; set; }
       
    }
}
Step 4: Add Controller Class.
Now let us add the MVC 5 controller as in the following screenshot:
 After clicking on Add button it will show the window. Specify the Controller name as Home with suffix Controller.
Note:
  • Controller name must be having suffix as 'Controller' after specifying the name of controller.
Step 5: Create Method into the HomeController.cs file.
Now modify the default code in HomeController.cs class file to convert HTML to PDF using Aspose.PDF , After modifying code will look like as follows,
HomeController.cs
using Aspose.Pdf;
using ConvertHTMLToPDFUsingAspose.Models;
using System;
using System.IO;
using System.Text;
using System.Web.Mvc;

namespace ConvertHTMLToPDFUsingAspose.Controllers
{

    public class HomeController : Controller
    {           // GET: Home
        public ActionResult HTMLToPDF()
        {
            InvoiceModel Invoice = new InvoiceModel();
            Invoice.CustomerName = "Vithal Wadje";
            Invoice.TransactionDate = DateTime.Now.ToString("dd-MM-yyy");
            Invoice.TransactionRef = "CMD0152PAY";
            Invoice.TransactionAmount = "4000.00";
            Invoice.Status = "Success";
            return View(Invoice);
        }

        [HttpPost]
        public ActionResult HTMLToPDF(int? id)
        {

       //Consider this data coming from database
            InvoiceModel Obj = new InvoiceModel();
            Obj.CustomerName = "Vithal Wadje";
            Obj.TransactionDate = DateTime.Now.ToString("dd-MM-yyy");
            Obj.TransactionRef = "CMD0152PAY";
            Obj.TransactionAmount = "4000.00";
            Obj.Status = "Success";

            string PdfHtmlTemplate = @"<table border=2 width=100%"+">" +@" 
               <tbody><tr>
  
                  <td>
                      Customer Name
                  </td>
  
                  <td>
                     "+Obj.CustomerName+ @"
                  </td> 
              </tr> 
              <tr> 
                  <td>
                      Transaction Ref.  
                  </td>  
                  <td> " + Obj.TransactionRef + @" </td>
  
              </tr>
  
              <tr>
                  <td>
                      Transaction Date
                  </td>
  
                  <td> " + Obj.TransactionDate + @" </td >
  
              </tr>
  
              <tr>
  
                  <td>
                      Transaction Amount
                  </td >
  
                  <td> " + Obj.TransactionAmount + @" </td>
  
              </tr>
  
              <tr>
  
                  <td>
                      Status
                  </td>
  
                  <td> " + Obj.Status + @" </td>
  
              </tr>
  

          </tbody></table>";

            Aspose.Pdf.License Objpdflicense = new Aspose.Pdf.License();
            Objpdflicense.SetLicense(@"E:\Aspose\Aspose.Pdf.lic");
            Objpdflicense.Embedded = true;
            //Check if licensed applied
            if (Document.IsLicensed)
            {
                //Set the properties for PDF file page format         
                HtmlLoadOptions objLoadOptions = new HtmlLoadOptions();
                objLoadOptions.PageInfo.Margin.Bottom = 10;
                objLoadOptions.PageInfo.Margin.Top = 20;

                //Load HTML string into MemoryStream using Aspose document class
                Document doc = new Document(new MemoryStream(Encoding.UTF8.GetBytes(PdfHtmlTemplate)), objLoadOptions);
                string FileName = "Compilemode_" + DateTime.Now.ToString("dd-MM-yyyy")+".pdf";
                //Save PDF file on local hard drive or database or as you wish          
                doc.Save(@"E:\Saved Files\" + FileName);
            }
       
           return View(Obj);
        }

    }
}
Step 6: Create strongly typed view named HTMLToPDF using InvoiceModel class .
Right click on View folder of created application and choose add view , select InvoiceModel class and choose 'List' scaffolding template as.
 Click on Add button then it will create the view named HTMLToPDF , Now open the HTMLToPDF.cshtml view, Then some default code you will see which is generated by MVC scaffolding template, Now modify default code to make as per our requirements, After modifying the code it will look like as in the following,
HTMLToPDF.cshtml
@model ConvertHTMLToPDFUsingAspose.Models.InvoiceModel

@{
    ViewBag.Title = "www.compilemode.com";
}
@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <hr />
        <h4>Using Aspose.Pdf for .NET</h4>
        <hr />
        <table class="table-bordered table"> 
            <tr>
                <td>
                    @Html.DisplayNameFor(model => model.CustomerName)
                </td>
                <td>
                    @Html.DisplayFor(model => model.CustomerName)
                </td>
            </tr>
            <tr>
                <td>
                    @Html.DisplayNameFor(model => model.TransactionRef)
                </td>
                <td>@Html.DisplayFor(model => model.TransactionRef)</td>
            </tr>
            <tr>
                <td>
                    @Html.DisplayNameFor(model => model.TransactionDate)
                </td>
                <td>@Html.DisplayFor(model => model.TransactionDate)</td>
            </tr>
            <tr>
                <td>
                    @Html.DisplayNameFor(model => model.TransactionAmount)
                </td>
                <td>@Html.DisplayFor(model => model.TransactionAmount)</td>
            </tr>
            <tr>
                <td>
                    @Html.DisplayNameFor(model => model.Status)
                </td>
                <td>@Html.DisplayFor(model => model.Status)</td>
            </tr>
            
        </table>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Export To PDF" class="btn btn-primary" />
            </div>
        </div>
    </div>
}

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
Now after adding the Model, View and controller into our project. The solution explorer will look like as follows
 Now we have done all coding to convert HTML to PDF using Aspose.PDF in ASP.NET MVC

Step 7 : Now run the application.
After running the application the UI will be look like as follows, 

In the preceding Images , lets consider the preceding the transaction receipt which we wants to Export into PDF. Now click on Export to PDF button . It will generate the PDF file in our specified location as.

Now open the files , The contents of the file will be look like as follows


I hope from all preceding examples we have learned how to convert HTML to PDF using Aspose.PDF in ASP.NET MVC.
Note:

  • Download the Zip file of the sample application for a better understanding.
  • Since this is a demo, it might not be using proper standards, so improve it depending on your skills.
Summary
I hope this article is useful for all readers. If you have any suggestions please contact me.

Read more articles on ASP.NET MVC and ASPOSE:
Download Aspose : API To Create and Convert Files

Binding HTML Table Using Json Data In ASP.NET MVC

In this article we will learn how to bind html table using the Json (JavaScript object Notation) data in ASP.Net MVC .
So let's see,step by step
Step 1 : Create MVC application
  1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
  2. "File", then "New" and click "Project..." then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click on OK. 
  3. Choose MVC empty application option and click on OK
Step 2 : Create Model Class
Right click on Model folder in the created MVC application ,give the class name Employee or as you wish and click on OK .
Employee.cs
public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string City { get; set; }
        public string  Address { get; set; }
    }
Step 3 : Add controller class
Right click on Controller folder in the created MVC application ,give the class name Home or as you 
and click on OK
HomeControlle.cs
public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
        return View();
        }
        [HttpGet]
        public JsonResult EmpDetails()
        {
        //Creating List
            List<Employee> ObjEmp = new List<Employee>()
            {
        //Adding records to list
        new Employee {Id=1,Name="Vithal Wadje",City="Latur",Address="Kabansangvi" },
        new Employee {Id=2,Name="Sudhir Wadje",City="Mumbai",Address="Kurla" }
            };
        //return list as Json
        return Json(ObjEmp, JsonRequestBehavior.AllowGet);
        }
    }
In the above controller class JsonResult method EmpDetails  we have added the records into the Generic list. and returning it as JSON  to avoid database query for same result.
To work with JQuery we need a following JQuery library
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
The preceding JQuery library file version may be different that is lower or higher
Step 4 : Add Partial view
Right click on Home folder inside the View folder in the created MVC application as

Give the name EmpDetails and click on Add button and write the following code.
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
    $(document).ready(function () {
        //Call EmpDetails jsonResult Method
        $.getJSON("Home/EmpDetails",
        function (json) {
        var tr;
        //Append each row to html table
        for (var i = 0; i < json.length; i++) {
                tr = $('<tr/>');
                tr.append("<td>" + json[i].Id + "</td>");
                tr.append("<td>" + json[i].Name + "</td>");
                tr.append("<td>" + json[i].City + "</td>");
                tr.append("<td>" + json[i].Address + "</td>");
                $('table').append(tr);
            }
        });
    });
</script>
<table class="table table-bordered table-condensed table-hover table-striped">
        <thead>
        <tr>
        <th>Id</th>
        <th>Name</th>
        <th>City</th>
        <th>Address</th>
        </tr>
        </thead>
        <tbody></tbody>
</table>

Step 5 : Call partial view EmpDetails in Main Index view
Now call the partial view EmpDetails in Main Index view as using following code
@{
    ViewBag.Title = "www.compilemode.com";
}
<div style="margin-top:20px">
@Html.Partial("EmpDetails");
</div>
Step 6 : Run the application


From Preceding examples we have learned how to bind HTML table using JSON data in MVC.
Summary
I hope this tutorial is useful for all readers. If you have any suggestion then please comment below to the article.

Paging Searching And Sorting on HTML Table In ASP.NET MVC

Paging, Sorting , Searching is very important when you are working with huge records. In this article we will use jQuery data table library to make efficient, responsive Paging, Sorting, Searching on html table in ASP.NET MVC with json data. So let's start step by step, so it will be useful to understand from scratch.

Step 1: Create MVC application
  1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
  2. "File", then "New" and click "Project", then select "ASP.NET Web Application Template" and provide the Project a name as you wish and click on OK.
  3. Choose MVC empty application option and click OK
Step 2: Create Model Class
Right click on Model folder in the created MVC application, give the class name Employee or as you wish and click OK.
public class Employee  
    {  
        public int Id { get; set; }  
        public string Name { get; set; }  
        public string City { get; set; }  
        public string Address { get; set; }  
    }  
Step 3: Add controller class
Right click on Controller folder in the created MVC application and add the controller class as:

Now after selecting controller template, click on add button then the following window appears,



Specify the controller name and click on add button, Now open the HomeController.cs file and write the following code into the Home controller class as:
HomeController.cs
public class HomeController : Controller  
    {  
        // GET: Home  
        [HttpGet]  
        public ActionResult Index()  
        {  
            return View();  
        }  
  
        [HttpGet]  
        public JsonResult EmpDetails()  
        {  
            //Creating List      
            List<Employee> ObjEmp = new List<Employee>()  
        {    
            //Adding records to list      
            new Employee  
            {  
                Id = 1, Name = "Vithal Wadje", City = "Latur", Address = "Kabansangvi"  
            },  
            new Employee  
            {  
                Id = 2, Name = "Sudhir Wadje", City = "Mumbai", Address = "Kurla"  
            },  
             new Employee  
            {  
                Id = 3, Name = "Dinesh Beniwal", City = "New Delhi", Address = "Noida"  
            },  
               new Employee  
            {  
                Id = 4, Name = "Dhananjay Kumar", City = "New Delhi", Address = "Delhi"  
            },  
                 new Employee  
            {  
                Id = 5, Name = "Jitendra Gund", City = "Pune", Address = "Pune"  
            },  
                   new Employee  
            {  
                Id = 6, Name = "Anil Kumar", City = "chandigarh", Address = "chandigarh"  
            },  
                     new Employee  
            {  
                Id = 7, Name = "Ramesh", City = "Mumbai", Address = "Kurla"  
            },  
                       new Employee  
            {  
                Id = 8, Name = "Sachin", City = "XYZ", Address = "XYZ"  
            },  
                                    new Employee  
            {  
                Id = 9, Name = "Ravi", City = "XYZ", Address = "XYZ"  
            },  
                                                 new Employee  
            {  
                Id = 10, Name = "Kapil", City = "XYZ", Address = "XYZ"  
            },  
                                                              new Employee  
            {  
                Id = 11, Name = "Vivek", City = "XYZ", Address = "XYZ"  
            }  
        };  
            //return Json      
            return Json(ObjEmp, JsonRequestBehavior.AllowGet);  
        }  
    }  
In the above controller class JsonResult method EmpDetails we have added the records into the Generic list and returning it as JSON to avoid database query for same result.
To work with JQuery we need the following or any higher version JQuery library,
<script src="~/Scripts/jquery-1.10.2.min.js"></script>  
Step 4: Add Partial view
Right click on Home folder inside the View folder in the created MVC application as:

 
Give the name Index, click on Add button and write the following code.
<script src="~/Scripts/jquery-1.10.2.min.js"></script>    
<script>    
    $(document).ready(function () {    
        //Call EmpDetails jsonResult Method    
        $.getJSON("Home/EmpDetails",    
        function (json) {    
        var tr;    
        //Append each row to html table    
        for (var i = 0; i < json.length; i++) {    
                tr = $('<tr/>');    
                tr.append("<td>" + json[i].Id + "</td>");    
                tr.append("<td>" + json[i].Name + "</td>");    
                tr.append("<td>" + json[i].City + "</td>");    
                tr.append("<td>" + json[i].Address + "</td>");    
                $('table').append(tr);    
            }    
        });    
    });    
</script>    
<table class="table table-bordered table-condensed table-hover table-striped">    
        <thead>    
        <tr>    
        <th>Id</th>    
        <th>Name</th>    
        <th>City</th>    
        <th>Address</th>    
        </tr>    
        </thead>    
        <tbody></tbody>    
</table>    
Step 5: Run the application
After running the application the output will be as in the following screenshot without paging.

In the preceding example data came without paging, sorting and searching.
Step 6
: Enabled paging, sorting and searching using jQuery data table 
To enable the paging, sorting and searching using jQuery data table we need the jQuery data table library. There are many ways to add this library but in this article we are using CDN library which has the following CDN path,
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.10/css/jquery.dataTables.min.css">  
<script type="text/javascript" language="javascript" src="//cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js"></script>  
Now make changes into the jQuery function and add $('#EmpInfo').DataTable();  function just after the Json table binding is over, after referencing all the necessary files and code then Index.cshtml code will be as in the following,
Index.cshtml

@{  
    ViewBag.Title = "www.compilemode.com";  
}  
<script src="~/Scripts/jquery-1.10.2.min.js"></script>  
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.10/css/jquery.dataTables.min.css">  
<script type="text/javascript" language="javascript" src="//cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js"></script>  
<script>  
  
    $(document).ready(function () {  
        //Call EmpDetails jsonResult Method  
        $.getJSON("Home/EmpDetails",  
        function (json) {  
            var tr;  
  
        //Append each row to html table  
        for (var i = 0; i < json.length; i++) {  
                tr = $('<tr/>');  
                tr.append("<td>" + json[i].Id + "</td>");  
                tr.append("<td>" + json[i].Name + "</td>");  
                tr.append("<td>" + json[i].City + "</td>");  
                tr.append("<td>" + json[i].Address + "</td>");  
                $('table').append(tr);  
  
        }  
        $('#EmpInfo').DataTable();  
        });  
  
    });  
  
</script>  
<hr />  
<div class="form-horizontal">  
    <table id="EmpInfo" class="table table-bordered  table-hover">  
        <thead>  
            <tr>  
                <th>Id</th>  
                <th>Name</th>  
                <th>City</th>  
                <th>Address</th>  
            </tr>  
        </thead>  
        <tbody></tbody>  
    </table>    
  
</div>  
Now run the application output will be like the following,

Now click on Id header, It will sort the records in ascending order as in the following,

Now type any text in textbox, it will dynamically detect all column records and fetches exact result what you expected as,


Now type anything which does not exist in the above records then it will show following message in grid,

From all the above examples, I hope you have learned how to make searching, paging and sorting on html table in ASP.NET MVC with the help of jQuery data table library.
Note:
  • For the complete code, please download the sample zip file.
  • You need to use the jQuery library.
  • You need to use jQuery data table  library.
  • Since in this article we are using CDN library then you have active internet connection.

Convert HTML To PDF Using Aspose.PDF In ASP.NET MVC 5

In today's modern application reporting part is very important to fulfill the clients complicated requirements . However in today's client based technologies applications like pure HTML or ASP.NET MVC application using Reporting server such as SSRS or other is very risky in terms of performance and maintenance so the best way to deal with this problems is to make Invoice or reporting template in HTML format and convert it into the PDF or other format as per requirements with the help of Aspose.Pdf etc.

In MVC application there is often need to convert HTML to PDF format So in this article we will learn how to convert HTML to PDF using Aspose.PDF for .NET . So lets learn step by step how to achieve this task in easy way.
 
We will cover following points about Aspose.PDF for .NET with sample ASP.NET MVC application including
  • What is Aspose.PDF ?
  • Aspose.Pdf features.
  • Creating ASP.NET MVC application to use Aspose.PDF. 
  • Add reference of Aspose.Pdf for .NET APIs from NuGet package manager using visual studio 2015.
  • Purchase or get the temporary license of  Aspose.Pdf for .NET product.
  • Applying and how to Aspose.Pdf license in .NET project.
  • Ensuring Aspose.Pdf license is applied or not .
  • How to convert HTML to PDF using Aspose.Pdf for .NET APIs .

What is Aspose.PDF?

Aspose.Pdf for .NET is a set of PDF APIs for document creation and manipulation that enables your .NET applications to read, write and manipulate existing PDF documents without using Adobe Acrobat. It also allows you to create forms and manage form fields embedded in a PDF document.
This APIs are written in managed C# and it allows developers to add PDF Creation and manipulation functionality to their Microsoft .NET application.
Following are the some key and incredible features of Aspose.Pdf APIs.
  • PDF compression options.
  • Table creation and manipulation.
  • Support for graph objects.
  • Extensive hyperlink functionality.
  • Extended security controls.
  • custom font handling.
  • Integration with data sources.
  • Add or remove bookmarks.
  • Create table of contents.
  • Add , update , delete extract or insert pages.
  • Transform pages to image.
  • Print Pdf documents.
So lets demonstrate preceding explanation with practically by creating one simple ASP.NET MVC application

Step 1: Create an MVC Application. 

Now let us start with a step by step approach from the creation of a simple MVC application as in the following:
  1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
  2. "File", then "New" and click "Project", then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click OK. After clicking, the following window will appear:

 Step 2 : Add The Reference of Aspose.PDF into project

Now the next step is to add the reference of Aspose.PDF APIs into our created MVC Project. Here are the steps:
  1. Right click on Solution ,find Manage NuGet Package manager and click on it.
  2. After as shown into the image and type in search box "Aspose.PDF".
  3. Select Aspose.PDF as shown into the image .
  4. Choose version of Aspose.PDF APIs and click on install button.

After successfully installation of Aspose.PDF APIs into ASP.NET MVC project , The added reference of Aspose.PDF APIs will be look like as follows into our created MVC application solution as


In preceding image you can see that Aspose.Pdf APIs is successfully installed in our project.

Step 3: Create Model Class

Now let us create the model class file named InvoiceModel.cs by right clicking on model folder as in the following screenshot:


Note:

It is not mandatory that Model class should be in Models folder, it is just for better readability; you can create this class anywhere in the solution explorer. This can be done by creating different folder names or without folder name or in a separate class APIs .
InvoiceModel.cs class file code snippet:
using System.ComponentModel.DataAnnotations;

namespace ConvertHTMLToPDFUsingAspose.Models
{
    public class InvoiceModel
    {
        [Display(Name ="Customer Name")]
        public string CustomerName { get; set; }
        [Display(Name = "Transaction Ref.")]
        public string TransactionRef { get; set; }
        [Display(Name = "Transaction Date")]
        public string TransactionDate { get; set; }
        [Display(Name = "Transaction Amount")]
        public string TransactionAmount { get; set; }
        public string Status { get; set; }
       
    }
}

Step 4: Add Controller Class

Now let us add the MVC 5 controller as in the following screenshot:


After clicking on Add button it will show the window. Specify the Controller name as Home with suffix Controller.

Note:
  • Controller name must be having suffix as 'Controller' after specifying the name of controller.

Step 5: Create Method into the HomeController.cs file.

Now modify the default code in HomeController.cs class file to convert HTML to PDF using Aspose.PDF , After modifying code will look like as follows,

HomeController.cs
using Aspose.Pdf;
using ConvertHTMLToPDFUsingAspose.Models;
using System;
using System.IO;
using System.Text;
using System.Web.Mvc;

namespace ConvertHTMLToPDFUsingAspose.Controllers
{

    public class HomeController : Controller
    {           // GET: Home
        public ActionResult HTMLToPDF()
        {
            InvoiceModel Invoice = new InvoiceModel();
            Invoice.CustomerName = "Vithal Wadje";
            Invoice.TransactionDate = DateTime.Now.ToString("dd-MM-yyy");
            Invoice.TransactionRef = "CMD0152PAY";
            Invoice.TransactionAmount = "4000.00";
            Invoice.Status = "Success";
            return View(Invoice);
        }

        [HttpPost]
        public ActionResult HTMLToPDF(int? id)
        {

       //Consider this data coming from database
            InvoiceModel Obj = new InvoiceModel();
            Obj.CustomerName = "Vithal Wadje";
            Obj.TransactionDate = DateTime.Now.ToString("dd-MM-yyy");
            Obj.TransactionRef = "CMD0152PAY";
            Obj.TransactionAmount = "4000.00";
            Obj.Status = "Success";

            string PdfHtmlTemplate = @"<table border=2 width=100%"+">" +@" 
               <tbody><tr>
  
                  <td>
                      Customer Name
                  </td>
  
                  <td>
                     "+Obj.CustomerName+ @"
                  </td> 
              </tr> 
              <tr> 
                  <td>
                      Transaction Ref.  
                  </td>  
                  <td> " + Obj.TransactionRef + @" </td>
  
              </tr>
  
              <tr>
                  <td>
                      Transaction Date
                  </td>
  
                  <td> " + Obj.TransactionDate + @" </td >
  
              </tr>
  
              <tr>
  
                  <td>
                      Transaction Amount
                  </td >
  
                  <td> " + Obj.TransactionAmount + @" </td>
  
              </tr>
  
              <tr>
  
                  <td>
                      Status
                  </td>
  
                  <td> " + Obj.Status + @" </td>
  
              </tr>
  

          </tbody></table>";

            Aspose.Pdf.License Objpdflicense = new Aspose.Pdf.License();
            Objpdflicense.SetLicense(@"E:\Aspose\Aspose.Pdf.lic");
            Objpdflicense.Embedded = true;
            //Check if licensed applied
            if (Document.IsLicensed)
            {
                //Set the properties for PDF file page format         
                HtmlLoadOptions objLoadOptions = new HtmlLoadOptions();
                objLoadOptions.PageInfo.Margin.Bottom = 10;
                objLoadOptions.PageInfo.Margin.Top = 20;

                //Load HTML string into MemoryStream using Aspose document class
                Document doc = new Document(new MemoryStream(Encoding.UTF8.GetBytes(PdfHtmlTemplate)), objLoadOptions);
                string FileName = "Compilemode_" + DateTime.Now.ToString("dd-MM-yyyy")+".pdf";
                //Save PDF file on local hard drive or database or as you wish          
                doc.Save(@"E:\Saved Files\" + FileName);
            }
       
           return View(Obj);
        }

    }
}

Step 6: Create strongly typed view named HTMLToPDF using InvoiceModel class

Right click on View folder of created application and choose add view , select InvoiceModel class and choose 'List' scaffolding template as.

Click on Add button then it will create the view named HTMLToPDF , Now open the HTMLToPDF.cshtml view, Then some default code you will see which is generated by MVC scaffolding template, Now modify default code to make as per our requirements, After modifying the code it will look like as in the following,

HTMLToPDF.cshtml
@model ConvertHTMLToPDFUsingAspose.Models.InvoiceModel

@{
    ViewBag.Title = "www.compilemode.com";
}
@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <hr />
        <h4>Using Aspose.Pdf for .NET</h4>
        <hr />
        <table class="table-bordered table"> 
            <tr>
                <td>
                    @Html.DisplayNameFor(model => model.CustomerName)
                </td>
                <td>
                    @Html.DisplayFor(model => model.CustomerName)
                </td>
            </tr>
            <tr>
                <td>
                    @Html.DisplayNameFor(model => model.TransactionRef)
                </td>
                <td>@Html.DisplayFor(model => model.TransactionRef)</td>
            </tr>
            <tr>
                <td>
                    @Html.DisplayNameFor(model => model.TransactionDate)
                </td>
                <td>@Html.DisplayFor(model => model.TransactionDate)</td>
            </tr>
            <tr>
                <td>
                    @Html.DisplayNameFor(model => model.TransactionAmount)
                </td>
                <td>@Html.DisplayFor(model => model.TransactionAmount)</td>
            </tr>
            <tr>
                <td>
                    @Html.DisplayNameFor(model => model.Status)
                </td>
                <td>@Html.DisplayFor(model => model.Status)</td>
            </tr>
            
        </table>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Export To PDF" class="btn btn-primary" />
            </div>
        </div>
    </div>
}

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
Now after adding the Model, View and controller into our project. The solution explorer will look like as follows
 Now we have done all coding to convert HTML to PDF using Aspose.PDF in ASP.NET MVC

Step 7 : Now run the application.

After running the application the UI will be look like as follows, 

In the preceding Images , lets consider the preceding the transaction receipt which we wants to Export into PDF. Now click on Export to PDF button . It will generate the PDF file in our specified location as.

Now open the files , The contents of the file will be look like as follows


I hope from all preceding examples we have learned how to convert HTML to PDF using Aspose.PDF in ASP.NET MVC.
Note:
  • Since this is a demo, it might not be using proper standards, so improve it depending on your skills.

Summary

I hope this article is useful for all readers. If you have any suggestions please contact me.

Read more articles on ASP.NET MVC and ASPOSE:

www.CodeNirvana.in

Protected by Copyscape
Copyright © Compilemode