In this code example, we will learn how to export DataGridView data to a pdf file and save that in a folder using C# code.
In this program, first, we have to get connected to the database and fetch data from the DB and show it in the Data GridView like the below image.
Before we go to the coding section, we must add iTextSharp library reference to our project.
To do that, right-click on the project and select "Manage NuGet Package" menu. After that go to the "Browse" tab and search for iTextSharp and install it.
Project --> Manage NuGet Package --> Browse tab --> Search iTextSharp; then install.
Now, go to the page load event, fetch employee data and bind to the data GridView.
- private void FrmExport_Load(object sender, EventArgs e)
- {
- SqlConnection sqlCon;
- string conString = null;
- string sqlQuery = null;
-
- conString = "Data Source=.;Initial Catalog=DemoTest;Integrated Security=SSPI;";
- sqlCon = new SqlConnection(conString);
- sqlCon.Open();
- sqlQuery = "SELECT * FROM tblEmployee";
- SqlDataAdapter dscmd = new SqlDataAdapter(sqlQuery, sqlCon);
- DataTable dtData = new DataTable();
- dscmd.Fill(dtData);
- dataGridView1.DataSource = dtData;
- }
Then, on the buttonclick event handler, we have to create a PdfTable object and document, get data from DataGridView, and add rows and columns to the document.
- private void btnPdf_Click(object sender, EventArgs e)
- {
- if (dataGridView1.Rows.Count > 0)
- {
- SaveFileDialog sfd = new SaveFileDialog();
- sfd.Filter = "PDF (*.pdf)|*.pdf";
- sfd.FileName = "Output.pdf";
- bool fileError = false;
- if (sfd.ShowDialog() == DialogResult.OK)
- {
- if (File.Exists(sfd.FileName))
- {
- try
- {
- File.Delete(sfd.FileName);
- }
- catch (IOException ex)
- {
- fileError = true;
- MessageBox.Show("It wasn't possible to write the data to the disk." + ex.Message);
- }
- }
- if (!fileError)
- {
- try
- {
- PdfPTable pdfTable = new PdfPTable(dataGridView1.Columns.Count);
- pdfTable.DefaultCell.Padding = 3;
- pdfTable.WidthPercentage = 100;
- pdfTable.HorizontalAlignment = Element.ALIGN_LEFT;
-
- foreach (DataGridViewColumn column in dataGridView1.Columns)
- {
- PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText));
- pdfTable.AddCell(cell);
- }
-
- foreach (DataGridViewRow row in dataGridView1.Rows)
- {
- foreach (DataGridViewCell cell in row.Cells)
- {
- pdfTable.AddCell(cell.Value.ToString());
- }
- }
-
- using (FileStream stream = new FileStream(sfd.FileName, FileMode.Create))
- {
- Document pdfDoc = new Document(PageSize.A4, 10f, 20f, 20f, 10f);
- PdfWriter.GetInstance(pdfDoc, stream);
- pdfDoc.Open();
- pdfDoc.Add(pdfTable);
- pdfDoc.Close();
- stream.Close();
- }
-
- MessageBox.Show("Data Exported Successfully !!!", "Info");
- }
- catch (Exception ex)
- {
- MessageBox.Show("Error :" + ex.Message);
- }
- }
- }
- }
- else
- {
- MessageBox.Show("No Record To Export !!!", "Info");
- }
- }
Now, run the application. When we click on the "Export To Pdf" button, it will ask where to save the file. Put a file name and click on OK. It will generate a pdf file with the given name.
I hope this code will help all readers. Happy Coding.