iText & iTextSharp.
iText is an open source DLL for creating PDF files in Java Language. It is well established and matured library.
it has been converted to the .NET compatibility and has been named as iTextSharp. It was written in C# and has a separate codebase, but it is synchronized to iText releases.
This article is not about generating view in MVC, but for converting view to PDF, so I will not go in deep for creating a view and will assume that you have a list page or any other view which needs to be exported in PDF format.
For e.g. consider the following two images. In first I have User List view of a sample Phone Book Application. Notice the EXPORT PDF Icon on right corner of the screen. On click of Icon, the view gets Exported as PDF which can be seen in second Image.
In View Page
In your View Page, add an icon or button, which will generate PDF on Click of it. I have chosen an Icon which will redirect to an Controllers action which will generate the PDF.
This will call UserList action in GeneratePDF controller.
Now in action, first we will get data from database and generate view by repeatedly binding to a string variable which will in turn be copied to a PDF Document.
Few things to note,
var lstUser = (from u in db.user
This is variable where we store data which will be used in PDF.
string pdfBody = string.Empty;
This variable will store our HTML body structure, which will be then copied to PDF document.
Note that I have used inline css and not any class. This is because, external class will not work in generating any document. You need to apply internal css only.
fpath and filenm
var fpath = HttpContext.Server.MapPath("~/Content/PDFDocuments/");
string filenm = "UserList.pdf";
This variable will store file path where we need to store generated file and file name of that file respectively.
We create a new object of document class and then open document to start writing in it.
Document document = new Document();
styles and hw
This variable will store styling related info for iTextSharp.
iTextSharp.text.html.simpleparser.StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet();
iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(document);
Once this all is done, pass our pdfBody variable to parse in hw variable and close the document variable.
Loop for Data
Loop through all the record and append it in pdfBody variable to get data in pdf.
for (int i = 0; i < lstUser.Count(); i++)
Response.ContentType = "application/pdf";
Response.WriteFile(HttpContext.Server.MapPath("~/Content/PDFDocuments/") + filenm);
This will specify the content type i.e. PDF and will start to write file on the specified location.
Hope you find this article interesting and can explore rich options of iTextSharp.