Abstract
This is a tip for creating PDF using ItextSharp and downloading the PDF file using ASP.NET MVC.
- Introduction
As we know whenever we are working on a project there is a need of reports that a user wants to view for a respective business date -- it can be any day to day transactional reports, inventory reports of stores etc. Irrespective of the project in the tip of code snippet I will be generating a PDF report of a sample records which I will fetch from database as shown below step by step.
1.1 Create New Project
Figure 1: New Project in VS 2015
1.2 Select MVC Template for creating WEB Application as shown below:
Figure 2: Selecting MVC Template
Here I will using Entity Framework to retrieve records from the table. If you are new to Entity Framework my suggestion is to go and read my basic article on Entity Framework.
• Getting Started With Entity Framework
• First what records I am going to show into the pdf file?
• I will be showing Employee details to the User as shown below in the snapshot.
Figure 3: Information to be shown in pdf
1.3 Creating your Models
Now we will create Model class named Employee as shown below:
Figure 4: Creating Model Class
Figure 5: Naming your Model class
- using System.Text;
- using System.Threading.Tasks;
- using System.ComponentModel.DataAnnotations;
- namespace DownloadPdf.Models
- {
- public class Employee
- {
-
- [Key]
- public int EmployeeId
- {
- get;
- set;
- }
- public string Name
- {
- get;
- set;
- }
- public string Gender
- {
- get;
- set;
- }
- public string City
- {
- get;
- set;
- }
- public int DepartmentId
- {
- get;
- set;
- }
- public DateTime Hire_Date
- {
- get;
- set;
- }
-
- }
- }
So now In order to create our db connectivity I will add a class which will act as DataModel for this project.
Figure 6: Creating DBContextDataModel Class
- using System.Data.Entity;
-
- namespace DownloadPdf.Models
- {
- public class DataModel: DbContext
- {
- public DbSet < Employee > employees
- {
- get;
- set;
- }
-
- protected override void OnModelCreating(DbModelBuildermodelBuilder)
- {
- modelBuilder.Entity < Employee > ().ToTable("tblEmployee");
- }
-
- }
- }
1.4 Adding the connection string,
Go to server explorer
Figure 7: Server Explorer window
Click on Data Connections and add new connection.
Figure 8: Adding Data Connection in asp.net MVC
Figure 9: Selecting your db
Select your server name and enter your database name. Click on ok to confirm.
Right click on new created connection:
Figure 10: Checking Properties of new Data Connection
Go to properties.
Figure 11: Connection String Property
And copy the connection string and create a connection string in web.config file as shown below:
- <connectionStrings>
- <add name="DataModel" connectionString="Data Source=DEVELOPER-VAIO;Initial Catalog=Demos;Integrated Security=True" providerName="System.Data.SqlClient" />
- </connectionStrings>
Make sure you name connection string with same name as your DataModel. Here I will using default Home controller and show the details from the table into the view.
- DataModel _context = newDataModel();
- public ActionResult Index() {
- List < Employee > employees = _context.employees.ToList < Employee > ();
-
- return View(employees);
- }
-
- View
-
-
- @model IEnumerable < DownloadPdf.Models.Employee >
- @ {
- ViewBag.Title = "Home Page";
- }
-
-
- < div class = "row" >
- < div class = "col-md-12" >
- < div class = "h2 text-center" > Employee Details < /div> < tableclass = "table table-bordered" >
-
- < thead >
- < tr >
- < td >
- Id < /td> < td >
- Name < /td> < td >
- Gender < /td> < td >
- City < /td> < td >
- Hire_Date < /td> < /tr>
-
- < /thead> < tbody >
-
- @foreach(varempin Model)
-
- { < tr >
- < td > @emp.EmployeeId < /td> < td > @emp.Name < /td> < td > @emp.Gender < /td> < td > @emp.City < /td> < td > @emp.Hire_Date < /td>
-
- < /tr>
- } < /tbody>
-
- < /table>
-
- < /div> < divclass = "col-sm-2" >
- < divclass = "btnbtn-success" > @Html.ActionLink("Create Pdf", "CreatePdf", "Home") < /div>
-
- < /div> < /div>
After running the application Our View,
Figure 12: Our Employee Details View
Now we will create a method to create pdf and download the same using Itextsharp so now we need to download Itextsharp.
- ITextSharp
“iText Software is a world-leading specialist in programmable PDF software libraries for professionals. Its solutions are used in sales and marketing, legal and governance, finance, IT, operations and HR by a diverse customer base that includes medical institutions, banks, governments and technology companies.”
Source: About
Go to Manage Nuget Package manager and search for Itextsharp as shown below:
Figure 13: Installing Nuget Package Manager
And install the same.
Now we will see the itextsharp library added to our references.
Figure 14:Demonstrating Addition of ItextSharpdll in references
Now let’s start creating our method for pdf creation.
In MVC we have several Action Result egPartialViewResult, Content, JavaScript Result, EmptyResult, Redirect Result etc. We will be using FileResult which used to send binary file content to the response.
Let get started:
- public FileResultCreatePdf()
- {
- MemoryStreamworkStream = newMemoryStream();
- StringBuilder status = newStringBuilder("");
- DateTimedTime = DateTime.Now;
-
- stringstrPDFFileName = string.Format("SamplePdf" + dTime.ToString("yyyyMMdd") + "-" + ".pdf");
- Document doc = newDocument();
- doc.SetMargins(0 f, 0 f, 0 f, 0 f);
-
- PdfPTabletableLayout = newPdfPTable(5);
- doc.SetMargins(0 f, 0 f, 0 f, 0 f);
-
-
-
- stringstrAttachment = Server.MapPath("~/Downloadss/" + strPDFFileName);
-
-
- PdfWriter.GetInstance(doc, workStream).CloseStream = false;
- doc.Open();
-
-
- doc.Add(Add_Content_To_PDF(tableLayout));
-
-
- doc.Close();
-
- byte[] byteInfo = workStream.ToArray();
- workStream.Write(byteInfo, 0, byteInfo.Length);
- workStream.Position = 0;
-
-
- return File(workStream, "application/pdf", strPDFFileName);
-
- }
-
- protected PdfPTableAdd_Content_To_PDF(PdfPTabletableLayout)
- {
-
- float[] headers = {50,24,45,35,50};
- tableLayout.SetWidths(headers);
- tableLayout.WidthPercentage = 100;
- tableLayout.HeaderRows = 1;
-
-
- List < Employee > employees = _context.employees.ToList < Employee > ();
-
-
-
- tableLayout.AddCell(newPdfPCell(newPhrase("Creating Pdf using ItextSharp", newFont(Font.FontFamily.HELVETICA, 8, 1, newiTextSharp.text.BaseColor(0, 0, 0)))) {
- Colspan = 12, Border = 0, PaddingBottom = 5, HorizontalAlignment = Element.ALIGN_CENTER
- });
-
-
-
- AddCellToHeader(tableLayout, "EmployeeId");
- AddCellToHeader(tableLayout, "Name");
- AddCellToHeader(tableLayout, "Gender");
- AddCellToHeader(tableLayout, "City");
- AddCellToHeader(tableLayout, "Hire Date");
-
-
-
- foreach(varempin employees)
- {
-
- AddCellToBody(tableLayout, emp.EmployeeId.ToString());
- AddCellToBody(tableLayout, emp.Name);
- AddCellToBody(tableLayout, emp.Gender);
- AddCellToBody(tableLayout, emp.City);
- AddCellToBody(tableLayout, emp.Hire_Date.ToString());
-
- }
-
- returntableLayout;
- }
-
- private static void AddCellToHeader(PdfPTabletableLayout, stringcellText)
- {
-
- tableLayout.AddCell(newPdfPCell(newPhrase(cellText, newFont(Font.FontFamily.HELVETICA, 8, 1, iTextSharp.text.BaseColor.YELLOW)))
- {
- HorizontalAlignment = Element.ALIGN_LEFT, Padding = 5, BackgroundColor = newiTextSharp.text.BaseColor(128, 0, 0)
- });
- }
-
-
- private static voidAddCellToBody(PdfPTabletableLayout, stringcellText)
- {
- tableLayout.AddCell(newPdfPCell(newPhrase(cellText, newFont(Font.FontFamily.HELVETICA, 8, 1, iTextSharp.text.BaseColor.BLACK)))
- {
- HorizontalAlignment = Element.ALIGN_LEFT, Padding = 5, BackgroundColor = newiTextSharp.text.BaseColor(255, 255, 255)
- });
- }
Now let’s run our Application and check whether pdf is getting generated or not?
Figure 16: View
Once User click on Generate Pdf. Pdf gets generated successfully as shown below.
Figure 17: PDF Generation
Now once we open the pdf we will see our records displayed in table format as shown below:
Figure 18: PDF View in Google Chrome
Hence I want to commence this code snippet tip for creating PDF file using ItextSharp in ASP.NET MVC. I hope this tip was useful and stay tuned on C# Corner for upcoming topics.
Read more articles on ASP.NET: