Here's the corrected code
Namespaces
using System.IO;
using System.Net.Mail;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
using System.Data;
using System.Text;
Code
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] {
new DataColumn("Id"),
new DataColumn("Name"),
new DataColumn("Country")});
dt.Rows.Add(1, "John Hammond", "United States");
dt.Rows.Add(2, "Mudassar Khan", "India");
dt.Rows.Add(3, "Suzanne Mathews", "France");
dt.Rows.Add(4, "Robert Schidner", "Russia");
ExportToPDF(dt);
}
}
private void ExportToPDF(DataTable dt)
{
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter hw = new HtmlTextWriter(sw))
{
StringBuilder sb = new StringBuilder();
sb.Append("<table width='100%' cellspacing='0' cellpadding='2'>");
sb.Append("<tr><td align='center' style='background-color: #18B5F0' colspan = '2'><b>Order Sheet</b></td></tr>");
sb.Append("<tr><td colspan = '2'></td></tr>");
sb.Append("<tr><td><b>Order No:</b> 100</td><td><b>Date: </b>" + DateTime.Now + " </td></tr>");
sb.Append("<tr><td><b>From :</b> " + "Company Name" + " </td><td><b>To: </b>" + " Some Company " + " </td></tr>");
sb.Append("</table>");
sb.Append("<table border = '1'>");
sb.Append("<tr>");
foreach (DataColumn column in dt.Columns)
{
sb.Append("<th>");
sb.Append(column.ColumnName);
sb.Append("</th>");
}
sb.Append("</tr>");
foreach (DataRow row in dt.Rows)
{
sb.Append("<tr>");
foreach (DataColumn column in dt.Columns)
{
sb.Append("<td>");
sb.Append(row[column]);
sb.Append("</td>");
}
sb.Append("</tr>");
}
sb.Append("</table>");
StringReader sr = new StringReader(sb.ToString());
Document pdfDoc = new Document(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();
MailMessage mm = new MailMessage("sender@gmail.com", "receiver@gmail.com");
mm.Subject = "GridView Exported PDF";
mm.Body = "GridView Exported PDF Attachment";
mm.Attachments.Add(new Attachment(new MemoryStream(bytes), "GridViewPDF.pdf"));
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = "sender@gmail.com";
NetworkCred.Password = "password";
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);
}
}
}
}
Screenshot