Creating PDF with ASP.Net MVC and RazorPDF

  • 52
In this post we are going to learn how we can easily create PDF from ASP.Net application with the help of Razor PDF NuGet package.

About Razor PDF:


This NuGet package is created by Al Nyveldt It internally uses ITextSharp an open source PDF convertor library. RazorPDF uses Razor View engine to create iTextXML which is in tern used to produce PDF file. You can get more information about that at below link.

https://www.nuget.org/packages/RazorPDF

Example(Creating PDF with ASP.Net MVC):


So what we are we waiting for ? Let’s create a simple example. To create example first thing we need to a create and ASP.Net MVC application.

ASPNETPDFDemoApplication

Once you click on OK. It will ask for type of project. We are going to create ASP.Net MVC internet application.

MVCTypeApplicationRazorPDF

Once you click on it will create an application. The next thing you need to install a NuGet package. You need to type following command on your NuGet Package manager console.

NuGetPackageforASPNETMVCPDF

Like following.

NugetPacketManagerConsoleForCreatingPDFinaspnetmvc

Now our application is ready to create PDF files. Now to create an example Let’s create a model class ‘Customer’ to create a listing of customers in the application.
namespace PDFDemor.Models
{
    public class Customer
    {
        public int CustomerID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}
Now Custom class is ready. So let’s create an CustomerController with listing of customer ActionResult like following.

CreatingControllerToCreatePDFinaspnetmvc

Now once you click Add It will create CustomerController. In index ActionResult I have created following code. Where I have created an list and pass it to view.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PDFDemo.Models;

namespace PDFDemo.Controllers
{
    public class CustomerController : Controller
    {
        //
        // GET: /Customer/

        public ActionResult Index()
        {
            List<Customer> customers= new List<Customer>();

            for (int i = 1; i <= 10; i++)
            {
                Customer customer = new Customer
                {
                    CustomerID = i,
                    FirstName = string.Format("FirstName{0}", i.ToString()),
                    LastName = string.Format("LastName{0}", i.ToString())
                };
                customers.Add(customer);
            }
            return View(customers);
        }

    }
}
Now lt’s time to create view for listing of customers like following.

CreatingaViewforPDfListing

Once you click add it will create a view and now let’s run that application. It will look like following.

image

So everything looks good now. Now It’s time to create PDF document for same list. Let’s create a new action result method called PDF in same controller.
public ActionResult PDF()
{
    List<Customer> customers = new List<Customer>();

    for (int i = 1; i <= 10; i++)
    {
        Customer customer = new Customer
        {
            CustomerID = i,
            FirstName = string.Format("FirstName{0}", i.ToString()),
            LastName = string.Format("LastName{0}", i.ToString())
        };
        customers.Add(customer);
    }

    return new RazorPDF.PdfResult(customers, "PDF");
}
Here in the above code I have created a list and send it to a PDF Result which will result in PDF Document.Now let’s create a Razor view for that action result like following.
@model List<PDFDemo.Models.Customer>
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <h2>Html List in PDF</h2>
    <table width="100%">
        <tr>
            <td>First Name</td>
          
            <td>Last Name</td>
        </tr>
        @foreach (var item in Model)
        {
            <tr>
                <td>@item.FirstName</td>
              
                <td>@item.LastName</td>
            </tr>
        }
    </table>
</body>
</html>
Here you can see I have printed a simple table with first name  and last name. I have made layout=null as I don’t want any HTML. Now let’s run this application. And my list is converted in PDF as expected.

image

That’s it. It’s very easy to create PDF with ASP.Net with Razor PDF. There are more complex examples created by Al Nyveldt at following link.

https://github.com/RazorAnt/RazorPDFSample

Hope you like it. Stay tuned for more.

52 comments:

  1. iTextXML is removed from the latest versions of the iTextSharp.

    ReplyDelete
  2. Hi, colors don´t work...

    Css?


    tks

    ReplyDelete
  3. Awesome. Saved me from lots of manual typing! Thanks for the library.

    ReplyDelete
  4. Very Nice and clean blog, Thank Jalpesh

    ReplyDelete
  5. Hello,
    Great function but I am getting error in the index.cshtml
    @foreach (var item in Model) { // The error occurs here :Object Reference NULL value


    @Html.DisplayFor(modelItem => item.FirstName)


    @Html.DisplayFor(modelItem => item.LastName)


    @Html.ActionLink("Edit", "Edit", new { id=item.CustomerID }) |
    @Html.ActionLink("Details", "Details", new { id=item.CustomerID }) |
    @Html.ActionLink("Delete", "Delete", new { id=item.CustomerID })


    }

    ReplyDelete
  6. @html directive will not work with this.

    ReplyDelete
  7. But the code was generated by MVC view following your example. What do you suggest?

    ReplyDelete
  8. If you see my code carefully I have not implemented @html I have used model to create it printer friendly view.


