Sometimes we need to give option download with PDF for some table on website. so this will help you.
I am using iTextSharp to download with PDF. You need to download it first and then after adding reference of that dll into your project you can use this codes.
I am using iTextSharp to download with PDF. You need to download it first and then after adding reference of that dll into your project you can use this codes.
protected void btnDownloadPDF_Click(object sender, EventArgs e)
{
StringBuilder str = new StringBuilder();
str.Append("<h1 align=\"center\" style=\"font-size:15;font-weight:bold;\"><u>Report</u></h1><br/><br/>");
str.Append("<table border=1 style=\"font-size:12;\">");
str.Append("<tr bgcolor=\"#43928D\" style=\"font-weight:bold;color:white;\">");
str.Append("<th>Name</th>");
str.Append("<th>Company</th>");
str.Append("<th>Date</th>");
str.Append("<th>Salary</th></tr>");
for (int i = 0; i < GridView1.Rows.Count; i++)
{
str.Append("<tr><td>" + GridView1.Rows[i].Cells[0].Text + "</td>");
str.Append("<td>" + GridView1.Rows[i].Cells[1].Text + "</td>");
str.Append("<td>" + GridView1.Rows[i].Cells[2].Text + "</td>");
str.Append("<td>" + GridView1.Rows[i].Cells[3].Text + "</td></tr>");
}
str.Append("</table>");
CommonFunctions Functions = new CommonFunctions();
Functions.ExportPDF(str, "SalaryReport");
}
Here ExportPDF is a function of my CommonFunctions Class.
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
public class CommonFunctions
{
public void ExportPDF(StringBuilder html, string FileName)
{
//set the cotent type to PDF
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + FileName + ".pdf");
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
//load the html content to the string reader
StringReader sr = new StringReader(html.ToString());
//HTMLDocument
//Document(Rectangle pageSize, float marginLeft, float marginRight, float marginTop, float marginBottom)
Document document = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
//iText class that allows you to convert HTML to PDF
HTMLWorker htmlWorker = new HTMLWorker(document);
//When this PdfWriter is added to a certain PdfDocument,
//the PDF representation of every Element added to this Document will be written to the outputstream.
PdfWriter.GetInstance(document, HttpContext.Current.Response.OutputStream);
//open the document
document.Open();
htmlWorker.Parse(sr);
//close the document stream
document.Close();
//write the content to the response stream
HttpContext.Current.Response.Write(document);
HttpContext.Current.Response.End();
}
}
No comments:
Post a Comment