Saturday, 12 July 2014

export Datagridview data to pdf in windows form application using c#




Description:-

In this example we explain that  how to export DataGridView data to PDF file in Windows Forms (WinForms) Applications using iTextSharp PDF conversion library usiong  C#.

DataGridView cannot provide facility to export Griddata directally to pdf and so that we have to use one .dll file and give reference to your project and use the functionality export to pdf in table format by using the iTextSharp.dll Table for this solution.
to show Example of how to Redirect to another aspx page in javascript click here Redirect to another aspx page in javascript

to show example of how to create timer or display clock in javascript click here create timer or display clock in javascript


To export Datagrid data or row to pdf format first download the iTextSharp.dll and the use it in your project.here below is code to export Datagridview data to pdf with table format and Company logo or image logo with header footer in pdf writing data.


 Code For Export to Pdf:-

//function for pass data to this function as a datareader and its display in pdf table format
private void GenerateBillAndExport(SqlDataReader Reader)
        {
            if (Reader.HasRows)
            {
                if (Reader.Read())
                {
                    PdfPTable PdfPTable  = new PdfPTable (3);
                    PdfPTable .DefaultCell.Padding = 3;
                    PdfPTable .WidthPercentage = 100;
                    PdfPTable .HorizontalAlignment = Element.ALIGN_LEFT;
                    PdfPTable .DefaultCell.BorderWidth = 1;
                
                    PdfPTable .AddCell(new PdfPCell (iTextSharp.text.Image.GetInstance("D://logo.jpg")) { Border = 0 });
                    PdfPTable .AddCell(new PdfPCell (new Phrase("Name: " + Reader[4].ToString())) { Border = 0 });
                    PdfPTable .AddCell(new PdfPCell (new Phrase("Date :" + DateTime.Now.ToShortDateString())) { Border = 0 });
                

                    PdfPTable .AddCell(new PdfPCell (new Phrase("CarName")) { BackgroundColor = iTextSharp.text.BaseColor.GRAY });
                    PdfPTable .AddCell(new PdfPCell (new Phrase("Detail")) { BackgroundColor = iTextSharp.text.BaseColor.GRAY });
                    PdfPTable .AddCell(new PdfPCell (new Phrase("Total")) { BackgroundColor = iTextSharp.text.BaseColor.GRAY });



                    PdfPTable .AddCell(Reader[2].ToString());
                    PdfPTable .AddCell(Reader[6].ToString());
                    PdfPTable .AddCell(Reader[7].ToString());
               
                    //add blank row
                    iTextSharp.text.pdf.PdfPCell  c1 = new iTextSharp.text.pdf.PdfPCell (new Phrase(" "));
                    iTextSharp.text.pdf.PdfPCell  c2 = new iTextSharp.text.pdf.PdfPCell (new Phrase(" "));
                    iTextSharp.text.pdf.PdfPCell  c3 = new iTextSharp.text.pdf.PdfPCell (new Phrase(" "));
                    PdfPTable .AddCell(c1);
                    PdfPTable .AddCell(c2);
                    PdfPTable .AddCell(c3);
                
                    //Add Footer row
                    PdfPTable .AddCell(new PdfPCell (new Phrase("Name:- Viajy Babariya" + Environment.NewLine + "Contact No:- 9978718797")) { BackgroundColor = iTextSharp.text.BaseColor.LIGHT_GRAY });
                    PdfPTable .AddCell(new PdfPCell (new Phrase("")));
                    PdfPTable .AddCell(new PdfPCell (new Phrase("Name:- Viajy Babariya" + Environment.NewLine + "Contact No:- 9978718797")) { BackgroundColor = iTextSharp.text.BaseColor.LIGHT_GRAY });
                   
                
                    //Exporting to PDF
                    string folderPath = "D:\\PDFs\\";
                    if (!Directory.Exists(folderPath))
                    {
                        Directory.CreateDirectory(folderPath);
                    }
                    using (FileStream stream = new FileStream(folderPath + Reader.GetValue(4) + "_" + DateTime.Now.ToShortDateString() + ".pdf", FileMode.Create))
                    {
                        Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 0f);
                        PdfWriter.GetInstance(pdfDoc, stream);
                       
                        pdfDoc.Open();
                        pdfDoc.Add(PdfPTable );
                        pdfDoc.Close();
                        stream.Close();
                        System.Diagnostics.Process.Start(folderPath + Reader.GetValue(4) + "_" + DateTime.Now.ToShortDateString() + ".pdf");
                       
                    }
            
                }

            }

        }







