Friday, February 4, 2011

DataGrid to PDF Export With proper Allignment.

Q. Query asked by one of the Programmer to Techies...?

I have a DataGrid on my Aspx page which will be bound with data during run time [from various functions consisting of different queries]. I am trying to export the data grid to a PDF using iTextSharp.dll [Version 4.0]. I am able to export but the alignment is not proper. My code looks like this:

protected void imgExportToPDF_Click(object sender, ImageClickEventArgs e)
{
try
{
HtmlForm form = new HtmlForm();
form.Controls.Add(DataGrid1);
StringWriter sw = new StringWriter();
HtmlTextWriter hTextWriter = new HtmlTextWriter(sw);
form.Controls[0].RenderControl(hTextWriter);
string html = sw.ToString();
Document Doc = new Document();

string reportName = DropDownList1..SelectedItem.Text;

//PdfWriter.GetInstance
//(Doc, new FileStream(Request.PhysicalApplicationPath
//+ "\\AmitJain.pdf", FileMode.Create));

PdfWriter.GetInstance(Doc, new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + reportName + ".pdf", FileMode.Create));
Doc.Open();



Chunk c = new Chunk(reportName + " Report \n\n", FontFactory.GetFont("Verdana", 15, iTextSharp.text.Color.BLUE));
Paragraph p = new Paragraph();
p.Alignment = Element.ALIGN_CENTER;
p.Add(c);

if (txtFromDate.Text != "" || txtToDate.Text != "")
{
Chunk chunk1 = new Chunk("Report Generated For Dates Bestween:" + txtFromDate.Text + " And " + txtToDate.Text + " Report Generated On:" + System.DateTime.Now.ToString(), FontFactory.GetFont("Verdana", 8, iTextSharp.text.Color.DARK_GRAY));
Paragraph p1 = new Paragraph();
p1.Alignment = Element.ALIGN_CENTER;
p1.Add(chunk1);
Doc.Add(p);
Doc.Add(p1);
}
else
{
Chunk chunk2 = new Chunk("Report Generated On:" + System.DateTime.Now.ToString(), FontFactory.GetFont("Verdana", 8, iTextSharp.text.Color.ORANGE));
Paragraph p2 = new Paragraph();
p2.Alignment = Element.ALIGN_CENTER;
p2.Add(chunk2);
Doc.Add(p);
Doc.Add(p2);
}


System.Xml.XmlTextReader xmlReader = new System.Xml.XmlTextReader(new StringReader(html));
HtmlParser.Parse(Doc, xmlReader);

Doc.Close();
string Path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + reportName + ".pdf";


ShowPdf(Path);



}
catch (Exception ex)
{
throw ex;
}



}

private void ShowPdf(string strS)
{
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition","attachment; filename=" + strS);
Response.TransmitFile(strS);
Response.End();
//Response.WriteFile(strS);
Response.Flush();
Response.Clear();

}

Kindly help with this issue...

Thanks in advance.
Sathya


---------------------------------------------------------
re: DataGrid to PDF Export With proper Allignment.
Nowshad M replied to Sathya on 29-Nov-10 04:52 AM
Hi,
Build your Headers and rows of PDF like this

