First include these references like
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
protected void CreatePdf_Click(object sender,
EventArgs e)
{
var document = new
Document(PageSize.A4, 50, 50, 25, 25);
// Create a new PdfWrite object,
writing the output to a MemoryStream
var output = new MemoryStream();
var writer =
PdfWriter.GetInstance(document, output);
// Open the Document for writing
document.Open();
// Read in the contents of the
Receipt.htm HTML template file
string contents =
File.ReadAllText(Server.MapPath("~/PdfTemplate/Receipt.htm"));
// Replace the placeholders with the
user-specified text
var itemsTable = @"<table><tr><th
style=""font-weight: bold"">Product #</th><th style=""font-weight:
bold"">Qty</th><th style=""font-weight: bold"">Price</th><th
style=""font-weight: bold"">Total Amount</th></tr>";
SqlConnection con = new
SqlConnection("server=192.168.1.50;database=Qwizo_Dev;user id=QwizoDev;password=Qwizo@123");
con.Open();
string query = "select *from TestUser";
string query1 = "select *from
TestProduct";
using (SqlCommand cmd = new
SqlCommand(query, con))
{
using (SqlDataReader dr =
cmd.ExecuteReader())
{
if (dr.Read())
{
contents =
contents.Replace("[Name]", dr[1].ToString() + " " + dr[2].ToString());
contents =
contents.Replace("[Address]", dr[3].ToString());
contents =
contents.Replace("[Name1]", dr[1].ToString() + " " + dr[2].ToString());
contents =
contents.Replace("[Address1]", dr[3].ToString());
}
}
}
using (SqlCommand cmd = new
SqlCommand(query1, con))
{
using (SqlDataReader dr =
cmd.ExecuteReader())
{
if (dr.Read())
{
itemsTable +=
string.Format("<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td></tr>",
dr[0].ToString(), dr[1].ToString(), dr[2].ToString(), dr[3].ToString());
}
}
}
itemsTable += "</table>";
contents = contents.Replace("[ITEMS]",
itemsTable);
var parsedHtmlElements =
HTMLWorker.ParseToList(new StringReader(contents), null);
foreach (var htmlElement in
parsedHtmlElements)
document.Add(htmlElement as
IElement);
// You can add additional elements to
the document. Let's add an image in the upper right corner
var logo =
iTextSharp.text.Image.GetInstance(Server.MapPath("~/Images/PPIC_Logo.png"));
var logo1 =
iTextSharp.text.Image.GetInstance(Server.MapPath("~/Images/PPIC_Logo.png"));
logo.SetAbsolutePosition(440, 800);
document.Add(logo);
document.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition",
string.Format("inline;filename=MeeraReceipt.pdf"));
Response.BinaryWrite(output.ToArray());
con.Close();
}