Convert HTML to PDF in .NET

后端 未结 30 1823
不知归路
不知归路 2020-11-22 00:28

I want to generate a PDF by passing HTML contents to a function. I have made use of iTextSharp for this but it does not perform well when it encounters tables and the layout

30条回答
  •  终归单人心
    2020-11-22 00:54

    Below is an example of converting html + css to PDF using iTextSharp (iTextSharp + itextsharp.xmlworker)

    using iTextSharp.text;
    using iTextSharp.text.pdf;
    using iTextSharp.tool.xml;
    
    
    byte[] pdf; // result will be here
    
    var cssText = File.ReadAllText(MapPath("~/css/test.css"));
    var html = File.ReadAllText(MapPath("~/css/test.html"));
    
    using (var memoryStream = new MemoryStream())
    {
            var document = new Document(PageSize.A4, 50, 50, 60, 60);
            var writer = PdfWriter.GetInstance(document, memoryStream);
            document.Open();
    
            using (var cssMemoryStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(cssText)))
            {
                using (var htmlMemoryStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(html)))
                {
                    XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, htmlMemoryStream, cssMemoryStream);
                }
            }
    
            document.Close();
    
            pdf = memoryStream.ToArray();
    }
    

提交回复
热议问题