Friday, January 6, 2012

HTML To PDF Converter Asp.net

using Pdfizer; //download Pdfizer and itextsharp dll also
using System.IO;

 protected void btnDownload_Click1(object sender, EventArgs e)
    {
        string sPathToWritePdfTo = Server.MapPath(".") + "\\test.pdf";
        string path = Server.MapPath("./images/logo3w.png");
        System.Text.StringBuilder sbHtml = new System.Text.StringBuilder();
        sbHtml.Append("<html>");
        sbHtml.Append("<head>");
        sbHtml.Append("</head>");
        sbHtml.Append("<body>");
        sbHtml.Append("<div>");
        sbHtml.Append("<img src='" + path + "' alt='' />");
        sbHtml.Append("</div>");
        sbHtml.Append("<br/>");
        sbHtml.Append("<table border='0' cellpadding='0' cellspacing='0'>");
        sbHtml.Append("<tr><td>testing the text</td></tr>");
        sbHtml.Append("</table>");
        sbHtml.Append("</body>");
        sbHtml.Append("</html>");

        using (System.IO.Stream stream = new System.IO.FileStream
        (sPathToWritePdfTo, System.IO.FileMode.OpenOrCreate))
        {
            Pdfizer.HtmlToPdfConverter htmlToPdf = new Pdfizer.HtmlToPdfConverter();
            htmlToPdf.Open(stream);
            htmlToPdf.Run(sbHtml.ToString());
            htmlToPdf.Close();
        }
        System.Web.HttpContext.Current.Response.Clear();
        System.Web.HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "devtesting.pdf"));
        System.Web.HttpContext.Current.Response.ContentType = "application/pdf";
        System.Web.HttpContext.Current.Response.WriteFile(sPathToWritePdfTo);
        System.Web.HttpContext.Current.Response.End();
    }

/*http://itextpdf.com/terms-of-use*/

2 comments:

  1. Muito bom, só não conseguir fazer funcionar cores de Backgraund,color...
    divs..

    ReplyDelete