public PdfPTable BuildRows(PdfPTable pdfTable, params string[] rowValues)
{
try
{
for (int count = 0; count < rowValues.Length; count++)
{
PdfPCell cel;
if (rowValues[count]+"" != "Fail")
cel = new PdfPCell(new Phrase(rowValues[count].ToString(), new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 9f, (int)System.Drawing.FontStyle.Regular, new iTextSharp.text.Color(System.Drawing.Color.Black))));
else
cel = new PdfPCell(new Phrase(rowValues[count].ToString(), new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 9f, (int)System.Drawing.FontStyle.Regular, new iTextSharp.text.Color(System.Drawing.Color.Red))));
cel.PaddingLeft = 10f;
cel.PaddingBottom = 4f;
cel.BorderColor = new iTextSharp.text.Color(229, 229, 229);
cel.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
pdfTable.AddCell(cel);
}
return pdfTable;
}
catch (Exception ex)
{
return pdfTable;
}
}
public void BuildPdfHeaders(PdfPTable pdfTable, string reportHeading, string reportSubHeading,int colCount, params string[] headerValues)
{
try
{
PdfPCell dateCell = new PdfPCell(new Phrase("Date : " + DateTime.Now.Date.ToString("dd/MM/yyyy") + "", new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 8f, (int)System.Drawing.FontStyle.Regular, new iTextSharp.text.Color(System.Drawing.Color.Black))));
dateCell.PaddingTop = 10f;
dateCell.Colspan = colCount;
dateCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
dateCell.Border = iTextSharp.text.Rectangle.NO_BORDER;
pdfTable.AddCell(dateCell);
PdfPCell reportHeader = new PdfPCell(new Phrase(reportHeading, new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 12f, (int)System.Drawing.FontStyle.Bold, new iTextSharp.text.Color(System.Drawing.Color.Black))));
reportHeader.PaddingTop = 0f;
reportHeader.Colspan = colCount;
reportHeader.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
reportHeader.Border = iTextSharp.text.Rectangle.NO_BORDER;
pdfTable.AddCell(reportHeader);
PdfPCell subHeader = new PdfPCell(new Phrase(reportSubHeading, new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 8f, (int)System.Drawing.FontStyle.Italic, new iTextSharp.text.Color(System.Drawing.Color.Black))));
subHeader.PaddingBottom = 10f;
subHeader.Colspan = colCount;
subHeader.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
subHeader.Border = iTextSharp.text.Rectangle.NO_BORDER;
pdfTable.AddCell(subHeader);
for (int emptyCount = 0; emptyCount < colCount*2; emptyCount++)
{
PdfPCell emptyCel = new PdfPCell(new Phrase(""));
emptyCel.PaddingBottom = 10f;
emptyCel.Border = iTextSharp.text.Rectangle.NO_BORDER;
pdfTable.AddCell(emptyCel);
}
for (int count = 0; count < headerValues.Length; count++)
{
PdfPCell header = new PdfPCell(new Phrase(headerValues[count].ToString(), new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 10f, (int)System.Drawing.FontStyle.Regular, new iTextSharp.text.Color(System.Drawing.Color.Black))));
header.PaddingBottom = 5f;
header.BorderColor = new iTextSharp.text.Color(229, 229, 229);
header.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
header.BackgroundColor = new iTextSharp.text.Color(242, 242, 242);
pdfTable.AddCell(header);
}
}
catch (Exception ex)
{
throw ex;
}
}

---------------------------------------------------------

Reply

re: DataGrid to PDF Export With proper Allignment.
Nowshad M replied to Sathya on 29-Nov-10 04:58 AM
Hi,
Find the below code also

public void CreatePdfTable(out iTextSharp.text.Document pdfDoc, out string path, out PdfPTable pdfTable, int colCount, string fileName)

{

string deletePath = HttpContext.Current.Server.MapPath("~/PDF");

if (Directory.Exists(deletePath))

{

string[] files = Directory.GetFiles(deletePath);

foreach (string file in files)

{

File.Delete(file);

}

}



pdfDoc = new iTextSharp.text.Document();

path = HttpContext.Current.Server.MapPath("~/PDF\\" + fileName + ".pdf");

iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, new FileStream(path, FileMode.Create));

pdfTable = new PdfPTable(colCount);

pdfTable.WidthPercentage = 100.0f;

HeaderFooter footer = new HeaderFooter(new Phrase(""), false);

footer.Border = 0;

pdfDoc.Footer = footer;

footer.Alignment = HeaderFooter.ALIGN_CENTER;

}



You should make function call like below in the button click



protected void btnExportPdf_Click(object sender, ImageClickEventArgs e)

{

try

{

grvCountryReport.AllowPaging = false;

grvCountryReport.DataSource = objDA.GetCountryDetails();

grvCountryReport.DataBind();

int rowCount = grvCountryReport.Rows.Count;

int colCount = grvCountryReport.Columns.Count;

iTextSharp.text.Document pdfDoc;

string path;

PdfPTable pdfTable;

objLib.CreatePdfTable(out pdfDoc, out path, out pdfTable, colCount, "Country Details Report");



pdfDoc.Open();

objLib.BuildPdfGridHeaders(pdfTable, "Country Details Report", "This shows a detailed country report", colCount, "Country Name");

BuildPdfGridRows(rowCount, pdfDoc, pdfTable);

pdfDoc.Add(pdfTable);

pdfDoc.Close();

objLib.Exportpdf(path, "Country Details Report");



if (!ClientScript.IsStartupScriptRegistered("alert"))

{



Page.ClientScript.RegisterStartupScript



(this.GetType(), "alert", "viewmaskpanelReport();", true);



}

}

catch (Exception ex)

{



}



}



