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 ::

Tuesday, January 25, 2011

Add an Image to pdf document using ItextSharp

In this article we will show how to add Image in pdf document using Itextsharp in asp.net. For some report which is in pdf format we need to add image .jpg, .gif, .bmp or any image format.
Itextsharp is an open source free pdf generate library which will generate the pdf and yes you can add the image into it.

you can also refer to my articles on ItextSharp in asp.net here to create table in pdf doc here

Step 1 : Download the ITextsharp library from here.

Step 2 : Add Itextsharp.dll to your project by right click and add reference on the project explorer

Step 3 : Now add the Namespace to your .cs or .vb file


using iTextSharp.text;
using iTextSharp.text.pdf;




Step 4 :

Lets see this code which will be place image into PDF document


// Now image in the pdf file
string imageFilePath = Server.MapPath(".") + "/image/Sunset.jpg";
iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageFilePath);

//Resize image depend upon your need
jpg.ScaleToFit(280f, 260f);

//Give space before image
jpg.SpacingBefore = 30f;

//Give some space after the image
jpg.SpacingAfter = 1f;
jpg.Alignment = Element.ALIGN_CENTER;

doc.Add(paragraph); // add paragraph to the document

doc.Add(jpg); //add an image to the created pdf document



Now to see full code you can place the below code in any event like on button click

In C# sample code function:

private void CreatePDFFile()
{
Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
try
{
string pdfFilePath = Server.MapPath(".") + "/pdf/myPdf.pdf";

//Create Document class object and set its size to letter and give space left, right, Top, Bottom Margin
PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(pdfFilePath, FileMode.Create));
doc.Open();//Open Document to write

//Write some content into pdf file
Paragraph paragraph = new Paragraph("This is my first line using Paragraph.");

// Now image in the pdf file
string imageFilePath = Server.MapPath(".") + "/image/Sunset.jpg";
iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageFilePath);

//Resize image depend upon your need
jpg.ScaleToFit(280f, 260f);

//Give space before image
jpg.SpacingBefore = 30f;

//Give some space after the image
jpg.SpacingAfter = 1f;
jpg.Alignment = Element.ALIGN_CENTER;

doc.Add(paragraph); // add paragraph to the document

doc.Add(jpg); //add an image to the created pdf document
}
catch (DocumentException docEx)
{
//handle pdf document exception if any
}
catch (IOException ioEx)
{
// handle IO exception
}
catch (Exception ex)
{
// ahndle other exception if occurs
}
finally
{
//Close document and writer
doc.Close();

}
}



Same above code vb.net method:

Private Sub CreatePDFFile()
Dim doc As New Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35)
Try
Dim pdfFilePath As String = Server.MapPath(".") & "/pdf/myPdf.pdf"

'Create Document class object and set its size to letter and give space left, right, Top, Bottom Margin
Dim wri As PdfWriter = PdfWriter.GetInstance(doc, New FileStream(pdfFilePath, FileMode.Create))
doc.Open()
'Open Document to write
'Write some content into pdf file
Dim paragraph As New Paragraph("This is my first line using Paragraph.")

' Now image in the pdf file
Dim imageFilePath As String = Server.MapPath(".") & "/image/Sunset.jpg"
Dim jpg As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(imageFilePath)

'Resize image depend upon your need
jpg.ScaleToFit(280F, 260F)

'Give space before image
jpg.SpacingBefore = 30F

'Give some space after the image
jpg.SpacingAfter = 1F
jpg.Alignment = Element.ALIGN_CENTER

doc.Add(paragraph)
' add paragraph to the document
'add an image to the created pdf document
doc.Add(jpg)
Catch docEx As DocumentException
'handle pdf document exception if any
Catch ioEx As IOException
' handle IO exception
Catch ex As Exception
' ahndle other exception if occurs
Finally
'Close document and writer

doc.Close()
End Try
End Sub



If you run your application you can see the image in pdf document like this:




Hope this will help all!



Thank You for your valuable time.

Irfan Ahmad alias (Isfan Habib)
(Team Lead)
DZ International
Srinagar, Kashmir
e-mail: irfanhabib06@gmail.com

Monday, January 24, 2011

Visual Studio / SQL Server Unable to open database / Operating systerm Error 5

Operating systerm Error 5 usually means not enough permission.

Make sure account under which SQL server service is runing has modify permission on the folder where you have kept your MDF File.

Not account under you are logged in Windows (does not matter you have permission; it is the SQL server service account that needs permission)

•Right click on the folder D:\Development Workx\Hamza Workingx\hamriqueweb_1_Edited_ALi2\App_Data and click on properties
•Click on security tab
•Click on Add button and add sql service account
•Provide modify privilege and click ok
•Verify both mdf and ldf have modify privilege
•Attach the db