Search This Blog

Friday 26 June 2015

Export dataset to pdf using itextsharp Or export datatable to pdf using itextsharp in asp.net Or export datatable to pdf using c# Or export datatable to pdf in asp.net

Step 1:- Download itextsharp.dll

Step 2:- Create Project

Step 3:- After creating project Right click References folder -> click on Add References... -> Browse file and click add  -> click OK

Step 4:- (Default.aspx)

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Demo.CreatePdf" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Button ID="Button1" runat="server" Text="Create & Download Pdf" OnClick="Button1_Click" />
        </div>
    </form>
</body>
</html>

Step 5:- (Default.aspx.cs)

using System;
using System.Data;
using System.IO;
using System.Web.UI;
using iTextSharp.text.pdf;
using iTextSharp.text;

namespace Demo
{
    public partial class Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            DataSet ds = new DataSet();

            ds.ReadXml(Server.MapPath("\\") + "breakfast_menu.xml");

            if (ds.Tables[0].Rows.Count > 0)
            {
                int pdfRowIndex = 1;

                string filename = "Pdf-" + DateTime.Now.ToString("dd-MM-yyyy hh_mm_s_tt");

                string filepath = Server.MapPath("\\") + "" + filename + ".pdf";

                Document document = new Document(PageSize.A4, 5f, 5f, 10f, 10f);

                FileStream fs = new FileStream(filepath, FileMode.Create);

                PdfWriter writer = PdfWriter.GetInstance(document, fs);

                document.Open();

                Image img = Image.GetInstance(Server.MapPath("Images\\") + "food-and-water-1.jpg");
               
                document.Add(img);

                Font font1 = FontFactory.GetFont(FontFactory.COURIER_BOLD, 10);
                Font font2 = FontFactory.GetFont(FontFactory.COURIER, 8);

                //This is used for formatting the each column with their respective data (record) size.
                //In our example data set containing 4 columns, so I used it 4 different sizes to format each column.
                //If your data contains more columns you can add the same number of parameters in it to format each column.
                float[] columnDefinitionSize = { 5F, 2F, 7F, 2F };

                //This is used for Add A Paragraph to pdf
                Paragraph paragraph1 = new Paragraph();
                Paragraph paragraph2 = new Paragraph();
                paragraph1.Add("Breakfast Menu List");
                paragraph1.Alignment = Element.ALIGN_CENTER;
                paragraph2.Add(" ");
                paragraph2.Alignment = Element.ALIGN_CENTER;
                document.Add(paragraph1);
                document.Add(paragraph2);

                PdfPTable table;
                PdfPCell cell;

                table = new PdfPTable(columnDefinitionSize);
                table.WidthPercentage = 100;

                cell = new PdfPCell();

                cell.BackgroundColor = new BaseColor(0xC0, 0xC0, 0xC0);

                /*Create table Column Name Here*/
                table.AddCell(new Phrase("Name", font1));
                table.AddCell(new Phrase("Price", font1));
                table.AddCell(new Phrase("Description", font1));
                table.AddCell(new Phrase("Calories", font1));

                //OR

                /*You can use loop to add a column*/
                //for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
                //{
                //    string columnName = ds.Tables[0].Columns[i].ToString();

                //    table.AddCell(new Phrase(columnName, font1));
                //}

                //This Line Help to Repeat Header in Each Page of Pdf
                table.HeaderRows = 1;

                //Fill Data in Rows of table in PDF
                foreach (DataRow data in ds.Tables[0].Rows)
                {
                    table.AddCell(new Phrase(data["Name"].ToString(), font2));
                    table.AddCell(new Phrase(data["Price"].ToString(), font2));
                    table.AddCell(new Phrase(data["Description"].ToString(), font2));
                    table.AddCell(new Phrase(data["Calories"].ToString(), font2));

                    pdfRowIndex++;
                }

                document.Add(table);
                document.Close();
                document.CloseDocument();
                document.Dispose();
                writer.Close();
                writer.Dispose();
                fs.Close();
                fs.Dispose();

                //Code for download the file
                FileStream sourceFile = new FileStream(filepath, FileMode.Open);
                float fileSize = 0;
                fileSize = sourceFile.Length;
                byte[] getContent = new byte[Convert.ToInt32(Math.Truncate(fileSize))];
                sourceFile.Read(getContent, 0, Convert.ToInt32(sourceFile.Length));
                sourceFile.Close();
                Response.ClearContent();
                Response.ClearHeaders();
                Response.Buffer = true;
                Response.ContentType = "application/pdf";
                Response.AddHeader("Content-Length", getContent.Length.ToString());
                Response.AddHeader("Content-Disposition""attachment; filename=" + filename + ".pdf;");
                Response.BinaryWrite(getContent);
                Response.Flush();
                File.Delete(filepath);
                Response.End();
            }
        }
    }
}

Example:-