-------------------------------------------------------------------
Reply

re: DataGrid to PDF Export With proper Allignment.
Sathya replied to Nowshad M on 29-Nov-10 05:12 AM
Wow.. Thanks a lot for your Immediate Response Dear Nowshad,

Can u please post the definition for the function ExportPDF that you have mentioned above...?

Will adopt everything and get back to you

Thanks and Regards,
Sathya
Reply

re: DataGrid to PDF Export With proper Allignment.
Nowshad M replied to Sathya on 29-Nov-10 05:15 AM
Hi,
Find the Export PDF function as below

public void Exportpdf(string path, string fileName)
{
try
{
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".pdf");
HttpContext.Current.Response.TransmitFile(path);
HttpContext.Current.Response.End();
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Clear();
}
catch (Exception ex)
{
}
}

Hope this helps


---------------------------------------------------------

Reply

re: DataGrid to PDF Export With proper Allignment.
Sathya replied to Nowshad M on 29-Nov-10 05:28 AM
I am sure its gonna help a lot Nowshad,

Are these functions and their definitions same..?

BuildPdfGridHeaders as BuildPdfHeaders? and BuildPdfGridRows is same as BuildRows? because they have different parameters...

If they are different kindly post it here as I can see that your code is absolutely fantabulous...

---------------------------------------------------------

Reply

re: DataGrid to PDF Export With proper Allignment.
Nowshad M replied to Sathya on 29-Nov-10 05:31 AM
Hi,
Please find the full length of code an dlet me know the results

public void CreatePdfTable(out iTextSharp.text.Document pdfDoc, out string path, out PdfPTable pdfTable, int colCount, string fileName)
{
string deletePath = HttpContext.Current.Server.MapPath("~/PDF");
if (Directory.Exists(deletePath))
{
string[] files = Directory.GetFiles(deletePath);
foreach (string file in files)
{
File.Delete(file);
}
}

pdfDoc = new iTextSharp.text.Document();
path = HttpContext.Current.Server.MapPath("~/PDF\\" + fileName + ".pdf");
iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, new FileStream(path, FileMode.Create));
pdfTable = new PdfPTable(colCount);
pdfTable.WidthPercentage = 100.0f;
HeaderFooter footer = new HeaderFooter(new Phrase(""), false);
footer.Border = 0;
pdfDoc.Footer = footer;
footer.Alignment = HeaderFooter.ALIGN_CENTER;
}

public void BuildPdfGridHeaders(PdfPTable pdfTable, string reportHeading, string reportSubHeading,int colCount, params string[] headerValues)
{
try
{
PdfPCell dateCell = new PdfPCell(new Phrase("Date : " + DateTime.Now.Date.ToString("dd/MM/yyyy") + "", new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 8f, (int)System.Drawing.FontStyle.Regular, new iTextSharp.text.Color(System.Drawing.Color.Black))));
dateCell.PaddingTop = 10f;
dateCell.Colspan = colCount;
dateCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
dateCell.Border = iTextSharp.text.Rectangle.NO_BORDER;
pdfTable.AddCell(dateCell);

PdfPCell reportHeader = new PdfPCell(new Phrase(reportHeading, new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 12f, (int)System.Drawing.FontStyle.Bold, new iTextSharp.text.Color(System.Drawing.Color.Black))));
reportHeader.PaddingTop = 0f;
reportHeader.Colspan = colCount;
reportHeader.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
reportHeader.Border = iTextSharp.text.Rectangle.NO_BORDER;
pdfTable.AddCell(reportHeader);

PdfPCell subHeader = new PdfPCell(new Phrase(reportSubHeading, new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 8f, (int)System.Drawing.FontStyle.Italic, new iTextSharp.text.Color(System.Drawing.Color.Black))));
subHeader.PaddingBottom = 10f;
subHeader.Colspan = colCount;
subHeader.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
subHeader.Border = iTextSharp.text.Rectangle.NO_BORDER;
pdfTable.AddCell(subHeader);

for (int emptyCount = 0; emptyCount < colCount*2; emptyCount++)
{
PdfPCell emptyCel = new PdfPCell(new Phrase(""));
emptyCel.PaddingBottom = 10f;
emptyCel.Border = iTextSharp.text.Rectangle.NO_BORDER;
pdfTable.AddCell(emptyCel);
}


