Click here to Skip to main content
15,886,757 members
Articles / Web Development / HTML5

HTML to PDF in ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.42/5 (6 votes)
8 Mar 2015CPOL2 min read 83.4K   26   26
This post is about conversion of HTML to PDF in ASP.NET using a free third party library (nReco htmltopdf) and exe (wkhtmltopdf).

In this post, I am going to show you how can we easily import HTML into PDF in ASP.NET without compromising UI. I was looking for an alternative of Crystal reports in ASp.NET 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, I did some research for libraries for these file formats. Most programming folks were recommending 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 details, 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.

Requirements

  • Same PDF page as it's 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 ASP.NET solution at the end of source code.

Example code is as given below:

C#
/// <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 is as given below:

C#
/// <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>            " +
        "</tr>");
    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 asp.net</th>  " +
            "<th style=\"width: 100px; text-align: left;
            text-align: center;\">4 out of 10</th>            " +
        "</tr>");
    }
    html.Append("</tbody></html>");
    return html.ToString();
}

Create Page number on every page with count.

C#
private string CreatePDFScript()
        {
            return "<html><head><style>td,th{line-height:20px;} 
            tr { page-break-inside: avoid }</style><script>function subst() 
            {var vars={};var x=document.location.search.substring(1).split('&');
            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()\">";
        }

The below image is a snap of the source code. You can download the sample ASP.NET solution here.

ClassStructure

Image 2

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
My name is Muhammad Hussain. I'm a Software Engineer.
blog

Comments and Discussions

 
QuestionCannot generate PDF: (exit code: -1073741819 Pin
akimba13-Sep-17 22:31
akimba13-Sep-17 22:31 
AnswerRe: Cannot generate PDF: (exit code: -1073741819 Pin
HarvinderSyan13-Oct-17 11:25
HarvinderSyan13-Oct-17 11:25 
QuestionNreco Generates wkhtmltopdf.exe Pin
raju@shekhar19-Dec-16 6:12
raju@shekhar19-Dec-16 6:12 
QuestionJavaScript code is not running Pin
Akshay Belure14-Jul-16 23:04
Akshay Belure14-Jul-16 23:04 
QuestionPage Width Pin
Member 123585516-Apr-16 0:39
Member 123585516-Apr-16 0:39 
QuestionRunning Jquery or Angular.js in Nreco Pin
Kerim Özgiray21-Dec-15 22:32
Kerim Özgiray21-Dec-15 22:32 
QuestionDeploying on 32bit OS Pin
Josée Loubier25-Nov-15 5:09
Josée Loubier25-Nov-15 5:09 
AnswerRe: Deploying on 32bit OS Pin
M.Hussain.4-Dec-15 13:31
M.Hussain.4-Dec-15 13:31 
GeneralRe: Deploying on 32bit OS Pin
Member 114486455-May-16 9:43
Member 114486455-May-16 9:43 
QuestionHeader issue Pin
Member 1173857027-Sep-15 20:46
Member 1173857027-Sep-15 20:46 
AnswerRe: Header issue Pin
M.Hussain.4-Dec-15 13:39
M.Hussain.4-Dec-15 13:39 
GeneralNice article Pin
Shivkumar12j23-Jun-15 3:42
Shivkumar12j23-Jun-15 3:42 
QuestionNot generating proper PDF for Hindi or any other unicode font Pin
sanchat16-Jun-15 0:14
sanchat16-Jun-15 0:14 
AnswerRe: Not generating proper PDF for Hindi or any other unicode font Pin
M.Hussain.25-Aug-15 15:51
M.Hussain.25-Aug-15 15:51 
QuestionNot working on Server Pin
Anil K Verma27-May-15 19:01
professionalAnil K Verma27-May-15 19:01 
AnswerRe: Not working on Server Pin
Gloold4-Oct-15 22:25
Gloold4-Oct-15 22:25 
QuestionError: Failed loading page file Pin
joy201520-May-15 4:50
joy201520-May-15 4:50 
AnswerRe: Error: Failed loading page file Pin
M.Hussain.3-Jun-15 8:39
M.Hussain.3-Jun-15 8:39 
Questionexit code: -1073741515 Pin
vathere5-Apr-15 22:08
vathere5-Apr-15 22:08 
AnswerRe: exit code: -1073741515 Pin
M.Hussain.12-Apr-15 12:35
M.Hussain.12-Apr-15 12:35 
GeneralRe: exit code: -1073741515 Pin
Namshub12-Apr-15 23:18
Namshub12-Apr-15 23:18 
QuestionOne last thing Pin
Dewey11-Mar-15 8:30
Dewey11-Mar-15 8:30 
AnswerRe: One last thing Pin
M.Hussain.12-Apr-15 12:40
M.Hussain.12-Apr-15 12:40 
QuestionWorks fine, but please... Pin
Dewey11-Mar-15 8:16
Dewey11-Mar-15 8:16 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun8-Mar-15 20:44
Humayun Kabir Mamun8-Mar-15 20:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.