Click here to Skip to main content
15,501,079 members
Articles / Web Development / ASP.NET
Posted 26 Sep 2011


179 bookmarked

PDF reporting using ASP.NET MVC3

Rate me:
Please Sign up or sign in to vote.
4.83/5 (72 votes)
5 Aug 2012CPOL8 min read
A description and solution for creating PDF reports using ASP.NET MVC3.




Almost every web application (that I have built) needs some kind of reporting. Many times the client wants to generate a PDF report that corresponds with the web page he or she is viewing. Using iTextSharp, a free C# PDF library, this is possible. This article describes and includes a solution for creating reports using iTextSharp and ASP.NET MVC3.


iTextSharp is a free C# PDF library that is ported from the Java-PDF library iText. iText was launched in 2000 and is a popular Open Source Java library for programmatic creation and manipulation of PDF. As with many successful Open-Source Java libraries, it was ported to C# under the name iTextSharp. iTextSharp has been under development since 2008 and is distributed under the GNU Affero General Public License version 3.

At its core, iTextSharp is an API to manipulate PDF creation. For a recent project, I was looking for a solution that would enable me to create PDF documents from existing HTML documents or Views used in an ASP.NET MVC3 project. The optimal solution for me would be to throw an existing ASP.NET MVC3 view at it and let it generate a PDF that is exactly the same as the HTML rendered by a browser.

The solution described here uses the HTMLWorker class from iTextSharp to generate a PDF from an HTML view. HTMLWorker is an iTextSharp class that is able to parse an HTML document and generate a PDF using what is called the SimpleParser of iTextSharp. Notice the name SimpleParser which indicates that not all HTML elements and CSS styles are supported. However, I was able to get good results using this solution.

To add reporting to your ASP.NET MVC3 project, first add the PDFReportGenerator project to your solution and add the iTextSharp.dll binary to your solution. PDFReportGenerator needs a reference to the binary. By adding the binary to the solution, you are able to build the project directly from source control. Check the demo source for an example.

Creating a report

Follow these steps to generate an actual report from your web application:

  1. Create a controller that derives from PdfViewController.
  2. Create a view that generates the HTML which should be translated to a PDF report.
  3. Create an action on a controller which calls the ViewPDF method on the PdfViewController.
  4. Create a link to trigger the action on the controller.

Below, these steps are described in more detail.

Create a controller that derives from PdfViewController

Create a new or reuse an existing controller and let it derive from PdfViewController from the PdfReportGenerator project. This enables your controller to call the ViewPDF method of the PDFViewController which generates the actual PDF. In the demo project, this is the HomeController.

Create a view that generates the HTML

Create a view that should be translated to a report. This could be an existing view or a new view specially for reporting. I usually create a new view as it lets me control the HTML markup for the report. As stated earlier, the report generator does not support all the HTML markup. In the demo project, this is the PrintDemo view.

Below, the PrintDemo view from the demo project is shown. As can be seen, this is just a simple ASP.NET Razor view with a table and some rows. It uses a strongly typed model but that is not necessary. A tip when trying to design your report is to add borders to your table or div. Using these borders, when looking at the generated PDF, you can clearly see the start and end of the areas of your report.

@using MvcReportGeneratorDemo.Models
@model CustomerList
<br />
<table cellpadding="3" cellspacing="3">
    <tr border="1" bgcolor="#777777" color="#ffffff">
    @foreach (Customer customer in Model)
        <tr border="1">

Create an action which calls the ViewPDF method

The PdfViewController class from which your controller derives contains a ViewPDF method. This method has the following signature:

protected ActionResult ViewPdf(string pageTitle, string viewName, object model)


  • pageTitle
    • Type: System.String
    • The title of the report which appears on the header of the page.
  • viewName
    • Type: System.String
    • The name of the view which should be converted to a report.
  • model
    • Type: System.Object
    • The model that is rendered by the view.

This methods generates the HTML view and converts it into a PDF report and sends this PDF as a binary stream back to the client. This means that when the client has a PDF plug-in installed, the PDF is shown inside the browser.

From an action inside your controller, this method should be called to generate the report and send it to the client. The following action from the demo application generates the PDF. "Customer report" is the title of the report, "PrintDemo is the name of the view, and the model is returned by the CreateCustomerList() which as its name implies generates a dummy list with customers.

