I will Explain You how to create PDF from Gridview.
Try to create a gridview that display in left
Then Click Event of both button
protected void btnGeneratePDF_Click(object sender, EventArgs e)
{
int columnCount = GridView1.Columns.Count;
int rowCount = GridView1.Rows.Count;
Document Doc = new Document();
PdfPTable grdTable = new PdfPTable(columnCount);
grdTable.AddCell("FirstName");
grdTable.AddCell("LastName");
for (int rowCounter = 0; rowCounter < rowCount; rowCounter++)
{
for (int columnCounter = 0; columnCounter < columnCount; columnCounter++)
{
string strValue = GridView1.Rows[rowCounter].Cells[columnCounter].Text;
grdTable.AddCell(strValue);
}
}
PdfWriter.GetInstance(Doc, new FileStream(Request.PhysicalApplicationPath + "/pdf/Name.pdf", FileMode.Create));
Doc.Open();
Doc.Add(new Paragraph("Student Information"));
Doc.Add(new Paragraph("\n"));
Doc.Add(grdTable);
Doc.Close();
grdTable.SpacingBefore = 15f;
}
protected void PDF_Click(object sender, EventArgs e)
{
PdfPTable table = new PdfPTable(gvdetails.Columns.Count);
int[] widths = new int[gvdetails.Columns.Count];
for (int x = 0; x < gvdetails.Columns.Count; x++)
{
// widths[x] = (int)gvdetails.Columns[x].ItemStyle.Width.Value;
string cellText = Server.HtmlEncode(gvdetails.Columns[x].HeaderText);
PdfPCell cell = new PdfPCell(new Phrase(cellText));
cell.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#EFF3FB"));
table.AddCell(cell);
}
// table.SetWidths(widths);
for (int i = 0; i < gvdetails.Rows.Count; i++)
{
if (gvdetails.Rows[i].RowType == DataControlRowType.DataRow)
{
for (int j = 0; j < gvdetails.Columns.Count; j++)
{
string cellText = gvdetails.Rows[i].Cells[j].Text;
PdfPCell cell = new PdfPCell(new Phrase(cellText));
if (i % 2 != 0)
{
cell.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#D1DDF1"));
}
table.AddCell(cell);
}
}
}
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
PdfWriter.GetInstance(pdfDoc, new FileStream(Request.PhysicalApplicationPath + "/pdf/data.pdf", FileMode.Create));
pdfDoc.Open();
pdfDoc.Add(new Paragraph("Student Information"));
pdfDoc.Add(new Paragraph("\n\n"));
pdfDoc.Add(table);
pdfDoc.Close();
table.SpacingBefore = 15f;
Response.End();
}
Both button have the same functionality but the different in second button is that I created the colorful gridview in PDF
0 comments:
Post a Comment