/// <summary> /// Gets HTML from a text string, wrapping lines in the given default block element. /// </summary> /// <param name="text">The plain text to convert into HTML</param> /// <returns>The HTML</returns> public static string GetHTMLFromText(string text, bool addLinks, DefaultBlockElement defaultBlockElement) { text = EscapeHtmlEntitiesAndAddLinks(text, addLinks); text = NormalizeText(text); return(ConvertTextToHtml(text, defaultBlockElement)); }
private static string ConvertTextToHtml(string text, DefaultBlockElement defaultBlockElement) { if (defaultBlockElement == null) { return(text.Replace("\r\n", "<br />")); } if (!text.Contains("\r\n")) { return(text); } bool insideBlockElement = false; bool blockElementIsEmpty = true; // Replace each occurrence of a sequence of non-CRLF characters followed by 0 or more CRLFs with the // non-CRLF characters wrapped in an HTML block element: // line1\r\nline2\r\n\r\nline3 => <p>line1<br />line2</p><p>line3</p> // (the <br /> is added because ParagraphDefaultBlockElement.NumberOfNewLinesToReplace == 2) string htmlFromText = Regex.Replace(text, @"(?<plainText>[^\r\n]+)?(?<succeedingNewLines>(\r\n){0," + defaultBlockElement.NumberOfNewLinesToReplace + "})", delegate(Match match) { Group plainText = match.Groups["plainText"]; Group succeedingNewLines = match.Groups["succeedingNewLines"]; if (plainText.Length == 0 && succeedingNewLines.Length == 0) { return(string.Empty); } StringBuilder html = new StringBuilder(); if (!insideBlockElement) { html.Append(defaultBlockElement.BeginTag); insideBlockElement = true; blockElementIsEmpty = true; } if (plainText.Length > 0) { html.Append(plainText.Value); blockElementIsEmpty = false; } // The length of succeedingNewLines is the number of characters captured and each newline is two characters: \r\n. int numberOfSucceedingNewLines = succeedingNewLines.Length / 2; if (numberOfSucceedingNewLines == defaultBlockElement.NumberOfNewLinesToReplace) { if (blockElementIsEmpty) { // Manually inflate the element, otherwise it won't be rendered. html.Append(" "); } html.AppendLine(defaultBlockElement.EndTag); insideBlockElement = false; } else { for (int i = 0; i < numberOfSucceedingNewLines; i++) { html.AppendLine("<br />"); blockElementIsEmpty = false; } } return(html.ToString()); }); return(insideBlockElement ? htmlFromText + defaultBlockElement.EndTag : htmlFromText); }
public BasicHtmlGenerationService(DefaultBlockElement defaultBlockElement) { _defaultBlockElement = defaultBlockElement; }