Last Updated: February 25, 2016
·
473
· ridermansb

Preview de um texto HTML

Recentemente precisei exibir um preview de um texto HTML.
Basicamente um usuário cadastra uma nova entrada no blog (por exemplo) e a ideia é exibir um preview deste post.

public static string GetFirstTag(this string htmlText)
{
    var htmlDoc = new HtmlDocument();
    htmlDoc.LoadHtml(htmlText);

    var imgNode = htmlDoc.DocumentNode.SelectSingleNode("//img[@src]");
    return imgNode != null
               ? imgNode.Attributes["src"].Value
               : "";
}

public static string GetSummaryHTML(this string htmlText, int maxWords, int maxParagrafos = int.MaxValue, bool addReticencias = false)
{
    string summaryHtml = string.Empty;
    int wordCount = 0;
    int paragrafoCount = 0;

    var htmlDoc = new HtmlDocument();
    htmlDoc.LoadHtml(htmlText);

    foreach (var element in htmlDoc.DocumentNode.ChildNodes)
    {
        string elementText = element.InnerText;
        summaryHtml += "<p>";
        paragrafoCount++;
        foreach (var word in elementText.Split(new[] {' '}))
        {
            summaryHtml += word + " ";
            wordCount++;
            if (wordCount >= maxWords)
                return summaryHtml + (addReticencias ? ".." : "") + "</p>";
        }
        summaryHtml += "</p>";
        if (paragrafoCount >= maxParagrafos)
            return summaryHtml;
    }

    return summaryHtml + "</p>";
}

public static string GetSummaryText(this string htmlText, int maxWords, bool addReticencias = false)
{
    string summaryHtml = string.Empty;
    int wordCount = 0;

    var htmlDoc = new HtmlDocument();
    htmlDoc.LoadHtml(htmlText);

    foreach (var element in htmlDoc.DocumentNode.ChildNodes)
    {
        string elementText = element.InnerText;
        foreach (var word in elementText.Split(new[] {' '}))
        {
            summaryHtml += word + " ";
            wordCount++;
            if (wordCount > maxWords)
                return summaryHtml + (addReticencias ? ".." : "");
        }
    }

    return summaryHtml;
}

Para isso utilizei o HTML Agility Pack http://htmlagilitypack.codeplex.com/