Click here to Skip to main content
15,867,568 members
Articles / Web Development / ASP.NET

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 438.6K   30.7K   179   128
A description and solution for creating PDF reports using ASP.NET MVC3.

ASP_MVC_Reporting/ASP_MVC3_PDF_Reporting_1.jpg

Contents

Introduction

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.

Background

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.

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

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:

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

Parameters

  • 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.

C#
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.

C#
@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.

C#
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.

C#
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:

C#
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

Colors

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.

Images

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.

History

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

License

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


Written By
Architect http://www.simpletechture.nl
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 patrick@simpletechture.nl.

Published Windows 8 apps:


Published Windows Phone apps:


Awards:

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

Comments and Discussions

 
QuestionGreate Article - How to give Background imgae Pin
Shamseer K17-Sep-16 2:43
professionalShamseer K17-Sep-16 2:43 
QuestionOnly heading is printing. The content not getting printed Pin
hishamkmr19-Sep-15 20:51
hishamkmr19-Sep-15 20:51 
Questionthank's Pin
Member 1193724726-Aug-15 2:31
Member 1193724726-Aug-15 2:31 
QuestionCannot load dynamic images.... Pin
Naeem Ullah23-Aug-15 22:38
Naeem Ullah23-Aug-15 22:38 
Questionproblem Pin
Member 1152138112-Mar-15 21:19
Member 1152138112-Mar-15 21:19 
QuestionHow to print on new page Pin
Member 1152138112-Mar-15 21:18
Member 1152138112-Mar-15 21:18 
QuestionClickable on PDF file Pin
tranmaiphuong5-Mar-15 22:28
tranmaiphuong5-Mar-15 22:28 
QuestionNot valid PDF document Pin
Member 87111476-Jan-15 4:17
Member 87111476-Jan-15 4:17 
QuestionInline css is not working Pin
Member 1048839126-Dec-14 1:10
Member 1048839126-Dec-14 1:10 
QuestionHow to remove the page number and Date from the PDF. Pin
Member 1048839125-Dec-14 23:57
Member 1048839125-Dec-14 23:57 
AnswerRe: How to remove the page number and Date from the PDF. Pin
Patrick Kalkman26-Dec-14 0:55
Patrick Kalkman26-Dec-14 0:55 
GeneralRe: How to remove the page number and Date from the PDF. Pin
Member 1048839126-Dec-14 1:11
Member 1048839126-Dec-14 1:11 
QuestionArabic letters support Pin
Nasir Taha25-Nov-14 22:17
Nasir Taha25-Nov-14 22:17 
GeneralMy vote of 1 Pin
Anchal Singh28-Sep-14 20:11
Anchal Singh28-Sep-14 20:11 
GeneralMy Vote Of 5 Pin
DiponRoy15-Aug-14 20:59
mvaDiponRoy15-Aug-14 20:59 
GeneralRe: My Vote Of 5 Pin
Patrick Kalkman26-Dec-14 0:56
Patrick Kalkman26-Dec-14 0:56 
GeneralPoints Pin
Member 1081583413-May-14 10:40
Member 1081583413-May-14 10:40 
GeneralRe: Points Pin
Patrick Kalkman26-Dec-14 0:56
Patrick Kalkman26-Dec-14 0:56 
GeneralMy vote of 5 Pin
Member 42253394-Mar-14 2:18
Member 42253394-Mar-14 2:18 
GeneralRe: My vote of 5 Pin
Patrick Kalkman15-Apr-14 20:42
Patrick Kalkman15-Apr-14 20:42 
QuestionAccess error Pin
nataliaps2-Jan-14 23:48
nataliaps2-Jan-14 23:48 
AnswerRe: Access error Pin
handersonmarinho23-Jan-14 5:17
handersonmarinho23-Jan-14 5:17 
GeneralRe: Access error Pin
nataliaps24-Jan-14 11:40
nataliaps24-Jan-14 11:40 
AnswerRe: Access error Pin
Patrick Kalkman2-Feb-14 20:33
Patrick Kalkman2-Feb-14 20:33 
GeneralRe: Access error Pin
nataliaps18-Mar-14 1:14
nataliaps18-Mar-14 1:14 

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.