Hi everyone ,
I want to export datagridview to PDF file,After generating the pdf I'm not able to open that file..when i try to open it shows file corrupted error message and also not getting "Pdf Generation successfully " Message.
Here is my code :
private void btnExportPdf_Click(string heading, string filename)
{
try
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "All Files | *.* ";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
string path = saveFileDialog.FileName;
Document pdfdoc = new Document(PageSize.A4); // Setting the page size for the PDF
PdfWriter writer = PdfWriter.GetInstance(pdfdoc, new FileStream(path + ".pdf", FileMode.Create)); //Using the PDF Writer class to generate the PDF
writer.PageEvent = new PDFFooter();
// Opening the PDF to write the data from the textbox
PdfPTable table = new PdfPTable(dataGridView1.Columns.Count);
//table.TotalWidth = GridView.Width;
float[] widths = new float[]
{
dataGridView1.Columns[0].Width, dataGridView1.Columns[1].Width, dataGridView1.Columns[2].Width
};
table.SetWidths(widths);
table.HorizontalAlignment = 1; // 0 - left, 1 - center, 2 - right;
table.SpacingBefore = 2.0F;
PdfPCell cell = null;
pdfdoc.Open();
//doc.Open();
// Phrase p = new Phrase(new Chunk(heading, titleFont));
// doc.Add(p);
foreach (DataGridViewColumn c in dataGridView1.Columns)
{
cell = new PdfPCell(new Phrase(new Chunk(c.HeaderText)));
cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
table.AddCell(cell);
}
if (dataGridView1.Rows.Count > 0)
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
PdfPCell[] objcell = new PdfPCell[dataGridView1.Columns.Count];
for (int j = 0; j < dataGridView1.Columns.Count - 1; j++)
{
cell = new PdfPCell(new Phrase(dataGridView1.Rows[i].Cells[j].Value.ToString()));
cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
table.AddCell(cell);
//lstCells.Add(cell);
objcell[j] = cell;
}
PdfPRow newrow = new PdfPRow(objcell);
table.Rows.Add(newrow);
}
}
pdfdoc.Add(table);
MessageBox.Show("Pdf Generation Successfully.");
pdfdoc.Close();
}
}
catch (Exception ex)
{
MessageBox.Show("Error in pdf Generation.");
}
}