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.
Giri PanickerPosted Feb 24, 2023, 9:28 PM
Worked, thanks for the help Amit.
Benyamin DashtestaniPosted Nov 23, 2021, 3:24 PM
HI Thanks it worked great but how to make it support UTF-8 to print Persian text Too?
Krzysztof PiechPosted Sep 7, 2021, 10:11 AM
Hi. First sorry for my english ;) . How to set a landscape page ( the A4_Landscape page size doesn't work ). And how to change font size, or do something like autofit font size to cell width ?
Langat WeslyPosted Aug 8, 2021, 7:52 AM
Am getting this error,,,, Error:object reference not set to an instance of an object.
Kumaresh ALAGAPPAPILLAIPosted Apr 9, 2021, 3:59 PM
How to not show DataGridView table header when export to pdf using iTextSharp.
Harrold LeePosted Feb 16, 2021, 11:29 AM
How to Exclude the First Column while exporting? Thank you in advance
Ulury GoncalvesPosted Nov 12, 2020, 8:16 AM
I am using the same code, but i am getting some exception; "System.NullReferenceException: 'Refer?ncia de objeto n?o definida para uma inst?ncia de um objeto.'System.Windows.Forms.DataGridViewCell.Value.get returned null." this exception doesn't even make any sense to me
Brian.KiserPosted Oct 1, 2020, 7:51 AM
I'm getting an error on line 48: Non-invocable member 'Document' cannot be used like a method. It's happening on the second half of the assignment statement.
Sumonto MehediPosted Feb 20, 2020, 1:16 AM
If another image column exist on this table- is it possible to convert all images also?
Abubakr MahdiPosted Aug 8, 2019, 12:22 AM
Good article.
Pankajkumar PatelPosted Aug 5, 2019, 1:47 AM
Nice article