Tuesday, October 6, 2009

Creating a PDF from Asp.Net

We need to have IText Sharp dll for this Code to work.. You can make a search in Google to get the Dll file. And after importing the dll you can use this code to create a PDF in specified path.

protected void btnPDF_Click(object sender, EventArgs e)
{
//ScriptManager.RegisterStartupScript(this, this.GetType(), "", "window.open('../PDFTest.aspx?PDFUrl=StatusLog.pdf','_blank');", true);


Response.Write("");
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=StatusLog.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
grdStatus.AllowPaging = false;
grdStatus.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
}

No comments:

Post a Comment