Create A PDF File And Download Using ASP.NET MVC

Abstract

This is a tip for creating PDFs 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 the database as shown below step by step.

Create New Project

Web app

Figure 1. New Project in VS 2015

Select the MVC Template for creating a WEB Application as shown below

MVC Template

Figure 2. Selecting MVC Template

Here I will use 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 in the PDF file?

I will be showing Employee details to the User as shown below in the snapshot.

Information

Figure 3. Information to be shown in pdf

Creating your Models

Now we will create a Model class named Employee as shown below.

Model Class

Figure 4. Creating Model Class

Model

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 that will act as DataModel for this project.

DBContextDataModel

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(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Employee>().ToTable("tblEmployee");
        }

    }
}

Adding the connection string

Go to Server Explorer.

Server Explorer

Figure 7. Server Explorer window

Click on Data Connections and add a new connection.

 Data Connection

Figure 8. Adding Data Connection in asp.net MVC

 DB

Figure 9. Selecting your db

Select your server name and enter your database name. Click on ok to confirm.

Right-click on the newly created connection.

 Properties

Figure 10. Checking Properties of New Data Connection

Go to properties.

Figure 11. Connection String Property

Copy the connection string and create a connection string in the 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 the connection string with the same name as your DataModel. Here I will use the default Home controller and show the details from the table in the view.

DataModel _context = new DataModel();
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>
        <table class="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(var emp in 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>
    <div class="col-sm-2">
        <div class="btn btn-success">@Html.ActionLink("Create Pdf", "CreatePdf", "Home")</div>
    </div>
</div>

After running the application Our View.

Employee Details

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.

Package Manager

Figure 13. Installing Nuget Package Manager

And install the same.

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

ItextSharpdll

Figure 14. Demonstrating the Addition of ItextSharpdll in references

Now let’s start creating our method for pdf creation.

In MVC we have several Action Results egPartialViewResult, Content, JavaScript Result, EmptyResult, Redirect Result, etc. We will be using FileResult which is used to send binary file content to the response.

Let's get started.

public FileResult CreatePdf()
{
    MemoryStream workStream = new MemoryStream();
    StringBuilder status = new StringBuilder("");
    DateTime dTime = DateTime.Now;
    // file name to be created   
    string strPDFFileName = string.Format("SamplePdf" + dTime.ToString("yyyyMMdd") + "-" + ".pdf");
    Document doc = new Document();
    doc.SetMargins(0f, 0f, 0f, 0f);
    // Create PDF Table with 5 columns   
    PdfPTable tableLayout = new PdfPTable(5);
    doc.SetMargins(0f, 0f, 0f, 0f);
    // Create PDF Table    
    // file will created in this path   
    string strAttachment = Server.MapPath("~/Downloadss/" + strPDFFileName);
    PdfWriter.GetInstance(doc, workStream).CloseStream = false;
    doc.Open();
    // Add Content to PDF    
    doc.Add(Add_Content_To_PDF(tableLayout));
    // Closing the document   
    doc.Close();
    byte[] byteInfo = workStream.ToArray();
    workStream.Write(byteInfo, 0, byteInfo.Length);
    workStream.Position = 0; 
    return File(workStream, "application/pdf", strPDFFileName);
}
protected PdfPTable Add_Content_To_PDF(PdfPTable tableLayout)
{
    float[] headers = { 50, 24, 45, 35, 50 }; // Header Widths   
    tableLayout.SetWidths(headers); // Set the pdf headers   
    tableLayout.WidthPercentage = 100; // Set the PDF File witdh percentage   
    tableLayout.HeaderRows = 1;
    // Add Title to the PDF file at the top   
    List<Employee> employees = _context.employees.ToList<Employee>();
    tableLayout.AddCell(new PdfPCell(new Phrase("Creating Pdf using ItextSharp", new Font(Font.FontFamily.HELVETICA, 8, 1, new iTextSharp.text.BaseColor(0, 0, 0))))
    {
        Colspan = 12,
        Border = 0,
        PaddingBottom = 5,
        HorizontalAlignment = Element.ALIGN_CENTER
    });
    //// Add header   
    AddCellToHeader(tableLayout, "EmployeeId");
    AddCellToHeader(tableLayout, "Name");
    AddCellToHeader(tableLayout, "Gender");
    AddCellToHeader(tableLayout, "City");
    AddCellToHeader(tableLayout, "Hire Date");
    //// Add body   
    foreach (var emp in employees)
    {

        AddCellToBody(tableLayout, emp.EmployeeId.ToString());
        AddCellToBody(tableLayout, emp.Name);
        AddCellToBody(tableLayout, emp.Gender);
        AddCellToBody(tableLayout, emp.City);
        AddCellToBody(tableLayout, emp.Hire_Date.ToString());
    }
    return tableLayout;
}
// Method to add single cell to the Header   
private static void AddCellToHeader(PdfPTable tableLayout, string cellText)
{

    tableLayout.AddCell(new PdfPCell(new Phrase(cellText, new Font(Font.FontFamily.HELVETICA, 8, 1, iTextSharp.text.BaseColor.YELLOW)))
    {
        HorizontalAlignment = Element.ALIGN_LEFT,
        Padding = 5,
        BackgroundColor = new iTextSharp.text.BaseColor(128, 0, 0)
    });
}
// Method to add single cell to the body   
private static void AddCellToBody(PdfPTable tableLayout, string cellText)
{
    tableLayout.AddCell(new PdfPCell(new Phrase(cellText, new Font(Font.FontFamily.HELVETICA, 8, 1, iTextSharp.text.BaseColor.BLACK)))
    {
        HorizontalAlignment = Element.ALIGN_LEFT,
        Padding = 5,
        BackgroundColor = new iTextSharp.text.BaseColor(255, 255, 255)
    });
}

Now let’s run our Application and check whether the pdf is getting generated or not.

View

Figure 15. View

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

PDF Generation

Figure 16. PDF Generation

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

Google Chrome

Figure 17. PDF View in Google Chrome

Hence I want to commence this code snippet tip for creating PDF files 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.


Similar Articles