public ActionResult PrintCustomers()
   return this.ViewPdf("Customer report", "PrintDemo", CreateCustomerList());

The last step is to create a link on a page that calls this action to actually print the report.

Trigger the action on the controller

A simple method to create a link to trigger the action on the controller is by using an ActionLink. This link calls the action that we defined on the controller.

@Html.ActionLink("Print customers", "PrintCustomers", null,  new { target = "_blank" })

These are the steps you need to be able to create PDF reports from your ASP.NET MVC3 projects. Read the next part of the article if you are interested in the details of how the PdfReportGenerator actually converts the ASP.NET MVC3 view into a report.

Detailed Reporting Project overview

The PdfReportGenerator project consist of six classes which can be seen in the image below. The PdfReportGenerator assembly works by rendering the ASP.NET MVC3 view into a string and converting this string with HTML using the iTextSharp into a PDF report.

6 Classes that make up the PdfReportGenerator project

Rendering an ASP.NET MVC3 view into a string

The class HtmlViewRenderer is responsible for rendering the ASP.NET view into a string. The method RenderViewToString has the following signature.

public string RenderViewToString(Controller controller, string viewName, object viewData)

The first argument is viewName which is the name of the view that should get rendered to a string including the model viewData that is needed by the view. The controller is necessary to be able to use to render the view using the view engine of ASP.NET MVC.

Convert the HTML string into a PDF byte array

Once we have the HTML in a string, StandardPdfRenderer converts the HTML string into a PDF byte array. The class StandardPdfRenderer has a method Render with the following signature.

public byte[] Render(string htmlText, string reportTitle)

htmlText is the rendered view as a string that was produced by the HtmlViewRender; pageTitle is, as the name suggests, the title of the report.

Send the byte array back to the client as a stream

The last step is to convert the byte array into an instance of the BinaryContentResult class. The class BinaryContentResult derives from the ASP.NET MVC ActionResult. It overrides ExecuteResult and returns the content as a binary stream.

The class PdfViewController is the class that combines these classes. The method ViewPdf uses all the three previously mentioned classes to generate the PDF as shown in the code below:

protected ActionResult ViewPdf(string pageTitle, string viewName, object model)
    // Render the view html to a string.
    string htmlText = this.htmlViewRenderer.RenderViewToString(this, viewName, model);

    // Let the html be rendered into a PDF document through iTextSharp.
    byte[] buffer = standardPdfRenderer.Render(htmlText, pageTitle);

    // Return the PDF as a binary stream to the client.
    return new BinaryContentResult(buffer, "application/pdf");

Points of interest


iTextsharp supports colors out of the box; in the demo application, the background colors of the rows are alternated using different colors. These colors are visible in the report.

New page support

One thing that I needed with my project that was not supported by the HTML conversion in iTextSharp was functionality to force a page break. Most of the time, with reporting, you need to be able to force a page break, for example, if you want a graph to start always on a new page. The way I solved this was to add support for it to iTextSharp. As it is Open-Source, you are able to add new features to it. I added support for a non-existing HTML tag called <np /> which forces iTextSharp to create a new page. I created a patch so that it could be committed to the iTextSharp project. I do not know if it will be included in the main trunk of the project as it feels somewhat strange to invent new HTML tags just to support a page break. But if you need it, you can use the patch to compile iTextSharp with new page support.


It is possible to add images to the report by using an <img src="" /> tag. I had no success with dynamically generated images. So I generate the images that I needed before the action conversion process takes place. A single static image can be seen in the report.  

ASP.NET support

It should be possible to use the same kind of solution using older versions of ASP.NET MVC. However, I have not tried it.


  • 26/09/2011
    • First version.
  • 06/08/2012
    • Added an image to the PDF report.  


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

Written By
Netherlands Netherlands
Patrick Kalkman is a senior Software Architect with more than 20 years professional development experience. He works for SimpleTechture where he helps teams develop state of the art web applications.

Patrick enjoys writing his blog. It discusses agile software development. Patrick can be reached at

Published Windows 8 apps:

Published Windows Phone apps:


Best Mobile article of March 2012
Best Mobile article of June 2012

