-->

How to export database data to PDF file in ASP.NET.


Introduction

In this post I am explain how to export database data to PDF file in ASP.Net.

Here i am writing this article to explain how to export database data to PDF file in ASP.NET

Steps :

Step - 1 : Create New Project.

Go to File > New > Project > Select asp.net web forms application > Entry Application Name > Click OK.

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create table for fetch data.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.
In this example, I have used one tables as below

Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Add a Webpage and Design for Show Data in Gridview & Export to PDF

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select web form/ web form using master page under Web > Enter page name > Add.

HTML Code
              <h3>Export Database Data to PDF in ASP.NET</h3>
                <div>
                    <asp:GridView ID="gvData" runat="server" AutoGenerateColumns="false" CellPadding="5">
                        <Columns>
                            <asp:BoundField DataField="SLID" HeaderText="Sl No." />
                            <asp:BoundField DataField="Country" HeaderText="Country" />
                            <asp:BoundField DataField="State" HeaderText="State" />
                            <asp:BoundField DataField="City" HeaderText="City" />
                        </Columns>
                    </asp:GridView>
                    <div>
                        <asp:Button ID="btnExport" runat="server" Text="Export to PDF" OnClick="btnExport_Click" />
                    </div>
                </div>
        

Step-6: Write following code in Page_Load event for Show data in Gridview.


             protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    PopualteData();
                }
            }
        
Here is the function...
            private void PopualteData()
            {
                using (MyDatabaseEntities dc = new MyDatabaseEntities())
                {
                    var v = dc.CityDatas.OrderBy(a => a.Country).ThenBy(a => a.State).ThenBy(a => a.City).ToList();
                    gvData.DataSource = v;
                    gvData.DataBind();
                }
            }
        

Step-7: Add Reference (itextsharp.dll)

Right Click on references under project folder > Add Reference > Select itextsharp.dll > OK.

Step-8: Write below code in button click (btnExportPDF_Click) event for export Database data to PDF File.


             protected void btnExport_Click(object sender, EventArgs e)
            {
                // This code is for export Database data to PDF file
                string fileName = Guid.NewGuid() + ".pdf";
                string filePath = Path.Combine(Server.MapPath("~/PDFFiles"), fileName);

                Document doc = new Document(PageSize.A4, 2, 2, 2, 2);
            
                // Create paragraph for show in PDF file header
                Paragraph p = new Paragraph("Export Database data to PDF file in ASP.NET");
                p.SetAlignment("center");

                try
                {
                    PdfWriter.GetInstance(doc, new FileStream(filePath, FileMode.Create));
                    //Create table here for write database data
                    PdfPTable pdfTab = new PdfPTable(4); // here 4 is no of column
                    pdfTab.HorizontalAlignment = 1; // 0- Left, 1- Center, 2- right
                    pdfTab.SpacingBefore = 20f;
                    pdfTab.SpacingAfter = 20f;

                    List<CityData> data = new List<CityData>();
                    using (MyDatabaseEntities dc = new MyDatabaseEntities())
                    {
                        data = dc.CityDatas.OrderBy(a => a.Country).ThenBy(a => a.State).ThenBy(a => a.City).ToList();
                    }

                    pdfTab.AddCell("Sl. No.");
                    pdfTab.AddCell("Country");
                    pdfTab.AddCell("State");
                    pdfTab.AddCell("City");
                
                    foreach (var City in data)
                    {
                        pdfTab.AddCell(City.SLID.ToString());
                        pdfTab.AddCell(City.Country);
                        pdfTab.AddCell(City.State);
                        pdfTab.AddCell(City.City);
                    }
                    doc.Open();
                    doc.Add(p);
                    doc.Add(pdfTab);
                    doc.Close();

                    byte[] content = File.ReadAllBytes(filePath);
                    HttpContext context = HttpContext.Current;

                    context.Response.BinaryWrite(content);
                    context.Response.ContentType = "application/pdf";
                    context.Response.AppendHeader("Content-Disposition","attachment; filename="+fileName);
                    context.Response.End();
                }
                catch (Exception)
                {

                    throw;
                }
                finally
                {
                    doc.Close();
                }
            }
        

Step-9: Run Application.

Related Post:


Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.