asp.net

Convert HTML to PDF In C sharp

A
Desh-Duniya Team Author
| Published June 01, 2019

Add Package

Install-Package iTextSharp
Install-Package itextsharp.xmlworker
public ActionResult Index()
        {
           
            string html = System.IO.File.ReadAllText(Server.MapPath("~/Sample-Invoice.html"));
            string htmlContent = html; 
            Document document = new Document();
            string FileName = Guid.NewGuid().ToString();
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("sample.pdf", FileMode.Create));
            document.Open();
            ICSSResolver cssResolver = new StyleAttrCSSResolver();
            
            ICssFile cssFile = XMLWorkerHelper.GetCSS(new FileStream(Server.MapPath("~") + "/Content/Site.css", FileMode.Open));
            cssResolver.AddCss(cssFile);
            // HTML  
            HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
            htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
            // Pipelines  
            PdfWriterPipeline pdfFile = new PdfWriterPipeline(document, writer);
            HtmlPipeline html1 = new HtmlPipeline(htmlContext, pdfFile);
            CssResolverPipeline css = new CssResolverPipeline(cssResolver, html1);
            // XML Worker  
            XMLWorker worker = new XMLWorker(css, true);
            XMLParser p = new XMLParser(worker);
            p.Parse(new StringReader(htmlContent));

            document.Close();

            //To download same PDF I write below code

            Response.Clear();
            string pdfPath = Server.MapPath(@"~\PDF\" + FileName + ".pdf");
            WebClient client = new WebClient();
            Byte[] buffer = client.DownloadData(pdfPath);
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-length", buffer.Length.ToString());
            Response.BinaryWrite(buffer);
            Response.Flush();
            
            Response.End();


            return View();
        }

Discussion (0)

Please sign in to participate in the discussion.
No comments yet. Be the first to join the conversation!