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:
https://www.nuget.org/packages/RazorPDF
Example(Creating PDF with ASP.Net MVC):
Once you click on OK. It will ask for type of project. We are going to create ASP.Net MVC internet application.
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.
Like following.
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.
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.
Once you click add it will create a view and now let’s run that application. It will look like following.
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.
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.
iTextXML is removed from the latest versions of the iTextSharp.
ReplyDeleteYes I know that.
ReplyDeleteHi, colors don´t work...
ReplyDeleteCss?
tks
Awesome. Saved me from lots of manual typing! Thanks for the library.
ReplyDeleteVery Nice and clean blog, Thank Jalpesh
ReplyDeleteThanks Haresh
ReplyDeletethanks lee
ReplyDeleteI will check that.
ReplyDeletegreet
ReplyDeleteHello,
ReplyDeleteGreat 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 })
}
@html directive will not work with this.
ReplyDeletethanks
ReplyDeleteBut the code was generated by MVC view following your example. What do you suggest?
ReplyDeleteIf you see my code carefully I have not implemented @html I have used model to create it printer friendly view.
ReplyDeleteI have used @html for viewing purpose in browser
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
ReplyDeleteYou are welcome!! Glad that you have figure it out!!
ReplyDeleteI 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.
ReplyDeleteWhat error you are getting?. Are you using similar kind of pdf generation view like.
ReplyDelete@model List
@{
Layout = null;
}
Html List in PDF
First Name
Last Name
@foreach (var item in Model)
{
@item.FirstName
@item.LastName
}
I think we have a problem in messaging. It seems that some of my messages are posted on DISQUS and others on DotNetJalps.
ReplyDeleteThe 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.
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.
ReplyDeleteHow do I change the orientation to 'landscape'?
ReplyDeletethanks Jalpesh, its working , m in need to add images with dat pdf, can u help me ?
ReplyDeleteI will check and get back to you
ReplyDeleteme too getting same problem, css not working
ReplyDeleteHI Brad I will write a post about it. Right now doing R and D for that.
ReplyDeletehi, do you know how to add colors, styles?
ReplyDeletethanks
hi, do you know how to add colors or styles?
ReplyDeletethanks
...all....
ReplyDeleteHi will post an blog post for that
ReplyDeleteWill post blog post soon
ReplyDeletePlease see the answer from p viga
ReplyDeleteDear Sir,
ReplyDeleteMy 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.
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
ReplyDeletebut 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
How do we handle if we have multiple pages? can we get report header on each page?
ReplyDeleteI will write a blog post soon about all the problems people are facing!!
ReplyDeleteCan you make sure you have added all the required references I suggest to remove all the references and add via nuget package.
ReplyDeleteI will write an blog post for the same.
ReplyDeleteHi, 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 :(
ReplyDeletenot worked with itextsharp latest version...is there any solution
ReplyDeleteI will check and will let you know
ReplyDeleteHi, this package is awesome.
ReplyDeleteIs there a possibility to send the PdfResult as email?
hi it is great but if u do this in empty web application it is not converting please help me ....
ReplyDeleteStep 1- take empty web application
setp 2 -install razar pkg then do same code it can't display.
can you paste your code there.
ReplyDeleteWhen 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.
ReplyDeletethanks so much
I am telling about PDF Action Result. You need to create a view for PDF.
Deletei 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.
ReplyDeleteYou can create a empty view via clicking on action result then you manually you need to use it.
Deletewhen 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 ?
ReplyDeleteon Button Click redirect to Customer\pdf
Deletethis is the button i currently have,
Deletebutton 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
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.
ReplyDeleteYes, You can add this to already existing controller the only things you need to create a separate view for this.
DeleteHi Jalpesh,
ReplyDeleteDoes 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?
Can you provide me your source code I help you better way.
DeleteGiven demo not working in MVC 5 blank application. Anything required to modify it to working in MVC5?
ReplyDeleteI will check and will let you know. Most probably it should work.
DeleteInline styles are not applying?
ReplyDeleteIt will not work. You have to give style sheet class only.
DeleteJalpesh
ReplyDeletewhat is setting for create pdf in multilingual case like Hindi,Gujarat etc..
Kirti it will support if ITextSharp supports
DeleteHi,
ReplyDeleteIt would be helpful if u can provide VB version of the same implementation.
There are lots of C# to VB.NET converter available like http://converter.telerik.com/. You can convert this code via this.
DeleteHi,
ReplyDeleteI have an empty PDF with asp .net MVC 5 normal ???
I think there must be some thing wrong either one of HTML tag was not complete.
DeleteHum 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
DeleteCan you send me your code please on email address mentioned in my blog's about me page.
DeleteSelect.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.
ReplyDeleteMore details: http://selectpdf.com/community-edition/
I m facing this problem : Could not load type 'iTextSharp.text.html.HtmlParser' from
ReplyDeleteassembly 'itextsharp, Version=5.0.6.0, Culture=neutral,
PublicKeyToken=8354ae6d2174ddca'.
You are missting Itextsharp referecne. Did you added it via Nuget Package? or you find the same version nuget pacakge for itextsharp
ReplyDeletehttps://www.nuget.org/packages/iTextSharp/5.0.6 - add this nuget pacakge -Install-Package iTextSharp -Version 5.0.6
ReplyDeleteError when run page
ReplyDeleteI 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
But still I am getting this error
ReplyDeletedid you added reference to Itextsharp version5?
ReplyDeleteYou need to add reference to Itextsharp 5.0. See the previous errors there.
ReplyDeleteHello!!
ReplyDeleteI get this error pleaaase help me!! i have already added Itextsharp 5.5.5.0!!!
I get the following error what I tried the RazorPDF. I also installed the itextSharp reference from nugget package. Please help me out.
ReplyDeleteDid you installed itextsharp version 5.0.6.0?
ReplyDeleteI did install iTextSharp Version 5.0.6.0 as depicted in the attached image.
ReplyDeleteYou can uninstall package and install it again.
ReplyDeletei had the same error, please download itextsharp 4.1.2.0 dll manually and add the reference.
ReplyDeletei have the same question, any asnwer?
ReplyDelete