private void cardetail_Load(object sender, EventArgs e)
        {

            dataGridView2.DataSource = binddata();
            dataGridView2.AutoGenerateColumns = false;
            dataGridView2.AllowUserToAddRows = false;


           

            DataGridViewLinkColumn Editlink = new DataGridViewLinkColumn();
            Editlink.UseColumnTextForLinkValue = true;
            Editlink.HeaderText = "Edit";
            Editlink.DataPropertyName = "lnkColumn";
            Editlink.LinkBehavior = LinkBehavior.SystemDefault;
            Editlink.Text = "Edit";

            dataGridView2.Columns.Add(Editlink);
            DataGridViewLinkColumn Deletelink = new DataGridViewLinkColumn();
            Deletelink.UseColumnTextForLinkValue = true; Deletelink.HeaderText = "delete";
            Deletelink.DataPropertyName = "lnkColumn";
            Deletelink.LinkBehavior = LinkBehavior.SystemDefault;
            Deletelink.Text = "Delete";
            dataGridView2.Columns.Add(Deletelink);

            DataGridViewLinkColumn Printlink = new DataGridViewLinkColumn();
            Printlink.UseColumnTextForLinkValue = true; Deletelink.HeaderText = "Export to pdf";
            Printlink.DataPropertyName = "lnkColumn";
            Printlink.LinkBehavior = LinkBehavior.SystemDefault;
            Printlink.Text = "Export to pdf";
            dataGridView2.Columns.Add(Printlink);

        }

//Binding Gridview


public void binddata()
        {
            DataTable dt = new DataTable();
            string query = "select * from cardetail";

            SqlCommand cmd = new SqlCommand(query, cn);
            SqlDataAdapter sa = new SqlDataAdapter();
            sa.SelectCommand = cmd;

            cn.Open();
            cmd.ExecuteNonQuery();
            sa.Fill(dt);
            dataGridView2.DataSource = dt;
            dataGridView2.AutoGenerateColumns = false;
            dataGridView2.AllowUserToAddRows = false;

            cn.Close();




        }

//Edit Delete Event


private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            SqlCommand cmd;
            SqlCommand Command;
            SqlDataReader Reader;
            try
            {
                empid = Convert.ToInt32(dataGridView2.Rows[e.RowIndex].Cells["id"].Value);
                switch (e.ColumnIndex)
                {
                    case 9:
                        cn.Open();
                        Command = new SqlCommand("Select * from cardetail where id='" + empid +"'", cn);
                        Reader = Command.ExecuteReader();
                        if (Reader.HasRows)
                        {
                            if (Reader.Read())
                            {
                                textBox8.Text = Reader.GetValue(1).ToString();

                                textBox9.Text = Reader.GetValue(2).ToString();
                                textBox10.Text = Reader.GetValue(3).ToString();
                                textBox11.Text = Reader.GetValue(4).ToString();
                                textBox12.Text = Reader.GetValue(5).ToString();
                                textBox13.Text = Reader.GetValue(6).ToString();
                                textBox14.Text = Reader.GetValue(7).ToString();
                                button4.Visible = true;
                                button3.Visible = false;
                            }

                        }
                        cn.Close();
                        break;

                    case 10:
                        cn.Open();
                        cmd = new SqlCommand("delete from cardetail where id = '" + empid + "'", cn);
                        cmd.ExecuteNonQuery();
                        cn.Close();
                        MessageBox.Show("Deleted Successfully.....");
                         binddata();
                      
                        break;
                    case 11:
                        cn.Open();

                        Command = new SqlCommand("Select * from cardetail where id='" + empid +"'", cn);
                        Reader = Command.ExecuteReader();
                        GenerateBillAndExport(Reader);
                        cn.Close();


                        break;
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


//Update Button Click


private void button4_Click(object sender, EventArgs e)
        {

            string a = DateTime.Now.ToShortDateString();
            string query = "update cardetail set carno='" + textBox8.Text + "',carname='" + textBox9.Text + "',address='" + textBox10.Text + "',personname='" + textBox11.Text +"',cellno='" + textBox12.Text + "',detail='" + textBox13.Text + "',total='" +Convert.ToDouble(textBox14.Text) + "' where id='" + empid + "'";

            SqlCommand cmd = new SqlCommand(query, cn);
            cn.Open();
            cmd.ExecuteNonQuery();
            MessageBox.Show("Record Updates Successfully.....");
            cn.Close();
            clear();
            binddata();
          
 button3.Visible = true;
            button4.Visible = false;

        }

3 comments:

  1. Great information …..Very helpful .. there are various tools also available online to convert html to pdf. Expert PDF is one of best software i used for converting html to pdf asp.net.You can check all details at their site

    http://www.html-to-pdf.net/html-to-pdf-aspdotnet.aspx

    ReplyDelete
    Replies
    1. Thanks for comment and touch with this blog for new update post..

      Delete
  2. Thanks for sharing! I am also using this ZetPDf.com platform that has the fastest pdf solutions for .net applications.

    ReplyDelete