Sunday, June 9, 2013

Creating PDF with ASP.Net MVC and RazorPDF

Update: I have written a new blog post about better approach to create a PDF with asp.net mvc- You can find that following location.- A Better Solution to create PDF with Rotativa and ASP.NET MVC

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.

Share:

81 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
  34. Hi Jalpesh,

    Does it work for image too? Becuase I have added image in PDF view and when page runs its not displaying it. Only plan html tag accepting even not working with any CSS stylesheet.

    Could you please let me know the solution?

    ReplyDelete
    Replies
    1. Can you provide me your source code I help you better way.

      Delete
  35. Given demo not working in MVC 5 blank application. Anything required to modify it to working in MVC5?

    ReplyDelete
    Replies
    1. I will check and will let you know. Most probably it should work.

      Delete
  36. Replies
    1. It will not work. You have to give style sheet class only.

      Delete
  37. Jalpesh

    what is setting for create pdf in multilingual case like Hindi,Gujarat etc..

    ReplyDelete
  38. Hi,
    It would be helpful if u can provide VB version of the same implementation.

    ReplyDelete
    Replies
    1. There are lots of C# to VB.NET converter available like http://converter.telerik.com/. You can convert this code via this.

      Delete
  39. Hi,

    I have an empty PDF with asp .net MVC 5 normal ???

    ReplyDelete
    Replies
    1. I think there must be some thing wrong either one of HTML tag was not complete.

      Delete
    2. Hum no no my html is correct , with head and body and doctype html5 with a parapgraph , my pdf is empty with new mvc 5.1

      Delete
    3. Can you send me your code please on email address mentioned in my blog's about me page.

      Delete
  40. Select.Pdf offers a Community Edition (FREE) of the powerful Html To Pdf Converter for .NET that can be found in the full featured pdf library Select.Pdf for .NET. The free html to pdf converter offers most of the features the professional sdk offers, the only notable limitation is that it can only generate pdf documents up to 5 pages long.

    More details: http://selectpdf.com/community-edition/

    ReplyDelete
  41. I m facing this problem : Could not load type 'iTextSharp.text.html.HtmlParser' from
    assembly 'itextsharp, Version=5.0.6.0, Culture=neutral,
    PublicKeyToken=8354ae6d2174ddca'.

    ReplyDelete
  42. You are missting Itextsharp referecne. Did you added it via Nuget Package? or you find the same version nuget pacakge for itextsharp

    ReplyDelete
  43. https://www.nuget.org/packages/iTextSharp/5.0.6 - add this nuget pacakge -Install-Package iTextSharp -Version 5.0.6

    ReplyDelete
  44. Error when run page
    I have visual studio 2012.

    and one more problem that how to run report viewer with rdlc report on web server live because run local server but live error that is show in 2 image.
    Please help Me because i make one big system in mvc4 but report option not working with rdlc.
    suggest any other option if possible

    Thanks in Advance

    ReplyDelete
  45. But still I am getting this error

    ReplyDelete
  46. did you added reference to Itextsharp version5?

    ReplyDelete
  47. You need to add reference to Itextsharp 5.0. See the previous errors there.

    ReplyDelete
  48. Hello!!

    I get this error pleaaase help me!! i have already added Itextsharp 5.5.5.0!!!

    ReplyDelete
  49. I get the following error what I tried the RazorPDF. I also installed the itextSharp reference from nugget package. Please help me out.

    ReplyDelete
  50. Did you installed itextsharp version 5.0.6.0?

    ReplyDelete
  51. I did install iTextSharp Version 5.0.6.0 as depicted in the attached image.

    ReplyDelete
  52. You can uninstall package and install it again.

    ReplyDelete
  53. i had the same error, please download itextsharp 4.1.2.0 dll manually and add the reference.

    ReplyDelete
  54. i have the same question, any asnwer?

    ReplyDelete

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

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews