How to Export DataGridView Data to pdf file using C#

Spread the love
Export data to pdg

How to export DataGridView data to a pdf file and save using C#

We will learn how to export DataGridView data to a pdf file and save it using C# code in this example.

Export data to pdg

Step 1

Export data to pdg

Step 2

Export data to pdg

On Button Click Event add the Code below

private void button1_Click(object sender, EventArgs e) {

if (dataGridView1.Rows.Count>0)

{

SaveFileDialog save = new SaveFileDialog();

save.Filter = "PDF (*.pdf)|*.pdf";

save.FileName = "Result.pdf";

bool ErrorMessage = false;

if (save.ShowDialog()==DialogResult.OK)

{

if (File.Exists(save.FileName))

{

try

{

File.Delete(save.FileName);

}

catch (Exception ex)

{

ErrorMessage = true;

MessageBox.Show("Unable to wride data in disk"+ex.Message);

}

}

if (!ErrorMessage)

{

try

{

PdfPTable pTable = new PdfPTable(dataGridView1.Columns.Count);

pTable.DefaultCell.Padding = 2;

pTable.WidthPercentage = 100;

pTable.HorizontalAlignment = Element.ALIGN_LEFT;

foreach (DataGridViewColumn col in dataGridView1.Columns)

{

PdfPCell pCell = new PdfPCell(new Phrase(col.HeaderText));

pTable.AddCell(pCell);

}

foreach (DataGridViewRow viewRow in dataGridView1.Rows)

{

foreach (DataGridViewCell dcell in viewRow.Cells)

{

pTable.AddCell(dcell.Value.ToString());

}

}

using (FileStream fileStream=new FileStream(save.FileName,FileMode.Create))

{

Document document = new Document(PageSize.A4,8f,16f,16f,8f);

PdfWriter.GetInstance(document, fileStream);

document.Open();

document.Add(pTable);

document.Close();

fileStream.Close();

}

MessageBox.Show("Data Export Successfully","info");

}

catch (Exception ex)

{

MessageBox.Show("Error while exporting Data"+ex.Message);

}

}

}

}

else

{

MessageBox.Show("No Record Found","Info");

}

}
Video tutorial ​

Thank you for visit. Please don’t forget to subscribe our official YouTube Channel RashiCode

Leave a Reply

Your email address will not be published.