How do I convert malformed HTML to PDF with iText and XMLWorker?

别等时光非礼了梦想. 提交于 2019-12-12 04:33:17

问题


I am trying to convert HTML(with external CSS) into PDF using Itext XMLWorkerHelper, am facing the run-time exception whenever XMLWorkerHelper parses a malformed HTML. For example:

The html below has input tag not closed : and XMLWorkerHelper cannot parse and throws run-time exception.

if i try with proper HTML input tag enclosed,it works fine.

How can i convert malformed or complex HTML (along with css) to PDF using Itext.

below is my code:

var test_html = File.ReadAllText("C:/Desking _ Lender Program - Dealertrack.html");
var test_css = File.ReadAllText("C:/login.css");
using (var msCss = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(test_css)))
                    {
                        using (var msHtml = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(test_html)))
                        {

                            //Parse the HTML
                            try
                            {
                                iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msHtml, msCss);
                            }
                            catch { }
                        }
                    }

回答1:


It's a bit unclear whether you've decided to use iText7 or iTextSharp (5.x.x), but here's a simple example of the latter using HtmlAgilityPack to clean up malformed HTML:

var malformedHtml = @"
<h1>Malformed HTML</h1>
<p>A paragraph <b><span>with improperly nested tags</b></span></p><hr>
<table><tr><td>Cell 1, row 1</td><td>Cell 1, row 2";
HtmlDocument h = new HtmlDocument()
{
    OptionFixNestedTags = true, OptionWriteEmptyNodes = true
};
h.LoadHtml(malformedHtml);

string css = @"
h1 { font-size:1.4em; }
hr { margin-top: 4em; margin-bottom: 2em; color: #ddd; }
table { border-collapse: collapse; }
table, td { border: 1px solid black; }
td { padding: 4px; }
span { color: red; }";

using (var stream = new MemoryStream())
{
    using (var document = new Document())
    {
        PdfWriter writer = PdfWriter.GetInstance(document, stream);
        document.Open();
        using (var htmlStream = new MemoryStream(Encoding.UTF8.GetBytes(h.DocumentNode.WriteTo())))
        {
            using (var cssStream = new MemoryStream(Encoding.UTF8.GetBytes(css)))
            {
                XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, htmlStream, cssStream);
            }
        }
    }
    File.WriteAllBytes(OUTPUT, stream.ToArray());
}

PDF output:




回答2:


And if you are free to choose your particular iText flavour, please go with iText7 and pdfHTML. It supercedes XMLWorker, supports a wider range of tags and CSS3.0.



来源:https://stackoverflow.com/questions/43875060/how-do-i-convert-malformed-html-to-pdf-with-itext-and-xmlworker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!