HTML to PDF in ASP.Net

In this post I am going to show you how can we easily import html into pdf in without compromising UI. I was looking for an alternative of crystal reports in to generate reports without any javascript burden and complexities in developing them.

As crystal reports gives you the feature to import the report into pdf or excel. So I did some research for libraries for these file formats. Most programming folks were recommending for ITextSharp.

I knew and had used ITextSharp for pdf merge in a project. But when I tried to use this for html to pdf I didn’t get the result I wanted and there were a lot of workarounds needed to get all my requirements.

So I looked for some other solutions and fortunately I found this amazing free library NReco. Which by the way is a wrapper library in .net for this wonderful html to pdf exe wkhtmltopdf.

Before going into detail I’d like to mention my requirements when I was working on html to pdf import on a project. So it would be easier for you if it matches your requirements as well.


  • Same PDF page as its showing on browser
  • Show Background-color
  • Repeat header on every page
  • Show page number on every page
  • Page number count on every page
  • Show images
  • Option to change page orientation (Landscape, Portrait)
  • Free library
  • Support css

Issues I encountered and resolved.

  • Header overlaps when repeating on other pages
  • Page number
  • deploying on 32bit OS.

I’ve attached the link of a sample solution at the end of source codes.

Example code;

/// <summary>
/// Converts html into PDF using nReco dll and wkhtmltopdf.exe.
/// </summary>        
private byte[] ConvertHtmlToPDF()
   HtmlToPdfConverter nRecohtmltoPdfObj = new HtmlToPdfConverter();
   nRecohtmltoPdfObj.Orientation = PageOrientation.Portrait;
   nRecohtmltoPdfObj.PageFooterHtml = CreatePDFFooter();
   nRecohtmltoPdfObj.CustomWkHtmlArgs = "--margin-top 35 --header-spacing 0 --margin-left 0 --margin-right 0";            
   return nRecohtmltoPdfObj.GeneratePdf(CreatePDFScript() + ShowHtml() + "</body></html>");

