Create A PDF File And Download Using ASP.NET MVC

Abstract

This is a tip for creating PDF using ItextSharp and downloading the PDF file using ASP.NET MVC.

  1. 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

    web app
                                              Figure 1: New Project in VS 2015

    1.2 Select MVC Template for creating WEB Application as shown below:

    mvc
                                                 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.

    table
                                     Figure 3: Information to be shown in pdf

    1.3 Creating your Models

    Now we will create Model class named Employee as shown below:

    class
                                                    Figure 4: Creating Model Class

    class
                                                 Figure 5: Naming your Model class
    1. using System.Text;  
    2. using System.Threading.Tasks;  
    3. using System.ComponentModel.DataAnnotations;  
    4. namespace DownloadPdf.Models  
    5. {  
    6.     public class Employee  
    7.     {  
    8.   
    9.         [Key]  
    10.         public int EmployeeId  
    11.         {  
    12.             get;  
    13.             set;  
    14.         }  
    15.         public string Name   
    16.         {  
    17.             get;  
    18.             set;  
    19.         }  
    20.         public string Gender  
    21.         {  
    22.             get;  
    23.             set;  
    24.         }  
    25.         public string City  
    26.         {  
    27.             get;  
    28.             set;  
    29.         }  
    30.         public int DepartmentId  
    31.         {  
    32.             get;  
    33.             set;  
    34.         }  
    35.         public DateTime Hire_Date  
    36.         {  
    37.             get;  
    38.             set;  
    39.         }  
    40.   
    41.     }  
    42. }  
    So now In order to create our db connectivity I will add a class which will act as DataModel for this project.

    class
                                     Figure 6: Creating DBContextDataModel Class
    1. using System.Data.Entity;  
    2.   
    3. namespace DownloadPdf.Models  
    4. {  
    5.     public class DataModel: DbContext  
    6.     {  
    7.         public DbSet < Employee > employees  
    8.         {  
    9.             get;  
    10.             set;  
    11.         }  
    12.   
    13.         protected override void OnModelCreating(DbModelBuildermodelBuilder)   
    14.         {  
    15.             modelBuilder.Entity < Employee > ().ToTable("tblEmployee");  
    16.         }  
    17.   
    18.     }  
    19. }  
    1.4 Adding the connection string,

    Go to server explorer

    server
                   Figure 7: Server Explorer window

    Click on Data Connections and add new connection.

    add connection
                Figure 8: Adding Data Connection in asp.net MVC



    database
                               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:


    properties
                            Figure 10: Checking Properties of new Data Connection

    Go to properties.

    connection
                                              Figure 11: Connection String Property

    And copy the connection string and create a connection string in web.config file as shown below:
    1. <connectionStrings>  
    2.     <add name="DataModel" connectionString="Data Source=DEVELOPER-VAIO;Initial Catalog=Demos;Integrated Security=True" providerName="System.Data.SqlClient" />  
    3. </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.
    1. DataModel _context = newDataModel();  
    2. public ActionResult Index() {  
    3.     List < Employee > employees = _context.employees.ToList < Employee > ();  
    4.   
    5.     return View(employees);  
    6. }  
    7.   
    8. View  
    9.   
    10.   
    11. @model IEnumerable < DownloadPdf.Models.Employee >  
    12.     @ {  
    13.         ViewBag.Title = "Home Page";  
    14.     }  
    15.   
    16.   
    17. < div class = "row" >  
    18.     < div class = "col-md-12" >  
    19.     < div class = "h2 text-center" > Employee Details < /div> < tableclass = "table table-bordered" >  
    20.   
    21.     < thead >  
    22.     < tr >  
    23.     < td >  
    24.     Id < /td> < td >  
    25.     Name < /td> < td >  
    26.     Gender < /td> < td >  
    27.     City < /td> < td >  
    28.     Hire_Date < /td> < /tr>  
    29.   
    30. < /thead> < tbody >  
    31.   
    32.     @foreach(varempin Model)  
    33.   
    34. { < tr >  
    35.         < td > @emp.EmployeeId < /td> < td > @emp.Name < /td> < td > @emp.Gender < /td> < td > @emp.City < /td> < td > @emp.Hire_Date < /td>  
    36.   
    37.     < /tr>  
    38. } < /tbody>  
    39.   
    40. < /table>  
    41.   
    42. < /div> < divclass = "col-sm-2" >  
    43.     < divclass = "btnbtn-success" > @Html.ActionLink("Create Pdf""CreatePdf""Home") < /div>  
    44.   
    45. < /div> < /div>  
    After running the application Our View,

    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.

  2. 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:

    itext
                                              Figure 13: Installing Nuget Package Manager

    And install the same.

    Now we will see the itextsharp library added to our references.

    refrence
                         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:
    1. public FileResultCreatePdf()  
    2. {  
    3.     MemoryStreamworkStream = newMemoryStream();  
    4.     StringBuilder status = newStringBuilder("");  
    5.     DateTimedTime = DateTime.Now;  
    6.     //file name to be created   
    7.     stringstrPDFFileName = string.Format("SamplePdf" + dTime.ToString("yyyyMMdd") + "-" + ".pdf");  
    8.     Document doc = newDocument();  
    9.     doc.SetMargins(0 f, 0 f, 0 f, 0 f);  
    10.     //Create PDF Table with 5 columns  
    11.     PdfPTabletableLayout = newPdfPTable(5);  
    12.     doc.SetMargins(0 f, 0 f, 0 f, 0 f);  
    13.     //Create PDF Table  
    14.   
    15.     //file will created in this path  
    16.     stringstrAttachment = Server.MapPath("~/Downloadss/" + strPDFFileName);  
    17.   
    18.   
    19.     PdfWriter.GetInstance(doc, workStream).CloseStream = false;  
    20.     doc.Open();  
    21.   
    22.     //Add Content to PDF   
    23.     doc.Add(Add_Content_To_PDF(tableLayout));  
    24.   
    25.     // Closing the document  
    26.     doc.Close();  
    27.   
    28.     byte[] byteInfo = workStream.ToArray();  
    29.     workStream.Write(byteInfo, 0, byteInfo.Length);  
    30.     workStream.Position = 0;  
    31.   
    32.   
    33.     return File(workStream, "application/pdf", strPDFFileName);  
    34.   
    35. }  
    36.   
    37. protected PdfPTableAdd_Content_To_PDF(PdfPTabletableLayout)  
    38. {  
    39.   
    40.         float[] headers = {50,24,45,35,50}; //Header Widths  
    41.         tableLayout.SetWidths(headers); //Set the pdf headers  
    42.         tableLayout.WidthPercentage = 100; //Set the PDF File witdh percentage  
    43.         tableLayout.HeaderRows = 1;  
    44.         //Add Title to the PDF file at the top  
    45.   
    46.         List < Employee > employees = _context.employees.ToList < Employee > ();  
    47.   
    48.   
    49.   
    50.         tableLayout.AddCell(newPdfPCell(newPhrase("Creating Pdf using ItextSharp", newFont(Font.FontFamily.HELVETICA, 8, 1, newiTextSharp.text.BaseColor(0, 0, 0)))) {  
    51.             Colspan = 12, Border = 0, PaddingBottom = 5, HorizontalAlignment = Element.ALIGN_CENTER  
    52.         });  
    53.   
    54.   
    55.         ////Add header  
    56.         AddCellToHeader(tableLayout, "EmployeeId");  
    57.         AddCellToHeader(tableLayout, "Name");  
    58.         AddCellToHeader(tableLayout, "Gender");  
    59.         AddCellToHeader(tableLayout, "City");  
    60.         AddCellToHeader(tableLayout, "Hire Date");  
    61.   
    62.         ////Add body  
    63.   
    64.         foreach(varempin employees)   
    65.         {  
    66.   
    67.             AddCellToBody(tableLayout, emp.EmployeeId.ToString());  
    68.             AddCellToBody(tableLayout, emp.Name);  
    69.             AddCellToBody(tableLayout, emp.Gender);  
    70.             AddCellToBody(tableLayout, emp.City);  
    71.             AddCellToBody(tableLayout, emp.Hire_Date.ToString());  
    72.   
    73.         }  
    74.   
    75.         returntableLayout;  
    76.     }  
    77.     // Method to add single cell to the Header  
    78. private static void AddCellToHeader(PdfPTabletableLayout, stringcellText)  
    79. {  
    80.   
    81.     tableLayout.AddCell(newPdfPCell(newPhrase(cellText, newFont(Font.FontFamily.HELVETICA, 8, 1, iTextSharp.text.BaseColor.YELLOW)))  
    82.     {  
    83.         HorizontalAlignment = Element.ALIGN_LEFT, Padding = 5, BackgroundColor = newiTextSharp.text.BaseColor(128, 0, 0)  
    84.     });  
    85. }  
    86.   
    87. // Method to add single cell to the body  
    88. private static voidAddCellToBody(PdfPTabletableLayout, stringcellText)  
    89. {  
    90.     tableLayout.AddCell(newPdfPCell(newPhrase(cellText, newFont(Font.FontFamily.HELVETICA, 8, 1, iTextSharp.text.BaseColor.BLACK)))  
    91.      {  
    92.         HorizontalAlignment = Element.ALIGN_LEFT, Padding = 5, BackgroundColor = newiTextSharp.text.BaseColor(255, 255, 255)  
    93.     });  
    94. }  
    Now let’s run our Application and check whether pdf is getting generated or not?

    view
                                                                Figure 16: View

    Once User click on Generate Pdf. Pdf gets generated successfully as shown below.

    download
                                                          Figure 17: PDF Generation

    Now once we open the pdf we will see our records displayed in table format as shown below:

    chrome
                                                  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:

Up Next
    Ebook Download
    View all
    Learn
    View all