StringReader sr = new StringReader(strMailBody.ToString()); // strMailBody is a HTML string generated using HTML template.
Document pdfDoc = new Document(iTextSharp.text.PageSize.A4, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
using (MemoryStream memoryStream = new MemoryStream())
{
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
byte[] bytes = memoryStream.ToArray();
memoryStream.Close();
// Clears all content output from the buffer stream
Response.Clear();
// Gets or sets the HTTP MIME type of the output stream.
Response.ContentType = "application/pdf";
// Adds an HTTP header to the output stream
Response.AddHeader("Content-Disposition", "attachment; filename=SponsorshipForm.pdf");
// Gets or sets a value indicating whether to buffer output and send it after
// the complete response is finished processing.
Response.Buffer = true;
// Sets the Cache-Control header to one of the values of System.Web.HttpCacheability.
Response.Cache.SetCacheability(HttpCacheability.NoCache);
// Writes a string of binary characters to the HTTP output stream. it write the generated bytes.
Response.BinaryWrite(bytes);
// Sends all currently buffered output to the client, stops execution of the
// page, and raises the System.Web.HttpApplication.EndRequest event.
Response.End();
// Closes the socket connection to a client. it is a necessary step as you must close the response after doing work.its best approach.
Response.Close();
}