Html string sample;

        /// <summary>
        /// Returns HTML string.
        /// </summary>
        /// <remarks>Its test data. You can create html using data getting from database or whatever your data source.</remarks>
        /// <returns></returns>
        public string ShowHtml()
            StringBuilder html = new StringBuilder("<table id=\"tblReport\" cellspacing=\"0\" cellpadding=\"0\" style=\"border-width: 0px; border-collapse: collapse; font-family: Tahoma; font-size: 11px; table-layout: fixed; line-height: 20px;\">" +
            "<thead>" +
                "<tr style=\"background-color: #4862A3; font-family: verdana; color: white;\">" +
                    "<th style=\"width: 200px;  text-align: center;\">Name</th>           " +
                    "<th style=\"width: 150px; text-align: center;\">Date Published</th> " +
                    "<th style=\"width: 200px;  text-align: center;\">Category</th>     " +
                    "<th style=\"width: 100px; text-align: center;\">Popularity</th>     " +
                "</tr>" +
            "</thead>" +
            "<tbody>" +
                "<tr>" +
                    "<th style=\"width: 200px; text-align: left; text-align: center;\">Domain Driven Design</th>" +
                    "<th style=\"width: 150px; text-align: left; text-align: center;\">02/05/2011</th>          " +
                    "<th style=\"width: 200px; text-align: center; text-align: center;\">Design Patterns</th>   " +
                    "<th style=\"width: 100px; text-align: left; text-align: center;\">6 out of 10</th>         " +
                "</tr>" +
                "<tr>" +
                    "<th style=\"width: 200px; text-align: left; text-align: center;\">When Not to use jQuery</th> " +
                    "<th style=\"width: 150px; text-align: left; text-align: center;\">02/05/2011</th>             " +
                    "<th style=\"width: 200px; text-align: center; text-align: center;\">jQuery in ASP.Net</th>    " +
                    "<th style=\"width: 100px; text-align: left; text-align: center;\">8 out of 10</th>            " +
                "</tr>" +
                "<tr>" +
                    "<th style=\"width: 200px; text-align: left; text-align: center;\">Programmer's evolution</th> " +
                    "<th style=\"width: 150px; text-align: left; text-align: center;\">02/05/2011</th>             " +
                    "<th style=\"width: 200px; text-align: center; text-align: center;\">General Programming</th>  " +
                    "<th style=\"width: 100px; text-align: left; text-align: center;\">4 out of 10</th>            " +
            for (int i = 0; i < 150; i++)
                html.Append("<tr>" +
                    "<th style=\"width: 200px; text-align: left; text-align: center;\">Test Data</th> " +
                    "<th style=\"width: 150px; text-align: left; text-align: center;\">02/05/2011</th>             " +
                    "<th style=\"width: 200px; text-align: center; text-align: center;\">import html to pdf in</th>  " +
                    "<th style=\"width: 100px; text-align: left; text-align: center;\">4 out of 10</th>            " +
            return html.ToString();

Creat Page number on every page with count.

private string CreatePDFScript()
            return "<html><head><style>td,th{line-height:20px;} tr { page-break-inside: avoid }</style><script>function subst() {var vars={};var'&');for(var i in x) {var z=x[i].split('=',2);vars[z[0]] = unescape(z[1]);}" +
            "var x=['frompage','topage','page','webpage','section','subsection','subsubsection'];for(var i in x) {var y = document.getElementsByClassName(x[i]);" +
            "for(var j=0; j<y.length; ++j) y[j].textContent = vars[x[i]];}}</script></head><body onload=\"subst()\">";

Below image is a snap of the source code. You can download sample solution here.

Handling DBNull.Value

Every developer use DbNull.Value when writing code to communicate with database. But it could sometimes be quite painful when you want to write with a null-coalescing or ?: operator. The same would be when getting something from database and type checking.

For example in this code snippet I wrote a function which stores a comment in database. As userWebsite is an optional parameter so it could be null and if database expects null then you need to send DBNull.Value. To make it adjustable in ?: operator you just have to cast into an object. like;
Value = userWebsite != null ? userWebsite : (object)DBNull.Value.
I tested this code in fw 4.0 only, so I’m not sure about older versions.

internal int SaveComment(string name, string email, string comment, string? userWebsite)
            SqlCommand _command = new SqlCommand
                Connection = new SqlConnection { ConnectionString = "connection string" },
                CommandType = CommandType.StoredProcedure,
                CommandText = "csp_comment_save",
            _command.Parameters.AddRange(new SqlParameter[] { new SqlParameter { ParameterName = "name", Value = name, SqlDbType = SqlDbType.VarChar, Size = 100 },
            new SqlParameter { ParameterName = "email", Value = email, SqlDbType = SqlDbType.VarChar, Size = 50 },
            new SqlParameter { ParameterName = "comment", Value = comment, SqlDbType = SqlDbType.VarChar, Size = 255 },
            new SqlParameter { ParameterName = "website", Value = userWebsite != null ? userWebsite : (object)DBNull.Value, SqlDbType = SqlDbType.VarChar, Size = 20 }});
            int result=_command.ExecuteNonQuery();
            return result;

WCF RESTful service hosting on IIS6 and consuming by jQuery

Couple of days ago I needed to deploy a WCF RESTfull service on IIS6. Before then I never deployed RESTfull service on IIS6 so it came up with quite configurations for me. While I was deploying this web service on IIS6, I as usual goggled for some configuration related help, although I found, but most of the stuff were scattered. I mean I didn’t find all in a single post or a blog. So I thought why couldn’t do it.

In this post I developed a WCF RESTfull web service from scratch to hosting on web server and consuming by jQuery ajax. Here is the service contract. You’ll find UriTemplate with both with parameters and without parameter.

 /// <PostedOn></PostedOn>
    /// <PostedBy>Muhammad Hussain</PostedBy>
    [ServiceContract(Name = "DeepASPService", Namespace = "")]    
    interface IDeepASPService
        /// <summary>
        /// Returns all articles from the blog.
        /// </summary>        
        /// <returns></returns>
        [WebGet(UriTemplate = "/GetArticles?blogName={blogName}", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]        
        List<Article> GetAllArticles(string blogName);

        [WebGet(UriTemplate = "/GetTagArticles?tagName={tagName}", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
        List<Article> GetArticlesByTagName(string tagName);

        [WebGet(UriTemplate = "/GetArticle?Id={Id}", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
        Article GetArticleById(string Id);

        [WebGet(UriTemplate = "/SaveArticle?authenticationToken={authenticationToken}&amp;title={title}&amp;body={body}&amp;submittedBy={submittedBy}", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
        bool SaveArticle(string authenticationToken, string title, string body, string submittedBy);

Here is the Service implementing above contract. Most of the operations are only defined and not fully implemented as it didn’t need for this post. GetArticles operation returns a generic list in json format.

    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class DeepASPService : IDeepASPService
        public List<Article> GetAllArticles(string blogName)
            return new List<Article>()
                new Article { Id = Guid.NewGuid(), Name=blogName, Title = "WCF RESTfull web service.", Body = "Html body.", Comments=new List<Comment>()
                    new Comment { Id = Guid.NewGuid(), CommentedOn = DateTime.Now, DisplayName = "", Email="", Replies = null }
                new Article { Id = Guid.NewGuid(), Name=blogName,Title = "WCF RESTfull web service deploying on IIS 6.", Body = "Html body.", Comments=new List<Comment>()
                        new Comment { Id = Guid.NewGuid(), CommentedOn = DateTime.Now, DisplayName = "", Email="", Replies = new List<Comment> ()
                            new Comment { Id = Guid.NewGuid(), CommentedOn = DateTime.Now, DisplayName = "", Email="", Replies =null } 

        public List<Article> GetArticlesByTagName(string tagName)
            throw new NotImplementedException();

        public Article GetArticleById(string Id)
            throw new NotImplementedException();

        public bool SaveArticle(string authenticationToken, string title, string body, string submittedBy)
            if (AuthenticateRequest(authenticationToken))
                //save article 
            return true;

        private bool AuthenticateRequest(string authenticationToken)
            //authentication code
            return true;

In this sample application there are only two data contracts but you can have as many data contracts as you need.

    public class Article
        public Guid Id { get; set; }

        public string Name { get; set; }

        public string Title { get; set; }

        public string Body { get; set; }

        public List<Comment> Comments { get; set; }        
    public class Comment
        public Guid Id { get; set; }

        public string DisplayName { get; set; }

        public string Body { get; set; }

        public DateTime CommentedOn { get; set; }

        public string Email { get; set; }

        public List<Comment> Replies { get; set; }


<%@ ServiceHost Language="C#" Debug="true" Service="Namespace.ServiceName" CodeBehind="ServiceName.cs" Factory="System.ServiceModel.Activation.WebServiceHostFactory"%>



    <compilation debug="true" targetFramework="4.0" />
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
      <service name="Namespace.ServiceName" behaviorConfiguration="ServiceBehavior">
        <endpoint binding="webHttpBinding" contract="Namespace.ServiceInterface"
        <behavior name="ServiceBehavior" >
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="True"/>
        <behavior name="webHttp">
    <modules runAllManagedModulesForAllRequests="true"/>

Now we will host this service on IIS. So here is the step by step procedure;

1-Right click on website go to New

2-Click Create virtual directory(in this sample code I created a virutal directory in an existing website)

3- A wizard screen will come up like;
















4-Click Next

5-In Alias textbox give any name for your service e.g. TestRESTfullService

6-Next and browse the path where your service is e.g. wwwroot\RESTfullWCFService




Now although you have successfully deployed your service on IIS but hereafter configurations are required to run it properly.

1-Right click on the new virtual directory you created(e.g. TestRESTfullService)

2-Go to properties

3-By default this virtual directory will be shown as a website(globe logo will appear before it) so you need to convert this into an application.

4-Click on Create application button as showing at #1 in the below picture. After creating application your service icon will change from globe to gear.


















figure 2

5-Change execute permissions from None to Scripts only like the process 2 in the above picture

6- Click on Configuration button and you’ll see this screen;











7-Click on Insert and you’ll see a small screen like this;






8-Click on Browse and select aspnet_isapi.dll from C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll. If you don’t find v4.0.30319 folder and it means you don’t have dotnet framework 4 full version. So you’ll have to download it from microsoft website and install it. After installation complete you’ll find this so then select it.

9- DO NOT FORGET to uncheck “Verify that file exists” checkbox from the above screen.

10- Now click on Directory Security tab from figure 2.

11- In this Authentication Methods screen you will uncheck “Integrated windows authentication” checkbox.

12- Click OK.

13-Now go to ASP.Net tab from figure 2 and select ASP.Net version : 4.0.30313. (Sometimes a message will appear when version is changed so just press OK).

14- Now restart your IIS. It will lose all sessions of websites hosted on this server so be cautious, its better to do at night time.

14-That’s all you needed.You’ve done it !

Your WCF RESTfull service must be running

Now its time to consume your service. Here we will consume using jQuery ajax like;

function GetAllArticles() {
            var url = "/TestRESTfullService/ServiceName.svc/GetArticles?blogName=deepasp"
            $(function() {
                    type: "GET"
                    url: url,
                    async: true,
                    dataType: "json"
                    success: function(articles) {
                        if (articles != null) {
                            document.getElementById("response").innerHTML = ConvertObjecToHtml(articles);
                            document.getElementById("response").innerHTML ="No articles published yet on this blog."
                    error: function(e) {
                        alert("Error occured while processing service request" + e.responseText);

Here download the source code;

Session Variables Management

Session variables are used in our web applications quite often. Some of the variables are maintained for the whole session. So we can use them in different places to perform application’s logic. But while getting some values errors happen just because of a small silly spelling mistake and application blows up. We can somehow overcome most of the common session variables spelling mistake problems by using static classes. Because in this way you don’t need to spell each time you access.

In this post I created a static class in Web/UI layer and created properties for all those common session variables used by our application. So in this way you can set or get your session variables just using this class. It also serves you to organize your session variables in your project.
As it is only a class so I captured it in an image, but if you need source code it can be provided.

 /// <summary>
    /// Managing Session Variables
    /// </summary>
    internal static class BlogSessionVariables
        /// <summary>
        /// Gets sets UserIdentification variable.
        /// </summary>
        public static string UserIdentifier
            get { return (HttpContext.Current.Session["UserIdentification"] != null ? Convert.ToString(HttpContext.Current.Session["UserIdentification"]) : string.Empty); }
            set { HttpContext.Current.Session["UserIdentification"] = value; }

        /// <summary>
        /// Gets sets articles variable.
        /// </summary>
        public static List<dynamic> Articles
            get { return (HttpContext.Current.Session["Articles"] != null ? (List<dynamic>)HttpContext.Current.Session["Articles"] : null); }
            set { HttpContext.Current.Session["Articles"] = value; }

Click the image to enlarge so you can view the whole class and test functions.
session variable management

Pure JavaScript Autocomplete in ASP Classic

In this post I implemented auto-suggestion using pure JavaScript. Although if you wanna use jQuery autocomplete you can use it. But if you are only using for this purpose then I would recommend not to use jQuery.

Firstly they are large files which will obviously affect your application’s performance. Secondly it is little slower in DOM traversing than pure JavaScript. Thirdly you can easily change JavaScript code, as you don’t necessarily need to have high level expertise in JavaScript.
In addition to that sometimes it has browser compatibility issues as well. So always try to use more standard and basic way in your programming. At least that’s my practice.

I implemented this JavaScript Autocomplete using ASP Classic as a server side language. But you can use any other language. I tried to make it as simple as possible but you can still make it more simple because there’s always a room for better.

This is the html:

 <input type="text" id="txtSearchEngines" class="data">
 <div id="suggestionBox" style="display:none">sss</div>

CSS classes:

    position: absolute;
    border:01 gray solid;
    width: 300px;    
    font-family: Tahoma;

Here’s the JavaScript Code:

var request,xmlhttp,rowToSelect = 0,searchTextBox = document.getElementById("txtSearchEngines"),
function BindSearchTextBox(){
	searchTextBox.addEventListener("keyup", KeyUpOnSearchTextBox,false);
function KeyUpOnSearchTextBox(e){
	var suggestBox = document.getElementById("suggestionBox");
	if((e.keyCode >= 65 && e.keyCode <= 90) || (e.keyCode == 40 || e.keyCode == 38 || e.keyCode == 8) ){				
		if((e.keyCode == 40 || e.keyCode == 38 ) && != "none"){    				
			SelectSuggestedRow(e.keyCode == 40 ? 1: -1 );
			if(null != searchTextBox.value && "" != searchTextBox.value) SendAJAXRequestToServer(_URL+"?type=s&searchKey="+searchTextBox.value,ShowSuggestion,true);
			else{ HideSuggestionBox(); BindSearchTextBox();}
	else if(e.keyCode==13){searchTextBox.removeEventListener("keyup",KeyUpOnSearchTextBox); GetSelectedDetail(); }
function ShowSuggestion(){
	if (xmlhttp.readyState == 4) {
		if(xmlhttp.responseText != ""){
    		var suggestBox = document.getElementById("suggestionBox"),suggestRow=document.getElementById("suggest-rows");""; searchTextBox.offsetTop + searchTextBox.offsetHeight+ 02; searchTextBox.offsetLeft;
    		suggestBox.innerHTML = xmlhttp.responseText;   "";	
		else HideSuggestionBox();
function CloseSuggestionBox(e){
	var eObj = e || window.event;
	if("data") == -1) HideSuggestionBox();
function HandleTabKey(e){
	if(e.keyCode == 9) GetSelectedDetail();
	else if(e.keyCode == 27) HideSuggestionBox();
function HideSuggestionBox(){
	var suggestBox = document.getElementById("suggestionBox");
	suggestBox.innerHTML = null; ="none";	
function HoverOverSuggestedList(obj){UnselectRow(); rowToSelect = obj.getAttribute("rowIndex"); SelectRow();}
function SelectRow(){document.getElementById("tblSuggest").rows[rowToSelect].className = "suggest-data rowSelected";}
function SelectedRowClicked(e){GetSelectedDetail();}
function UnselectRow(){	var suggestedTable=document.getElementById("tblSuggest");if(suggestedTable != null) suggestedTable.rows[rowToSelect].className = "suggest-data";}
function SelectSuggestedRow(rowCount){
	if(rowToSelect == 0){ if(rowCount == 1) rowToSelect = rowCount;}
	else rowToSelect = rowToSelect + rowCount;
	if(rowToSelect >= document.getElementById("tblSuggest").rows.length){rowToSelect = rowToSelect - 1;SelectRow();}
	else SelectRow();
function GetSelectedDetail(){
	var suggestedTable=document.getElementById("tblSuggest");
	if(suggestedTable != null){
function SendAJAXRequestToServer(url,handler,ajax){
	xmlhttp= new XMLHttpRequest();'GET', url,ajax);
	xmlhttp.onreadystatechange = handler;

ASP Classic code to return the suggestions for the search key;

'put your security/authenciation code here
response.write GetSuggestion
public Function GetSuggestion
	'Its just a demo you can write your code to get from database.
	dim searchKey 
		searchKey = Request.QueryString("searchKey")
	if(searchKey = "g") then
		GetSuggestion = "<table border='0' cellpadding='0' cellspacing='0' width='100%' id=""tblSuggest""><tr onclick=""SelectedRowClicked(event)"" onmouseover=""HoverOverSuggestedList(this)"" name='suggest-rows' rowIndex=""0"" class='suggest-data data' ><td class=""data"" style=""display:none"">1</td><td class=""data"" align='left' class=""data"">Google</td></tr><tr onmouseover=""HoverOverSuggestedList(this)"" onclick=""SelectedRowClicked(event)"" name='suggest-rows' class='suggest-data data' rowIndex=""2""><td class=""data"" style=""display:none"">3</td><td class=""data"" align='left'>Google2</td></tr></table>"
	else if(searchKey = "b") then
		GetSuggestion = "<table border='0' cellpadding='0' cellspacing='0' width='100%' id=""tblSuggest""><tr onclick=""SelectedRowClicked(event)"" onmouseover=""HoverOverSuggestedList(this)"" name='suggest-rows' class='suggest-data data' rowIndex=""1""><td class=""data"" style=""display:none"">2</td><td class=""data"" align='left'>Bing</td></tr></table>"
	end if
	end if
end function

Instantiate Anonymous Generic List in C#

Sometimes we need anonymous objects in our day to day programming. I used anonymous types in my LINQ queries but I never instantiated an anonymous generic list, I mean I never needed to do it. But now I needed and found an easy way to do it. So if you need it you can enjoy :)

         /// <summary>
        /// Returns geo-location of cities.        
        /// </summary>
        /// <returns></returns>
        internal List<dynamic> GetCitiesGeoLocation()
            List<dynamic> cities = new List<dynamic>(){
                new { Name="Lahore", Latitude ="31.5497N", Longitude="74.3436E" },
                new { Name="London", Latitude ="51.5072N", Longitude="0.1275W" },
                new { Name ="Kansas City", Latitude ="39.0997N", Longitude ="94.5783W"}

            return cities;

Uses of Jquery Filter Selector

Jquery Filter selector becomes very handy for a geek who’s found of lambda function in LINQ. Here are some scenarios where we can easily use filter selector. Its very useful for a complex filter.
Some of the scenarios are;

  1. Dynamically setting the selected option of a dropdownlist
      $('#dropdownlistId option').filter(function() {
    return $.trim( $(this).text() ) == "Value to Compare"; })
  2. Dynamically changing the background color of a particular checked checkbox.
      $('input:checked').filter(function() { 
    return $.trim( $(this).val() ) == "Value to Compare"; })

Get every new post delivered to your Inbox.