for (int count = 0; count < headerValues.Length; count++)
{
PdfPCell header = new PdfPCell(new Phrase(headerValues[count].ToString(), new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 10f, (int)System.Drawing.FontStyle.Regular, new iTextSharp.text.Color(System.Drawing.Color.Black))));
header.PaddingBottom = 5f;
header.BorderColor = new iTextSharp.text.Color(229, 229, 229);
header.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
header.BackgroundColor = new iTextSharp.text.Color(242, 242, 242);
pdfTable.AddCell(header);
}
}
catch (Exception ex)
{
throw ex;
}
}

private void BuildPdfGridRows(int rowCount, iTextSharp.text.Document pdfDoc, PdfPTable pdfTable)
{
try
{
for (int rCount = 0; rCount < rowCount; rCount++)
{

Label CountryName = (Label)grvCountryReport.Rows[rCount].FindControl("lblCountryName");
pdfTable = objLib.BuildPdfGridRows(pdfTable, CountryName.Text);
}
}
catch (Exception ex)
{
throw ex;
}
}


---------------------------------------------------------

Reply

re: DataGrid to PDF Export With proper Allignment.
Sathya replied to Nowshad M on 29-Nov-10 07:06 AM
Dear Nawshad,

Your code is really superb and working fine for a test case. However I need one more help. in the code give by you,

private void BuildPdfGridRows(int rowCount, iTextSharp.text.Document pdfDoc, PdfPTable pdfTable)
{
try
{
for (int rCount = 0; rCount < rowCount; rCount++)
{

(Label)DataGrid1.Items[rCount].FindControl("lblCountryName");
pdfTable = BuildRows(pdfTable, cboPerformanceType.SelectedItem.Text);
}
}
catch (Exception ex)
{
throw ex;
}
}

You are using a "lblCountryName" in the DataGrid's find control attribute. However my DataGrid is a Dynamic one and Doesnt contain any templateColumns. All are dynamic data generated during run time [As I am using Same DataGrid as common datagrid to bind data executed by dynamic queries]...

So what would be the best alternative for the above function definition.

Eagerly awaiting your response.

Thanks and Regards,
Sathya


---------------------------------------------------------
Reply

re: DataGrid to PDF Export With proper Allignment.
Nowshad M provided a helpful reply to Sathya on 29-Nov-10 07:20 AM
Hi,
For that u need changes in two functions as below

private void BuildPdfGridRows(int rowCount, iTextSharp.text.Document pdfDoc, PdfPTable pdfTable)
{
try
{
for (int rCount = 0; rCount < rowCount; rCount++)
{
string[] text = new string[grvCountry.Columns.Count];
for (int cCount = 0; cCount < grvCountry.Columns.Count; cCount++)
{
if (cCount == 0)
text[cCount] = grvCountryReport.Rows[rCount].Cells[cCount].Text;
else
text[cCount] = "," + grvCountryReport.Rows[rCount].Cells[cCount].Text;
}
pdfTable = objLib.BuildPdfGridRows(pdfTable, text);
}
}
catch (Exception ex)
{

}
}

public PdfPTable BuildPdfGridRows(PdfPTable pdfTable, string[] rowValues)
{
try
{
for (int count = 0; count < rowValues.Length; count++)
{
PdfPCell cel = new PdfPCell(new Phrase(rowValues[count].ToString(), new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 9f, (int)System.Drawing.FontStyle.Regular, new iTextSharp.text.Color(System.Drawing.Color.Black))));
cel.PaddingLeft = 10f;
cel.PaddingBottom = 4f;

cel.BorderColor = new iTextSharp.text.Color(229, 229, 229);
cel.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
pdfTable.AddCell(cel);

}
return pdfTable;
}
catch (Exception ex)
{

return pdfTable;
}
}


---------------------------------------------------------
Reply

re: DataGrid to PDF Export With proper Allignment.
Sathya replied to Nowshad M on 29-Nov-10 08:49 AM
Hey Dear Nawshad,

You know what... It perfectly worked for me dear.. Thanks a lot...

However each cell is separated by a comma. I think I will do some RnD get it sorted to ensure, like entire datagrid is printed on to PDF...

Let me also know in future if you have any better ideas for the same..

But Really really thank you for your timely and valuable response.

You helped me a lot

Thanks and Regards,
Sathya
Reply



-------------------------------------------------------------------------------------
Full Post is below ::

No comments:

Post a Comment