    I have used @html for viewing purpose in browser

    ReplyDelete
  9. So because asp MVC already has index.cshtml, I delete that and replace with the new view index. When I run code I get error on for each line. Thank you

    ReplyDelete
  10. You are welcome!! Glad that you have figure it out!!

    ReplyDelete
  11. I am sorry but I still have a problem. You did not answer why I get error. I sent you the complete code generated by MVC view. I am not able to run the program to display the view before the PDF addition.

    ReplyDelete
  12. What error you are getting?. Are you using similar kind of pdf generation view like.

    @model List

    @{

    Layout = null;

    }











    Html List in PDF





    First Name



    Last Name



    @foreach (var item in Model)

    {



    @item.FirstName



    @item.LastName



    }

    ReplyDelete
  13. I think we have a problem in messaging. It seems that some of my messages are posted on DISQUS and others on DotNetJalps.
    The error happens when I create the first MVC View. I am not able to see the View with LastName and FirstName. Please synchronize my posts on both DISQUS and DotNetJalps.

    ReplyDelete
  14. Hi let's take it offline. Can you send me your problem with code at my email address given in about us page of this blog.

    ReplyDelete
  15. How do I change the orientation to 'landscape'?

    ReplyDelete
  16. thanks Jalpesh, its working , m in need to add images with dat pdf, can u help me ?

    ReplyDelete
  17. me too getting same problem, css not working

    ReplyDelete
  18. HI Brad I will write a post about it. Right now doing R and D for that.

    ReplyDelete
  19. hi, do you know how to add colors, styles?


    thanks

    ReplyDelete
  20. hi, do you know how to add colors or styles?


    thanks

    ReplyDelete
  21. Dear Sir,



    My view has an image in it, I followed this example and I can transfer the view to PDF successfully. But the image is gone.Do you have any suggestions I can use RazorPDF to generate a PDF document with an image in it? Thank you.

    ReplyDelete
  22. Hi, i can follow all these steps, if i try to show the view, "return view();" its work great, and show an html simple table


    but when i try:
    return new RazorPDF.PdfResult(null, "CustomView");
    the browser only show a gray screen.



    any idea in how to resolve this? or what can cause this situation??


    Thanks!!! :D

    ReplyDelete
  23. How do we handle if we have multiple pages? can we get report header on each page?

    ReplyDelete
  24. I will write a blog post soon about all the problems people are facing!!

    ReplyDelete
  25. Can you make sure you have added all the required references I suggest to remove all the references and add via nuget package.

    ReplyDelete
  26. Hi, thanks for response, in fact, i added RazorPDF via nuget. I can create a pdf file with itextSharp code in the controller, and works fine, but requires a lot of code to make a simple table with styles. i would prefer to make it with RazorPDF and .cshtml view, but its not working for me :(

    ReplyDelete
  27. not worked with itextsharp latest version...is there any solution

    ReplyDelete
  28. Hi, this package is awesome.

    Is there a possibility to send the PdfResult as email?

    ReplyDelete
  29. hi it is great but if u do this in empty web application it is not converting please help me ....


    Step 1- take empty web application


    setp 2 -install razar pkg then do same code it can't display.

    ReplyDelete
  30. When I ran the application after creating the index view, i didnt see the same page displayed in the sample. also can you explain more about "Now let’s create a Razor view for that action result like following". I was alittle confused on were this code should go. if there is anyway to get a little more details that would be much appreciated.

    thanks so much

    ReplyDelete
    Replies
    1. I am telling about PDF Action Result. You need to create a view for PDF.

      Delete
  31. i understand that, but should i create a view by right clicking on the actionresult or just by adding a new view thru solution explorer? i followed the sample but i must be missing something, because im not getting the list view or pdf view displaying when i run the application.

    ReplyDelete
    Replies
    1. You can create a empty view via clicking on action result then you manually you need to use it.

      Delete
  32. when i type customer/pdf in the url i get taken to the pdf display. however is there a way to have the data then with the click of a button display the pdf ?

    ReplyDelete
    Replies
    1. on Button Click redirect to Customer\pdf

      Delete
    2. this is the button i currently have,
      button type="button" class="btn btn-default btn-sm col-sm-3" id="incidentsPreviewReport" data-role="none">Preview Report</button
      can you help me with the code on how i can redirect this to Customer.pdf and view my pdf on the click.

      thank you

      Delete
  33. do you have any tips or advice on how i can add this functionality into an already created asp.net mvc 4 application? just wondering if i can add this code into alreay exsiting controllers and views or if there is some way to link these views and controllers to what i already have? i am kinda new to coding but i am asuming there is someway to make this work with my application. thank you so much for your help.

    ReplyDelete
    Replies
    1. Yes, You can add this to already existing controller the only things you need to create a separate view for this.

      Delete

Your feedback are very important to me. Please provide your feedback via putting comments.