Comments and Discussions

AnswerRe: error Pin
Patrick Kalkman15-Jan-13 21:08
MemberPatrick Kalkman15-Jan-13 21:08 
QuestionGreat stuff! Pin
silvia.stanila6-Dec-12 23:54
Membersilvia.stanila6-Dec-12 23:54 
AnswerRe: Great stuff! Pin
Patrick Kalkman15-Jan-13 21:07
MemberPatrick Kalkman15-Jan-13 21:07 
QuestionPagebreak functionality in itextsharp Pin
Scott Kersey3-Dec-12 6:44
MemberScott Kersey3-Dec-12 6:44 
AnswerRe: Pagebreak functionality in itextsharp Pin
Patrick Kalkman3-Dec-12 10:00
MemberPatrick Kalkman3-Dec-12 10:00 
AnswerRe: Pagebreak functionality in itextsharp Pin
Novakovi31-Oct-14 1:26
MemberNovakovi31-Oct-14 1:26 
GeneralMy vote of 5 Pin
sonam_m18-Nov-12 23:14
Membersonam_m18-Nov-12 23:14 
GeneralRe: My vote of 5 Pin
Patrick Kalkman3-Dec-12 10:01
MemberPatrick Kalkman3-Dec-12 10:01 
Thanks sonam_m!
Patrick Kalkman

My latest article: Weekly Thai Recipe! for Windows Phone
My Blog:

QuestionHow is it Persian language Pin
codeproject.ir8-Oct-12 11:21
Membercodeproject.ir8-Oct-12 11:21 
AnswerRe: How is it Persian language Pin
Patrick Kalkman8-Oct-12 22:54
MemberPatrick Kalkman8-Oct-12 22:54 
QuestionPatch & Separate files Pin
AlternativeThought13-Sep-12 1:15
MemberAlternativeThought13-Sep-12 1:15 
AnswerRe: Patch & Separate files Pin
Patrick Kalkman8-Oct-12 22:59
MemberPatrick Kalkman8-Oct-12 22:59 
Question{"Unable to cast object of type 'iTextSharp.text.List' to type 'iTextSharp.text.Paragraph'."} Pin
M Ali Qadir16-Aug-12 1:44
MemberM Ali Qadir16-Aug-12 1:44 
AnswerRe: {"Unable to cast object of type 'iTextSharp.text.List' to type 'iTextSharp.text.Paragraph'."} Pin
Patrick Kalkman8-Oct-12 23:00
MemberPatrick Kalkman8-Oct-12 23:00 
QuestionMy 5 ! Pin
WajihaAhmed7-Aug-12 6:56
MemberWajihaAhmed7-Aug-12 6:56 
AnswerRe: My 5 ! Pin
Patrick Kalkman7-Aug-12 21:41
MemberPatrick Kalkman7-Aug-12 21:41 
QuestionNice Stuff Pin
felipekm6-Aug-12 10:05
Memberfelipekm6-Aug-12 10:05 
AnswerRe: Nice Stuff Pin
Patrick Kalkman6-Aug-12 23:10
MemberPatrick Kalkman6-Aug-12 23:10 
GeneralMy vote of 5 Pin
Christian Amado6-Aug-12 9:38
professionalChristian Amado6-Aug-12 9:38 
GeneralRe: My vote of 5 Pin
Patrick Kalkman6-Aug-12 23:10
MemberPatrick Kalkman6-Aug-12 23:10 
Questionimage Pin
boylak30-Jul-12 21:20
Memberboylak30-Jul-12 21:20 
AnswerRe: image Pin
Patrick Kalkman5-Aug-12 22:52
MemberPatrick Kalkman5-Aug-12 22:52 
Questionhi,when multi page, second page's title position is not correct and no column caption Pin
chenlulouis16-Jul-12 18:39
Memberchenlulouis16-Jul-12 18:39 
GeneralRe: Convert HTML to PDF in ASP.NET MVC Razor Pin
Patrick Kalkman5-Aug-12 22:54
MemberPatrick Kalkman5-Aug-12 22:54 
GeneralMy vote of 5 Pin
FVermeer11-Jul-12 4:34
MemberFVermeer11-Jul-12 4:34 

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.