Hello to all
Im trying to know about itextsharp, i have the next code to make a PDF from my datagrid, and it Works, but i need to add two news improvements on it and i dont know how,
first is to add the page number in the PDF before its créate,
second is to group ítems by one column and when the ítem is different show this row/rows in a new page, something like group row by colum in diferent pages.
Someone could help me with this? thanks in advance.
private void button2_Click(object sender, EventArgs e)
{
exportgridtopdf(dataGridView1, "test");
}
public void exportgridtopdf(DataGridView dataGridView1, string filename)
{
BaseFont bf = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1250, BaseFont.EMBEDDED);
PdfPTable pdftable = new PdfPTable(dataGridView1.Columns.Count);
pdftable.HeaderRows = dataGridView1.Columns.Count;
pdftable.DefaultCell.Padding = 3;
pdftable.WidthPercentage = 100;
pdftable.HorizontalAlignment = Element.ALIGN_LEFT;
pdftable.DefaultCell.BorderWidth = 1;
iTextSharp.text.Font text = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL);
foreach (DataGridViewColumn column in dataGridView1.Columns)
{
PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText,text));
cell.BackgroundColor = new iTextSharp.text.BaseColor(240, 240, 240);
pdftable.AddCell(cell);
}
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
pdftable.AddCell(new Phrase(cell.Value.ToString(), text));
}
}
var savefiledialoge = new SaveFileDialog();
savefiledialoge.FileName = filename;
savefiledialoge.DefaultExt = ".pdf";
if (savefiledialoge.ShowDialog()==DialogResult.OK)
{
using (FileStream stream = new FileStream(savefiledialoge.FileName, FileMode.Create))
{
try
{
PdfWriter writer = PdfWriter.GetInstance(pdfdoc, stream);
pdfdoc.SetPageSize(PageSize.A4.Rotate());
pdfdoc.Open();
Ehead();
pdfdoc.Add(pdftable);
pdfdoc.Close();
stream.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "error occured ", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
MessageBox.Show("Downloaded","", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
private void Ehead()
{
var parrafo = new Paragraph("WHAREHOUSES");
parrafo.SpacingBefore = 20;
parrafo.SpacingAfter = 0;
parrafo.Alignment = 1;
pdfdoc.Add(parrafo);
var parrafo3 = new Paragraph("ORDERS" Date:" + DateTime.UtcNow);
parrafo3.SpacingBefore = 1;
parrafo3.SpacingAfter = 8;
parrafo3.Alignment = 1; //0-Left, 1 middle,2 Right
pdfdoc.Add(parrafo3);
}
What I have tried:
i spend sometime with
PageEventHelper
, colspan, rowspan..but i dont find the solution...