Mailkit: Converting HtmlBody to pdf using iTextSharp XMLWorker throws "The document has no pages"

c# html-agility-pack itext mailkit xmlworker


I'm using Mailkit to try to convert the HtmlBody of emails that I get from mail servers, but it seems that iTextSharp doesn't really like the HTML I'm providing it.

With a "example" HTML code, my technique functions properly, however I receive aThe document has no pages error notice that seems to be issued when the HTML is no longer valid.

public void GenerateHtmlFromBody(UniqueId uid)
    var email = imap.Inbox.GetMessage(uid);
    Byte[] bytes;

    using (var ms = new MemoryStream())
        using (var doc = new Document())
            using (var writer = PdfWriter.GetInstance(doc, ms))

                //Sample HTML and CSS
                var example_html = @"<p>This <em>is </em><span class=""headline"" style=""text-decoration: underline;"">some</span> <strong>sample <em> text</em></strong><span style=""color: red;"">!!!</span></p>";
                var example_css = @".headline{font-size:200%}";

                using (var srHtml = new StringReader(email.HtmlBody))
                    //Parse the HTML
                    iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml);
        bytes = ms.ToArray();
    var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "processedMailPdf.pdf");
    System.IO.File.WriteAllBytes(testFile, bytes);

I am enteringMimeMessage.HtmlBody and after some debugging, it seems to be html.

For testing the HtmlBody of theMimeMessage because I've reached my character limit.

What am I overlooking? Thanks.

EDIT: The HTMLWorker, which is out of date, is unstable when I try to use it. With one email, it worked, but not with others. Even though it was obviously not a solution, Mailkit did manage to produce a pdf, so at least that was "something."

3/7/2017 7:32:05 AM

Accepted Answer

It seems that you have two problems withHtmlBody :

  1. It may just be basic text.
  2. It is not well-formed when it is [X]HTML.

Your best option if there's a chance you could be working with a string that isn't well-formed XML is to utilize a parser like HtmlAgilityPack to sort out the issue. Here is a quick fix that addresses both of the aforementioned problems using XPath and removes them using UPDATED based on comments.HtmlCommentNode s that fail to parse iText XML Worker

string FixBrokenMarkup(string broken)
    HtmlDocument h = new HtmlDocument()
        OptionAutoCloseOnEnd = true,
        OptionFixNestedTags = true,
        OptionWriteEmptyNodes = true

    // UPDATED to remove HtmlCommentNode
    var comments = h.DocumentNode.SelectNodes("//comment()");
    if (comments != null) 
        foreach (var node in comments) { node.Remove(); }

    return h.DocumentNode.SelectNodes("child::*") != null
        //                            ^^^^^^^^^^
        // XPath above: string plain-text or contains markup/tags
        ? h.DocumentNode.WriteTo()
        : string.Format("<span>{0}</span>", broken);

Code to create the PDF is also included for completeness. using the pastebin URL you supplied above, tested and functioning:

var fixedMarkup = FixBrokenMarkup(PASTEBIN);
// swap initialization to verify plain-text works too
// var fixedMarkup = FixBrokenMarkup("some text");

using (var stream = new MemoryStream())
    using (var document = new Document())
        PdfWriter writer = PdfWriter.GetInstance(document, stream);
        using (var stringReader = new StringReader(fixedMarkup))
                writer, document, stringReader
    File.WriteAllBytes(OUTPUT, stream.ToArray());
3/10/2017 2:10:21 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow