3
Answers

Export data in pdf in window application

Sir
 
i am sharing export datagridview to pdf code and datagridview structure also
now i want last two column not print like edit or print only convert required column
that how to do  
 
all colum 8 but two is edit or print so i dont want print or export last two print or edit please  
 
 
if (result == DialogResult.Yes)
{
SaveFileDialog savefile = new SaveFileDialog();
// set a default file name
savefile.FileName = "PO.pdf";
// set filters - this can be done in properties as well
savefile.Filter = "Text files (*.pdf)|*.pdf|All files (*.*)|*.*";
if (savefile.ShowDialog() == DialogResult.OK)
{
//Creating iTextSharp Table from the DataTable data
PdfPTable pdfTable = new PdfPTable(dtgrdvwsalepo.ColumnCount);
pdfTable.DefaultCell.Padding = 4;
pdfTable.WidthPercentage = 100;
pdfTable.HorizontalAlignment = Element.ALIGN_MIDDLE;
pdfTable.DefaultCell.BorderWidth = 1;
// Adding Header row
foreach (DataGridViewColumn column in dtgrdvwsalepo.Columns)
{
PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText));
cell.BackgroundColor = new iTextSharp.text.Color(240, 240, 240);
pdfTable.AddCell(cell);
}
//Adding DataRow
foreach (DataGridViewRow row in dtgrdvwsalepo.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
pdfTable.AddCell(cell.Value.ToString());
}
}
//Exporting to PDF
using (FileStream stream = new FileStream(savefile.FileName, FileMode.Create))
{
Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 0f);
PdfWriter.GetInstance(pdfDoc, stream);
pdfDoc.Open();
pdfDoc.Add(pdfTable);
pdfDoc.Close();
stream.Close();
}
MessageBox.Show("Your pdf generated successfully!");
}
 

Attachment: scrrenshot.rar

Answers (3)

1
Photo of Amit Gupta
NA 22.9k 248.1k 8y
Hey Jitendra,
Make some changes as below:
1. 
  1. DataTable data  
  2. PdfPTable pdfTable = new PdfPTable(dtgrdvwsalepo.ColumnCount -2 );  
 2. Replacing foreach with for loop
  1. // Adding Header row
  2. //foreach (DataGridViewColumn column in dtgrdvwsalepo.Columns)
  3. for (int x =0; x < dtgrdvwsalepo.Columns.Count-2; x++)
  4. {
  5. DataGridViewColumn column = dtgrdvwsalepo.Columns[x];
  6. PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText));
 3. One more change
  1. //Adding DataRow  
  2. foreach (DataGridViewRow row in dtgrdvwsalepo.Rows)  
  3. {  
  4. //foreach (DataGridViewCell cell in row.Cells)  
  5. for (int i =0; i < row.Cells.Count-2; i++)  
  6. {  
  7. DataGridViewCell cell = row.Cells [i];  
  8. pdfTable.AddCell(cell.Value.ToString());  
  9. }  
 I think thats all you have to do.
 
 Apart from this, I prefer to use ReportViewer, just need to design once and can be exported to pdf, xls and more but till I am unaware of your requirement, you can use as per your need.
1
Photo of Amit Gupta
NA 22.9k 248.1k 8y
You can use for loop instead of foreach by just putting columns.count-2 as its condition. Thats it
0
Photo of Jitendra Sharma
NA 469 29.5k 8y
but how to used .. will u explain with code....