Thursday, 6 November 2014

Convert html to pdf

//Save on server
 string pdffile = "Invoice" + DateTime.Now.ToString();
        pdffile = pdffile.Replace('/', '_').Replace(' ', '_').Replace(':', '_')+".pdf";
        var htmlContent = div_abc.InnerHtml;
        var pdfBytes = (new NReco.PdfGenerator.HtmlToPdfConverter()).GeneratePdf(htmlContent);
        File.WriteAllBytes(Server.MapPath("UploadFiles/Invoice/") + pdffile , pdfBytes);






//Convert and download on client side
        Response.Clear();
        Response.ClearHeaders();
        Response.ClearContent();
        Response.ContentType = "application/pdf";
        var sb = new StringBuilder();
        //sb.Append(div_abc.InnerHtml);
        div_abc.RenderControl(new HtmlTextWriter(new System.IO.StringWriter(sb)));

        string s = sb.ToString();

        var pdfBytes = (new NReco.PdfGenerator.HtmlToPdfConverter()).GeneratePdf(s);
        Response.AppendHeader("content-disposition", "attachment; filename=Invoice-Com-Receipt.pdf");
        Response.AppendHeader("content-length", pdfBytes.Length.ToString());
        //string fileNameWitPath = Server.MapPath("~/css/" + "Invoice-Com-Receipt.pdf");
        Response.BinaryWrite(pdfBytes);

        Response.Flush();
        Response.Close();

No comments:

Post a Comment