private void cmdCreateDynamicDocument_Click(object sender, RoutedEventArgs e) { // Create first part of sentence. Run runFirst = new Run(); runFirst.Text = "Hello world of "; // Create bolded text. Bold bold = new Bold(); Run runBold = new Run(); runBold.Text = "dynamically generated"; bold.Inlines.Add(runBold); // Create last part of sentence. Run runLast = new Run(); runLast.Text = " documents"; // Add three parts of sentence to a paragraph, in order. Paragraph paragraph = new Paragraph(); paragraph.Inlines.Add(runFirst); paragraph.Inlines.Add(bold); paragraph.Inlines.Add(runLast); // Create a document and add this paragraph. FlowDocument document = new FlowDocument(); document.Blocks.Add(paragraph); // Show the document. docViewer.Document = document; }
/// <summary> /// This method returns a simple paragraph text of header. /// </summary> /// <param name="patternName">The name of pattern we want to display</param> /// <param name="hitStart">Start position of our hit</param> /// <param name="hitEnd">End position of our hit</param> /// <returns>A paragraph of text for our header.</returns> static public Paragraph GetRichHeader (String patternName, int hitStart, int hitEnd) { // Create our bold header bold text. Bold myBold = new Bold(); myBold.Inlines.Add("Sequence Hits Viewer"); Run myRun2 = new Run(); myRun2.Text = "================"; myRun2.Text += NEWLINE; myRun2.Text += NEWLINE; myRun2.Text += "Matched Start Position : [ " + hitStart + " ]"; myRun2.Text += NEWLINE; myRun2.Text += "Matched End Position : [ " + hitEnd + " ]"; myRun2.Text += NEWLINE; myRun2.Text += NEWLINE; myRun2.Text += "================ " + patternName + " ================"; myRun2.Text += NEWLINE; Paragraph Header = new Paragraph(); Header.Inlines.Add(myBold); Header.Inlines.Add(myRun2); return Header; }
private void PopulateDocument() { // Add some data to the List item. this.listOfFunFacts.FontSize = 14; this.listOfFunFacts.MarkerStyle = TextMarkerStyle.Circle; this.listOfFunFacts.ListItems.Add(new ListItem(new Paragraph(new Run("Fixed documents are for WYSIWYG print ready docs!")))); this.listOfFunFacts.ListItems.Add(new ListItem( new Paragraph(new Run("The API supports tables and embedded figures!")))); this.listOfFunFacts.ListItems.Add(new ListItem( new Paragraph(new Run("Flow documents are read only!")))); this.listOfFunFacts.ListItems.Add(new ListItem(new Paragraph(new Run ("BlockUIContainer allows you to embed WPF controls in the document!") ))); // Now add some data to the Paragraph. // First part of sentence. Run prefix = new Run("This paragraph was generated "); // Middle of paragraph. Bold b = new Bold(); Run infix = new Run("dynamically"); infix.Foreground = Brushes.Red; infix.FontSize = 30; b.Inlines.Add(infix); // Last part of paragraph. Run suffix = new Run(" at runtime!"); // Now add each piece to the collection of inline elements // of the Paragraph. this.paraBodyText.Inlines.Add(prefix); this.paraBodyText.Inlines.Add(infix); this.paraBodyText.Inlines.Add(suffix); }
public void WriteReference(string text, object reference) { CheckCompleteLine(); var bold = new Bold(); bold.Inlines.Add(new Run { Text = text }); this.blocks.Last().Inlines.Add(bold); }
private void WriteLog(string text, Brush color) { Bold myrun = new Bold(); myrun.Inlines.Add(text); myrun.Foreground = color; _pgph.Inlines.Add(myrun); _pgph.Inlines.Add(Environment.NewLine); }
public static void Append(this Paragraph paragraph, string value = "", Brush background = null, Brush foreground = null, bool bold = false, bool italic = false, bool underline = false) { Inline run = new Run(value); if (background != null) run.Background = background; if (foreground != null) run.Foreground = foreground; if (bold) run = new Bold(run); if (italic) run = new Italic(run); if (underline) run = new Underline(run); paragraph.Inlines.Add(run); }
private Inline GetInlineWithStyling( string line, System.Drawing.FontStyle style ) { Inline styledText = new Run( line ); if ( style.HasFlag( System.Drawing.FontStyle.Bold ) ) styledText = new Bold( styledText ); if ( style.HasFlag( System.Drawing.FontStyle.Italic ) ) styledText = new Italic( styledText ); if ( style.HasFlag( System.Drawing.FontStyle.Underline ) ) styledText = new Underline( styledText ); return styledText; }
private TreeViewItem AddNodeToTreeview(ItemsControl parent, string fieldName, string fieldValue) { // Is the value null? fieldValue = fieldValue ?? ""; // Create a span and add content to it var span = new SysDoc.Span(); var nameBold = new SysDoc.Bold(); nameBold.Inlines.Add(new SysDoc.Run(fieldName + ": ")); span.Inlines.Add(nameBold); span.Inlines.Add(fieldValue); return(AddNodeToTreeview(parent, span)); }
public MainWindow() { InitializeComponent(); Doc = new FlowDocument(); Paragraph para = new Paragraph(); para.Inlines.Add("normal"); Bold b = new Bold(); b.Inlines.Add("Bold"); para.Inlines.Add(b); Italic it = new Italic(); it.Inlines.Add("italic"); para.Inlines.Add(it); Doc.Blocks.Add(para); this.DataContext = Doc; }
public static FlowDocument PrintRecipe(Recipe r) { // Before printing check that all fields are valid if (r.Name == String.Empty || r.Time == String.Empty || r.Instructions == String.Empty || r.Writer == String.Empty) { throw new Exception("Reseptissä ei voi olla tyhjiä kenttiä!"); } // If all fields are valid print the recipe else { // Create a FlowDocument FlowDocument doc = new FlowDocument(); // Create a Section Section sec = new Section(); Section sec2 = new Section(); // Create first Paragraph Paragraph p1 = new Paragraph(); Paragraph p2 = new Paragraph(); // Create and add a new Bold, Italic and Underline Bold bld = new Bold(); bld.Inlines.Add(new Run(r.Name)); Italic italicBld = new Italic(); italicBld.Inlines.Add(bld); Underline underlineItalicBld = new Underline(); underlineItalicBld.Inlines.Add(italicBld); // Add Bold, Italic, Underline to Paragraph p1.Inlines.Add(underlineItalicBld); p1.Inlines.Add(new Run("\n" + r.Time)); p1.Inlines.Add(new Run("\n" + r.Writer)); p2.Inlines.Add(new Run(r.Instructions)); // Add Paragraph to Section sec.Blocks.Add(p1); sec2.Blocks.Add(p2); // Add Section to FlowDocument doc.Blocks.Add(sec); doc.Blocks.Add(sec2); return doc; } }
public void UpdateCurrentTaskDescription(string text) { string[] delimiters = { "*" }; String[] items = text.Split(delimiters, StringSplitOptions.None); InstructionLabel.Inlines.Clear(); bool bold = text.StartsWith("*"); foreach (var item in items) { Inline nextInline = new Run(item); if (bold) { //wrap into bold nextInline = new Bold(nextInline); } InstructionLabel.Inlines.Add(nextInline); bold = !bold; } }
/// <summary> /// Handles the Loaded event of the Window control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param> private void WindowLoaded(object sender, RoutedEventArgs e) { if (AeroGlassCompositionEnabled) { SetAeroGlassTransparency(); } _original = new Dictionary<string, string>(); if (Parser.CanLogin) { var login = Settings.Get(Parser.Name + " Login"); if (!string.IsNullOrWhiteSpace(login)) { try { var ua = Utils.Decrypt(Parser.GetType(), login); usernameTextBox.Text = _original["user"] = ua[0]; passwordTextBox.Password = _original["pass"] = ua[1]; } catch { } } } if (Parser.RequiredCookies.Length != 0) { for (var i = 0; i < Parser.RequiredCookies.Length; i++) { var b = new Bold(); b.Inlines.Add(Parser.RequiredCookies[i]); requiredCookies.Inlines.Add(b); if (i != Parser.RequiredCookies.Length - 1) { requiredCookies.Inlines.Add(", "); } } } cookiesTextBox.Text = _original["cookies"] = Utils.Decrypt(Parser.GetType(), Settings.Get(Parser.Name + " Cookies"))[0]; }
void AppendText(string text, System.Windows.Media.Brush color, bool bold) { var doc = _logger.Document; Paragraph paragraph = new Paragraph(); paragraph.Foreground = color; paragraph.LineHeight = 5; Inline content = new Run(text); if (bold) { content = new Bold(content); } paragraph.Inlines.Add(content); doc.Blocks.Add(paragraph); }
/// <summary> /// This method returns a simple paragraph text of header. /// </summary> /// <param name="patternName">The name of pattern we want to display</param> /// <param name="hitStart">Start position of our hit</param> /// <param name="hitEnd">End position of our hit</param> /// <returns>A paragraph of text for our header.</returns> static public Paragraph GetRichHeader ( String patternName, int hitStart, int hitEnd ) { // Create our bold header bold text. Bold myBold = new Bold(); myBold.Inlines.Add( "Selected match:" ); Run myRun2 = new Run(); myRun2.Text += NEWLINE; myRun2.Text += patternName + ": " + hitStart + " - " + hitEnd; myRun2.Text += NEWLINE; myRun2.Text += NEWLINE; Paragraph Header = new Paragraph(); Header.Inlines.Add( myBold ); Header.Inlines.Add( myRun2 ); return Header; }
public static IEnumerable<Paragraph> CreateParagraph(this Message message, IModelContext context) { var paragraphs = new List<Paragraph>(); var name = GetName(message, context); var title = new Bold(new Run(string.Format("{0} {1:hh:mm}: ", name, message.Date))); var paragraph = new Paragraph(); paragraph.Inlines.Add(title); paragraphs.Add(paragraph); if (message.Type == MessageType.Xaml) { var body = ParseXamlString(message.Body); paragraphs.AddRange(body.Blocks.Select(block => block as Paragraph)); } else { var body = new Run(message.Body); paragraph.Inlines.Add(body); } return paragraphs; }
public Block CreateBlock(HistoryCommandMessage message) { var paragraph = new Paragraph(); paragraph.Inlines.Add("Show messages from: "); foreach (var timeFrameParam in message.Frames) { Inline frame; if (timeFrameParam.Enabled) { var hyperlink = new Hyperlink(new Run(timeFrameParam.DisplayingValue)); var param = timeFrameParam; hyperlink.Click += (sender, args) => message.Callback(param); frame = hyperlink; } else { var disabled = new Bold(new Run(timeFrameParam.DisplayingValue)); frame = disabled; } paragraph.Inlines.Add(frame); paragraph.Inlines.Add(new Run(" ")); } return paragraph; }
public FlowDocument BuildCleanerDetails(cleaner c) { FlowDocument doc = new FlowDocument(); Paragraph p = new Paragraph(); // header Run label = new Run(); label.Text = c.label; label.FontSize = 20; Bold label_bold = new Bold(label); p.Inlines.Add(label_bold); p.Inlines.Add(new LineBreak()); // cleaner description p.Inlines.Add(new Run(c.description)); p.Inlines.Add(new LineBreak()); p.Inlines.Add(new LineBreak()); p.Inlines.Add(new LineBreak()); // cleaner options foreach (option o in c.option) { label = new Run(); label.Text = o.label + ": "; //label.FontSize = 20; label_bold = new Bold(label); p.Inlines.Add(label_bold); p.Inlines.Add(new Run(o.description)); p.Inlines.Add(new LineBreak()); // insert actions? p.Inlines.Add(string.Format("There {0} {1} actions in this option.", o.action.Count == 1 ? "is" : "are", o.action.Count)); //foreach (action a in o.action) //{ //} p.Inlines.Add(new LineBreak()); p.Inlines.Add(new LineBreak()); } doc.Blocks.Add(p); return doc; }
public void parse_DownloadProductReportPageCompleted(Object sender, HtmlDocumentLoadCompleted e) { if (e != null && e.Document != null && e.Document.DocumentNode != null) { IList<Block> pageBody = new List<Block>(); IList<HtmlNode> hnc = e.Document.DocumentNode.DescendantNodes().ToList(); Paragraph paragraph = new Paragraph(); Boolean content_flag = false; foreach (HtmlNode htmlNode in hnc) { if (htmlNode.Name.ToLower() == "h1" && htmlNode.Attributes.Count == 0) { PageTitle.Text = htmlNode.InnerText.Replace("�", "'"); content_flag = true; } else if (content_flag && htmlNode.Name.ToLower() == "h2") { if (paragraph.Inlines.Count > 0) { pageBody.Add(paragraph); paragraph = new Paragraph(); } if (htmlNode.InnerText == "Related Health Canada Web content:") { content_flag = false; } else { Paragraph h2 = new Paragraph(); h2.FontSize = 25.333; h2.Inlines.Add(htmlNode.InnerText.Trim()); pageBody.Add(h2); } } else if (content_flag && htmlNode.Name.ToLower() == "ul") { if (htmlNode.ParentNode.Name.ToLower() != "p") { if (paragraph.Inlines.Count > 0) { pageBody.Add(paragraph); paragraph = new Paragraph(); } Paragraph np = new Paragraph(); foreach (HtmlNode a in htmlNode.DescendantNodes().ToList()) { if (a.Name.ToLower() == "a") { Boolean err_flag = false; Hyperlink hl = new Hyperlink(); hl.Inlines.Add(a.InnerText); foreach (HtmlAttribute att1 in a.Attributes) { if (att1.Name.ToLower() == "href") { try { if (att1.Value.ToCharArray()[0] != '#') { hl.NavigateUri = new Uri("/ProductReportPage.xaml?external=true&href=" + att1.Value, UriKind.Relative); } else { err_flag = true; } } catch (Exception err) { err_flag = true; } break; } } if (!err_flag) { np.Inlines.Add(hl); } else { Run r = new Run(); r.Text = a.InnerText.Replace(" ", ""); np.Inlines.Add(r); } } else if (a.Name.ToLower() == "li") { Bold b = new Bold(); b.Inlines.Add("- "); np.Inlines.Add(b); } else if (a.Name.ToLower() == "b" || a.ParentNode.Name.ToLower() == "strong") { Bold b = new Bold(); b.Inlines.Add(a.InnerText.Replace(" ", "")); np.Inlines.Add(b); } else if (a.Name.ToLower() == "i") { Italic i = new Italic(); i.Inlines.Add(a.InnerText.Replace(" ", "")); np.Inlines.Add(i); } else if (a.Name.ToLower() == "#text") { if (a.ParentNode.Name.ToLower() != "a" && a.ParentNode.Name.ToLower() != "b" && a.ParentNode.Name.ToLower() != "strong" && a.ParentNode.Name.ToLower() != "i") { String str = ConvertWhitespacesToSingleSpaces(a.InnerText); if (str != " ") { str = str.Replace(""", "\""); Run run = new Run(); run.Text = str.Replace(" ", ""); np.Inlines.Add(run); } if (a.NextSibling != null && a.NextSibling.Name.ToLower() == "li") { np.Inlines.Add(new LineBreak()); } } } } np.Inlines.Add(new LineBreak()); pageBody.Add(np); } } else if (content_flag && htmlNode.Name.ToLower() == "p") { if (paragraph.Inlines.Count > 0) { pageBody.Add(paragraph); paragraph = new Paragraph(); } Paragraph np = new Paragraph(); foreach (HtmlNode pc in htmlNode.DescendantNodes().ToList()) { if (content_flag && htmlNode.Name.ToLower() == "ul") { foreach (HtmlNode a in htmlNode.DescendantNodes().ToList()) { if (a.Name.ToLower() == "a") { Boolean err_flag = false; Hyperlink hl = new Hyperlink(); hl.Inlines.Add(a.InnerText.Replace(" ", "")); foreach (HtmlAttribute att1 in a.Attributes) { if (att1.Name.ToLower() == "href") { try { if (att1.Value.ToCharArray()[0] != '#') { hl.NavigateUri = new Uri("/ProductReportPage.xaml?external=true&href=" + att1.Value, UriKind.Relative); } else { err_flag = true; } } catch (Exception err) { err_flag = true; } break; } } if (!err_flag) { np.Inlines.Add(hl); } else { Run r = new Run(); r.Text = a.InnerText.Replace(" ", ""); np.Inlines.Add(r); } } else if (a.Name.ToLower() == "li") { Bold b = new Bold(); b.Inlines.Add("- "); np.Inlines.Add(b); } else if (a.Name.ToLower() == "b" || a.ParentNode.Name.ToLower() == "strong") { Bold b = new Bold(); b.Inlines.Add(a.InnerText.Replace(" ", "")); np.Inlines.Add(b); } else if (a.Name.ToLower() == "i") { Italic i = new Italic(); i.Inlines.Add(a.InnerText.Replace(" ", "")); np.Inlines.Add(i); } else if (a.Name.ToLower() == "#text") { if (a.ParentNode.Name.ToLower() != "a" && a.ParentNode.Name.ToLower() != "b" && a.ParentNode.Name.ToLower() != "strong" && a.ParentNode.Name.ToLower() != "i") { String str = ConvertWhitespacesToSingleSpaces(a.InnerText); if (str != " ") { str = str.Replace(""", "\""); Run run = new Run(); run.Text = str.Replace(" ", ""); np.Inlines.Add(run); } if (a.NextSibling != null && a.NextSibling.Name.ToLower() == "li") { np.Inlines.Add(new LineBreak()); } } } } np.Inlines.Add(new LineBreak()); } else if (pc.Name.ToLower() == "a") { if (pc.ParentNode.Name.ToLower() != "i" && pc.ParentNode.Name.ToLower() != "b" && pc.ParentNode.Name.ToLower() != "strong") { Boolean image_flag = false; Boolean flag_local = false; Hyperlink hl = new Hyperlink(); hl.Inlines.Add(pc.InnerText.Replace(" ", "")); foreach (HtmlAttribute att1 in pc.Attributes) { if (att1.Name.ToLower() == "href") { try { if (att1.Value.ToCharArray()[0] != '#') { hl.NavigateUri = new Uri("/ProductReportPage.xaml?external=true&href=" + att1.Value, UriKind.Relative); } else { flag_local = true; } } catch (Exception err) { image_flag = true; } } else if (att1.Name.ToLower() == "class" && att1.Value == "image") { image_flag = true; } } if (!image_flag && !flag_local) { np.Inlines.Add(hl); } else if (flag_local) { Run r = new Run(); r.Text = pc.InnerText.Replace(" ", ""); np.Inlines.Add(r); } } } else if (pc.Name.ToLower() == "#text") { if (pc.ParentNode.Name.ToLower() != "a" && pc.ParentNode.Name.ToLower() != "b" && pc.ParentNode.Name.ToLower() != "strong" && pc.ParentNode.Name.ToLower() != "i") { String str = ConvertWhitespacesToSingleSpaces(pc.InnerText); if (str != " ") { str = str.Replace(""", "\""); Run run = new Run(); run.Text = str.Replace(" ", ""); np.Inlines.Add(run); } } } else if (pc.Name.ToLower() == "b" || pc.Name.ToLower() == "strong") { Bold b = new Bold(); foreach (HtmlNode n in pc.DescendantNodes().ToList()) { if (n.Name.ToLower() == "#text" && n.ParentNode.Name.ToLower() != "a") { b.Inlines.Add(n.InnerText.Replace(" ", "")); } else if (n.Name.ToLower() == "a") { Boolean image_flag = false; Boolean flag_local = false; Hyperlink hl = new Hyperlink(); hl.Inlines.Add(n.InnerText.Replace(" ", "")); foreach (HtmlAttribute att1 in n.Attributes) { if (att1.Name.ToLower() == "href") { try { if (att1.Value.ToCharArray()[0] != '#') { hl.NavigateUri = new Uri("/ProductReportPage.xaml?external=true&href=" + att1.Value, UriKind.Relative); } else { flag_local = true; } } catch (Exception err) { image_flag = true; } } else if (att1.Name.ToLower() == "class" && att1.Value == "image") { image_flag = true; } } if (!image_flag && !flag_local) { b.Inlines.Add(hl); } else { b.Inlines.Add(n.InnerText.Replace(" ", "")); } } } np.Inlines.Add(b); } else if (pc.Name.ToLower() == "br") { // Run r = new Run(); // r.Text = "\n"; // np.Inlines.Add(r); } else if (pc.Name.ToLower() == "i") { Italic i = new Italic(); foreach (HtmlNode n in pc.DescendantNodes().ToList()) { if (n.Name.ToLower() == "#text" && n.ParentNode.Name.ToLower() != "a") { i.Inlines.Add(n.InnerText.Replace(" ", "")); } else if (n.Name.ToLower() == "a") { Boolean image_flag = false; Boolean flag_local = false; Hyperlink hl = new Hyperlink(); hl.Inlines.Add(n.InnerText.Replace(" ", "")); foreach (HtmlAttribute att1 in n.Attributes) { if (att1.Name.ToLower() == "href") { try { if (att1.Value.ToCharArray()[0] != '#') { hl.NavigateUri = new Uri("/ProductReportPage.xaml?external=true&href=" + att1.Value, UriKind.Relative); } else { flag_local = true; } } catch (Exception err) { image_flag = true; } } else if (att1.Name.ToLower() == "class" && att1.Value == "image") { image_flag = true; } } if (!image_flag && !flag_local) { i.Inlines.Add(hl); } else { i.Inlines.Add(n.InnerText.Replace(" ", "")); } } } np.Inlines.Add(i); } } np.Inlines.Add(new LineBreak()); pageBody.Add(np); } } if (paragraph != null && paragraph.Inlines.Count > 0) { pageBody.Add(paragraph); } foreach (Block b in pageBody) { RichTextBox rtb = new RichTextBox(); rtb.IsReadOnly = true; rtb.VerticalAlignment = VerticalAlignment.Top; rtb.Blocks.Add(b); PageBody.Children.Add(rtb); } LoadingProductScreen.IsOpen = false; PageBody.InvalidateArrange(); PageBody.InvalidateMeasure(); scrollerViewer.InvalidateArrange(); scrollerViewer.InvalidateMeasure(); scrollerViewer.InvalidateScrollInfo(); Content.InvalidateArrange(); Content.InvalidateMeasure(); } }
private static Inline GetInline(FrameworkElement element, InlineDescription description) { Style style = null; if (!string.IsNullOrEmpty(description.StyleName)) { style = element.FindResource(description.StyleName) as Style; if (style == null) throw new InvalidOperationException("The style '" + description.StyleName + "' cannot be found"); } Inline inline = null; switch (description.Type) { case InlineType.Run: var run = new Run(description.Text); inline = run; break; case InlineType.LineBreak: var lineBreak = new LineBreak(); inline = lineBreak; break; case InlineType.Span: var span = new Span(); inline = span; break; case InlineType.Bold: var bold = new Bold(); inline = bold; break; case InlineType.Italic: var italic = new Italic(); inline = italic; break; case InlineType.Hyperlink: var hyperlink = new Hyperlink(); inline = hyperlink; break; case InlineType.Underline: var underline = new Underline(); inline = underline; break; } if (inline != null) { var span = inline as Span; if (span != null) { var childInlines = description.Inlines.Select(inlineDescription => GetInline(element, inlineDescription)) .Where(childInline => childInline != null) .ToList(); span.Inlines.AddRange(childInlines); } if (style != null) inline.Style = style; } return inline; }
// Recursively parses the given Html node into a corresponding Inline element private static Inline _parseHTMLNode(XNode node, HtmlBlock source) { if (node.NodeType == XmlNodeType.Text) { var text = ((XText)node).Value; text = text.ReplaceAll(_reWhitespace, " "); text = text.ReplaceAll(_reEncodedEntity, match => { var code = match.Groups[1].Value; if (code.At(0) == "#") { return Char.ConvertFromUtf32(Int32.Parse(code.After(0))); } else if (_htmlEntities.ContainsKey(code)) { return Char.ConvertFromUtf32(_htmlEntities[code]); } else { throw new Exception(TEXT.HtmlBlock_UnrecognizedChar.Substitute(code)); } }); return new Run(text); } if (node.NodeType != XmlNodeType.Element) { return null; } var tag = (XElement)node; var name = tag.Name.LocalName.ToLower(); Span outer = null; Brush emphBrush = null; double fontSize = 11; double paraBreak = 0; if (source != null) { emphBrush = source.EmphasizedForeground; fontSize = Double.IsNaN(source.FontSize) ? 11 : source.FontSize; } // hyperlink if (name == "a") { var link = new Hyperlink(); var href = tag.Get<Uri>("href"); if (href != null) link.NavigateUri = href; var trg = tag.Get("target"); if (trg.NotEmpty()) link.TargetName = trg; outer = link; } // bold else if (name == "b") { outer = new Bold(); } // big else if (name == "big") { outer = new Span(); outer.FontSize = fontSize * _fontFactors[4]; } // line break else if (name == "br") { return new LineBreak(); } // code else if (name == "c" || name == "code") { outer = new Span(); outer.FontFamily = new FontFamily("Courier New"); } // code else if (name == "em") { outer = new Span(); if (emphBrush != null) outer.Foreground = emphBrush; } // font style else if (name == "font") { outer = new Span(); var face = tag.Get("face"); if (face.NotEmpty()) outer.FontFamily = new FontFamily(face); var brush = tag.Get<Brush>("color", null); if (brush != null) outer.Foreground = brush; var size = tag.Get<int>("size", -1); if (size > 0) outer.FontSize = size; } // header 1-6 else if (name.Matches(_reHeaderTag)) { outer = new Bold(); if (emphBrush != null) outer.Foreground = emphBrush; outer.FontSize = fontSize * _fontFactors[7-Int32.Parse(name.At(1))]; paraBreak = 1; } // italic else if (name == "i") { outer = new Italic(); } // image else if (name == "img") { outer = new Span(); var uic = new InlineUIContainer(); var img = new Image(); var src = tag.GetImage("src"); if (src != null) img.Source = src; var w = tag.Get<int>("width", -1); if (w >= 0) img.Width = w; var h = tag.Get<int>("height", -1); if (h >= 0) img.Height = h; uic.Child = img; outer.Inlines.Add(uic); } // paragraph else if (name == "p") { outer = new Span(); paraBreak = 4; } // small else if (name == "small") { outer = new Span(); outer.FontSize = fontSize * _fontFactors[2]; } // span else if (name == "span") { outer = new Span(); } // underline else if (name == "u") { outer = new Underline(); } // invalid tag else { throw new Exception(TEXT.HtmlBlock_UnrecognizedTag.Substitute(tag.Name.LocalName)); } var tip = tag.GetImage("title"); if (tip != null) { outer.ToolTip = tip; } foreach (var child in tag.Nodes()) { var inner = _parseHTMLNode(child, source); if (inner != null) outer.Inlines.Add(inner); } if (paraBreak == 0) return outer; var para = new Span(); para.Inlines.Add(outer); para.Inlines.Add(new LineBreak()); var blankline = new Span(); blankline.FontSize = paraBreak; para.Inlines.Add(blankline); para.Inlines.Add(new LineBreak()); return para; }
private void fillRTF(RichTextBox box, int[,] dataArray, int selectMode) { FlowDocument displayedText = new FlowDocument(); for (int i = 0; i < 16; i++) { Paragraph currentLine = new Paragraph(); if (i <= currentRow && i >= currentRow - (selectMode-1)) { Run currentLineStart = new Run(); for (int column = 0; column < currentColumn; column++) { currentLineStart.Text += String.Format("{0,4}", dataArray[i, column]); } Bold currentElement = new Bold(); currentElement.Inlines.Add(String.Format("{0,4}", dataArray[i, currentColumn])); if (i == currentRow) { currentElement.Background = new SolidColorBrush(Colors.DarkOrange); } else { currentElement.Background = new SolidColorBrush(Colors.DarkMagenta); } Run currentLineEnd = new Run(); for (int column = currentColumn + 1; column < 16; column++) { currentLineEnd.Text += String.Format("{0,4}", dataArray[i, column]); } /* Style smallParagraphs = new Style(typeof(Paragraph)); smallParagraphs.Setters.Add(new Setter { Property = Paragraph.TextIndentProperty, Value = 30.0 }); currentLine.Style = smallParagraphs; */ currentLine.Inlines.Add(currentLineStart); currentLine.Inlines.Add(currentElement); currentLine.Inlines.Add(currentLineEnd); } else { Run currentLineStart = new Run(); for (int column = 0; column < 16; column++) { currentLineStart.Text += String.Format("{0,4}", dataArray[i, column]); } currentLine.Inlines.Add(currentLineStart); } displayedText.Blocks.Add(currentLine); } box.Document = displayedText; }
private IEnumerable<Inline> ConversationMessageToInlines(IConversationMessage message) { string senderNameString; string timestampString; string messageContents = message.MessageContents; List<Inline> messageInlines = new List<Inline>(); SolidColorBrush senderBrush; Span messagePrefixSpan = new Span(); senderNameString = GetSenderDisplayName(message); senderBrush = GetSenderBrush(message); Bold senderName = new Bold(new Run(senderNameString)); messagePrefixSpan.Foreground = senderBrush; messagePrefixSpan.Inlines.Add(senderName); timestampString = FormatTimeForConversation(message.Timestamp); if (timestampString != null) { string formattedTimestamp = string.Format(" (" + '\u200E' + "{0}" + '\u202C' + ")", timestampString); Run timestampRun = new Run(formattedTimestamp); messagePrefixSpan.Inlines.Add(timestampRun); } messagePrefixSpan.Inlines.Add(new Run(": ")); messageInlines.Add(messagePrefixSpan); messageInlines.Add(new ConversationContentRun(messageContents)); return messageInlines; }
public void parse_DownloadWikiPageCompleted(Object sender, HtmlDocumentLoadCompleted e) { if (e != null && e.Document != null && e.Document.DocumentNode != null) { IList<Block> pageBody = new List<Block>(); IList<HtmlNode> hnc = e.Document.DocumentNode.DescendantNodes().ToList(); Paragraph paragraph = new Paragraph(); Boolean flag = false; Boolean flag_table = false; foreach (HtmlNode htmlNode in hnc) { try { if (flag_table && htmlNode.PreviousSibling != null && htmlNode.PreviousSibling.Name.ToLower() == "table") { flag_table = false; } } catch (Exception err) { Console.Error.Write(err.StackTrace); } if (htmlNode.Name.ToLower() == "div") { foreach (HtmlAttribute att in htmlNode.Attributes) { if (att.Name.ToLower() == "id" && att.Value == "bodyContent") { flag = true; break; } else if (att.Name.ToLower() == "class" && att.Value == "printfooter") { flag = false; goto BreakParseLoop; } } } else if (htmlNode.Name.ToLower() == "table") { flag_table = true; } else if (flag && !flag_table && htmlNode.Name.ToLower() == "h2") { if (!(htmlNode.ParentNode.Name.ToLower() == "div" && htmlNode.ParentNode.Attributes.Count > 0 && htmlNode.ParentNode.Attributes[0].Value == "toctitle")) { if (paragraph.Inlines.Count > 0) { pageBody.Add(paragraph); paragraph = new Paragraph(); } Bold h2 = new Bold(); h2.Inlines.Add(htmlNode.InnerText); Paragraph para = new Paragraph(); para.Inlines.Add(h2); para.Inlines.Add(new LineBreak()); pageBody.Add(para); } } else if (flag && !flag_table && htmlNode.Name.ToLower() == "h3") { if (paragraph.Inlines.Count > 0) { pageBody.Add(paragraph); paragraph = new Paragraph(); } Bold h2 = new Bold(); h2.Inlines.Add(htmlNode.InnerText); Paragraph para = new Paragraph(); para.Inlines.Add(h2); para.Inlines.Add(new LineBreak()); pageBody.Add(para); } else if (flag && !flag_table && htmlNode.Name.ToLower() == "#text") { if (htmlNode.ParentNode.Name.ToLower() != "a" && htmlNode.ParentNode.Name.ToLower() != "b" && htmlNode.ParentNode.Name.ToLower() != "p" && htmlNode.ParentNode.Name.ToLower() != "i" && htmlNode.ParentNode.Name.ToLower() != "ul" && htmlNode.ParentNode.Name.ToLower() != "li" && htmlNode.ParentNode.Name.ToLower() != "h2" && htmlNode.ParentNode.Name.ToLower() != "h3" && htmlNode.ParentNode.Name.ToLower() != "td" && htmlNode.ParentNode.Name.ToLower() != "tr" && htmlNode.ParentNode.Name.ToLower() != "table" && !(htmlNode.ParentNode.Name.ToLower() == "div" && htmlNode.ParentNode.Attributes.Count > 0 && htmlNode.ParentNode.Attributes[0].Value == "jump-to-nav") && !(htmlNode.ParentNode.Name.ToLower() == "span" && htmlNode.ParentNode.ParentNode.Name.ToLower() == "td") && !(htmlNode.ParentNode.Name.ToLower() == "span" && htmlNode.ParentNode.ParentNode.Name.ToLower() == "tr") && !(htmlNode.ParentNode.Name.ToLower() == "span" && htmlNode.ParentNode.ParentNode.Name.ToLower() == "table") && !(htmlNode.ParentNode.Name.ToLower() == "span" && htmlNode.ParentNode.ParentNode.Name.ToLower() == "li") && !(htmlNode.ParentNode.Name.ToLower() == "span" && htmlNode.ParentNode.ParentNode.Name.ToLower() == "ul") && !(htmlNode.ParentNode.Name.ToLower() == "i" && htmlNode.ParentNode.ParentNode.Name.ToLower() == "p") && !(htmlNode.ParentNode.Name.ToLower() == "div" && htmlNode.ParentNode.Attributes.Count > 0 && htmlNode.ParentNode.Attributes[0].Value == "editsection") && !(htmlNode.ParentNode.Name.ToLower() == "span" && htmlNode.ParentNode.Attributes.Count > 0 && htmlNode.ParentNode.Attributes[0].Name == "class" && htmlNode.ParentNode.Attributes[0].Value == "toctext") && !(htmlNode.ParentNode.Name.ToLower() == "span" && htmlNode.ParentNode.Attributes.Count > 0 && htmlNode.ParentNode.Attributes[0].Name == "class" && htmlNode.ParentNode.Attributes[0].Value == "tocnumber") && htmlNode.ParentNode.Name.ToLower() != "script" && htmlNode.ParentNode.Name.ToLower() != "#comment" && htmlNode.ParentNode.Name.ToLower() != "dd" && htmlNode.ParentNode.Name.ToLower() != "dl") { String str = ConvertWhitespacesToSingleSpaces(htmlNode.InnerText); if (str != " ") { Run run = new Run(); run.Text = str; paragraph.Inlines.Add(run); } } } else if (flag && !flag_table && htmlNode.Name.ToLower() == "a") { if (htmlNode.ParentNode.Name != "p" && !(htmlNode.ParentNode.Name.ToLower() == "div" && htmlNode.ParentNode.Attributes.Count > 0 && htmlNode.ParentNode.Attributes[0].Value == "jump-to-nav") && htmlNode.ParentNode.Name.ToLower() != "li" && htmlNode.ParentNode.Name.ToLower() != "ul" && htmlNode.ParentNode.Name.ToLower() != "dd" && htmlNode.ParentNode.Name.ToLower() != "dl" && !(htmlNode.ParentNode.Name.ToLower() == "div" && htmlNode.ParentNode.Attributes.Count > 0 && htmlNode.ParentNode.Attributes[0].Value == "editsection") && !(htmlNode.ParentNode.Name.ToLower() == "i" && htmlNode.ParentNode.ParentNode.Name.ToLower() == "p")) { Boolean image_flag = false; Boolean flag_local = false; Hyperlink hl = new Hyperlink(); hl.Inlines.Add(htmlNode.InnerText); foreach (HtmlAttribute att1 in htmlNode.Attributes) { if (att1.Name.ToLower() == "href") { try { if (att1.Value.ToCharArray()[0] != '#') { hl.NavigateUri = new Uri("/WikiContentPage.xaml?href="+att1.Value, UriKind.Relative); } else { flag_local = true; } } catch (Exception err) { image_flag = true; } } else if (att1.Name.ToLower() == "class" && att1.Value == "image") { image_flag = true; } } if (!image_flag && !flag_local) { // hl.Click += new RoutedEventHandler(hyperlink_Click); paragraph.Inlines.Add(hl); } else if (flag_local) { Run r = new Run(); r.Text = htmlNode.InnerText; paragraph.Inlines.Add(r); } } } else if (flag && !flag_table && htmlNode.Name.ToLower() == "p") { if (paragraph.Inlines.Count > 0) { pageBody.Add(paragraph); paragraph = new Paragraph(); } Paragraph np = new Paragraph(); foreach (HtmlNode pc in htmlNode.DescendantNodes().ToList()) { if (pc.Name.ToLower() == "a") { if (pc.ParentNode.Name.ToLower() != "i" && pc.ParentNode.Name.ToLower() != "b") { Boolean image_flag = false; Boolean flag_local = false; Hyperlink hl = new Hyperlink(); hl.Inlines.Add(pc.InnerText); foreach (HtmlAttribute att1 in pc.Attributes) { if (att1.Name.ToLower() == "href") { try { if (att1.Value.ToCharArray()[0] != '#') { hl.NavigateUri = new Uri("/WikiContentPage.xaml?href=" + att1.Value, UriKind.Relative); } else { flag_local = true; } } catch (Exception err) { image_flag = true; } } else if (att1.Name.ToLower() == "class" && att1.Value == "image") { image_flag = true; } } if (!image_flag && !flag_local) { np.Inlines.Add(hl); } else if (flag_local) { Run r = new Run(); r.Text = pc.InnerText; np.Inlines.Add(r); } } } else if (pc.Name.ToLower() == "#text") { if (pc.ParentNode.Name.ToLower() != "a" && pc.ParentNode.Name.ToLower() != "b" && pc.ParentNode.Name.ToLower() != "i") { String str = ConvertWhitespacesToSingleSpaces(pc.InnerText); if (str != " ") { Run run = new Run(); run.Text = pc.InnerText; np.Inlines.Add(run); } } } else if (pc.Name.ToLower() == "b") { Bold b = new Bold(); foreach(HtmlNode n in pc.DescendantNodes().ToList()){ if (n.Name.ToLower() == "#text" && n.ParentNode.Name.ToLower() != "a"){ b.Inlines.Add(n.InnerText); } else if (n.Name.ToLower() == "a") { Boolean image_flag = false; Boolean flag_local = false; Hyperlink hl = new Hyperlink(); hl.Inlines.Add(n.InnerText); foreach (HtmlAttribute att1 in n.Attributes) { if (att1.Name.ToLower() == "href") { try { if (att1.Value.ToCharArray()[0] != '#') { hl.NavigateUri = new Uri("/WikiContentPage.xaml?href=" + att1.Value, UriKind.Relative); } else { flag_local = true; } } catch (Exception err) { image_flag = true; } } else if (att1.Name.ToLower() == "class" && att1.Value == "image") { image_flag = true; } } if (!image_flag && !flag_local) { b.Inlines.Add(hl); } else { b.Inlines.Add(n.InnerText); } } } np.Inlines.Add(b); } else if (pc.Name.ToLower() == "i") { Italic i = new Italic(); foreach (HtmlNode n in pc.DescendantNodes().ToList()) { if (n.Name.ToLower() == "#text" && n.ParentNode.Name.ToLower() != "a") { i.Inlines.Add(n.InnerText); } else if (n.Name.ToLower() == "a") { Boolean image_flag = false; Boolean flag_local = false; Hyperlink hl = new Hyperlink(); hl.Inlines.Add(n.InnerText); foreach (HtmlAttribute att1 in n.Attributes) { if (att1.Name.ToLower() == "href") { try { if (att1.Value.ToCharArray()[0] != '#') { hl.NavigateUri = new Uri("/WikiContentPage.xaml?href=" + att1.Value, UriKind.Relative); } else { flag_local = true; } } catch (Exception err) { image_flag = true; } } else if (att1.Name.ToLower() == "class" && att1.Value == "image") { image_flag = true; } } if (!image_flag && !flag_local) { i.Inlines.Add(hl); } else { i.Inlines.Add(n.InnerText); } } } np.Inlines.Add(i); } } pageBody.Add(np); } else if (flag && !flag_table && htmlNode.Name.ToLower() == "dl") { if (paragraph.Inlines.Count > 0) { pageBody.Add(paragraph); paragraph = new Paragraph(); } Paragraph np = new Paragraph(); np.TextAlignment = TextAlignment.Justify; foreach (HtmlNode a in htmlNode.DescendantNodes().ToList()) { if (a.Name.ToLower() == "a") { Boolean err_flag = false; Hyperlink hl = new Hyperlink(); hl.Inlines.Add(a.InnerText); foreach (HtmlAttribute att1 in a.Attributes) { if (att1.Name.ToLower() == "href") { try { if (att1.Value.ToCharArray()[0] != '#') { hl.NavigateUri = new Uri("/WikiContentPage.xaml?href="+att1.Value, UriKind.Relative); } else { err_flag = true; } } catch (Exception err) { err_flag = true; } break; } } if (!err_flag) { np.Inlines.Add(hl); } else { Run r = new Run(); r.Text = a.InnerText; np.Inlines.Add(r); } } else if (a.Name.ToLower() == "dd") { try { if (a.PreviousSibling != null & a.PreviousSibling.Name.ToLower() == "dd") { np.Inlines.Add(new LineBreak()); } } catch (Exception err) { Console.Error.Write(err.StackTrace); } } else if (a.Name.ToLower() == "b") { Bold b = new Bold(); b.Inlines.Add(a.InnerText); np.Inlines.Add(b); } else if (a.Name.ToLower() == "i") { Italic i = new Italic(); i.Inlines.Add(a.InnerText); np.Inlines.Add(i); } else if (a.Name.ToLower() == "#text") { if (a.ParentNode.Name.ToLower() != "a" && a.ParentNode.Name.ToLower() != "b" && a.ParentNode.Name.ToLower() != "i") { String str = ConvertWhitespacesToSingleSpaces(a.InnerText); if (str != " ") { Italic i = new Italic(); i.Inlines.Add(str); np.Inlines.Add(i); } } } } np.Inlines.Add(new LineBreak()); pageBody.Add(np); } else if (flag && !flag_table && htmlNode.Name.ToLower() == "ul") { if (paragraph.Inlines.Count > 0) { pageBody.Add(paragraph); paragraph = new Paragraph(); } if (htmlNode.ParentNode.Name.ToLower() != "td" && htmlNode.ParentNode.Name.ToLower() != "tr" && htmlNode.ParentNode.Name.ToLower() != "table" && !(htmlNode.ParentNode.Name.ToLower() == "ul" && htmlNode.ParentNode.ParentNode != null && htmlNode.ParentNode.ParentNode.Name.ToLower() == "td") && !(htmlNode.ParentNode.Name.ToLower() == "li" && htmlNode.ParentNode.ParentNode != null && htmlNode.ParentNode.ParentNode.Name.ToLower() == "ul" && htmlNode.ParentNode.ParentNode.ParentNode.Name.ToLower() == "td")) { Paragraph np = new Paragraph(); foreach (HtmlNode a in htmlNode.DescendantNodes().ToList()) { if (a.Name.ToLower() == "a") { Boolean err_flag = false; Hyperlink hl = new Hyperlink(); hl.Inlines.Add(a.InnerText); foreach (HtmlAttribute att1 in a.Attributes) { if (att1.Name.ToLower() == "href") { try { if (att1.Value.ToCharArray()[0] != '#') { hl.NavigateUri = new Uri("/WikiContentPage.xaml?href=" + att1.Value, UriKind.Relative); } else { err_flag = true; } } catch (Exception err) { err_flag = true; } break; } } if (!err_flag) { np.Inlines.Add(hl); } else { Run r = new Run(); r.Text = a.InnerText; np.Inlines.Add(r); } } else if (a.Name.ToLower() == "li") { try { if (a.PreviousSibling != null & a.PreviousSibling.Name.ToLower() == "li") { np.Inlines.Add(new LineBreak()); } } catch (Exception err) { Console.Error.Write(err.StackTrace); } Bold b = new Bold(); b.Inlines.Add("- "); np.Inlines.Add(b); } else if (a.Name.ToLower() == "b") { Bold b = new Bold(); b.Inlines.Add(a.InnerText); np.Inlines.Add(b); } else if (a.Name.ToLower() == "i") { Italic i = new Italic(); i.Inlines.Add(a.InnerText); np.Inlines.Add(i); } else if (a.Name.ToLower() == "#text") { if (a.ParentNode.Name.ToLower() != "a" && a.ParentNode.Name.ToLower() != "b" && a.ParentNode.Name.ToLower() != "i") { String str = ConvertWhitespacesToSingleSpaces(a.InnerText); if (str != " ") { Run run = new Run(); run.Text = str; np.Inlines.Add(run); } } } } np.Inlines.Add(new LineBreak()); pageBody.Add(np); } } else if (htmlNode.Name.ToLower() == "h1") { foreach (HtmlAttribute att2 in htmlNode.Attributes) { if (att2.Name.ToLower() == "class" && att2.Value == "firstHeading") { PageTitle.Text = htmlNode.InnerText; } } } } BreakParseLoop: if (paragraph != null && paragraph.Inlines.Count > 0) { pageBody.Add(paragraph); } foreach (Block b in pageBody) { RichTextBox rtb = new RichTextBox(); rtb.IsReadOnly = true; rtb.VerticalAlignment = VerticalAlignment.Top; rtb.Blocks.Add(b); PageBody.Children.Add(rtb); } PageBody.InvalidateArrange(); PageBody.InvalidateMeasure(); scrollViewer1.InvalidateArrange(); scrollViewer1.InvalidateMeasure(); scrollViewer1.InvalidateScrollInfo(); } else { this.NavigationService.Navigate(new Uri("/ContentLoadError.xaml?href="+CurrentPage, UriKind.Relative)); } progress.Visibility = Visibility.Collapsed; }
private void UpdateTextWithHighlight(Dictionary<TextBlock, WindowSearchResult> highlightstack) { foreach (var key in highlightstack.Keys) { var textBlock = key; var windowResult = highlightstack[key]; var windowDisplayText = windowResult.ResultWindow.Title; List<int> listOfBoldIndexesForDisplayText; IOrderedEnumerable<int> listOfIndexesForProcessName; if (windowResult.BestScoreSource == WindowSearchResult.TextType.ProcessName) { listOfBoldIndexesForDisplayText = new List<int>(); listOfIndexesForProcessName = windowResult.SearchMatchesInProcessName.OrderBy(x => x); } else { listOfBoldIndexesForDisplayText = windowResult.SearchMatchesInTitle.OrderBy(x => x).ToList(); listOfIndexesForProcessName = new List<int>().OrderBy(x => x); } foreach(var i in listOfIndexesForProcessName) { listOfBoldIndexesForDisplayText.Add(i + windowDisplayText.Length + 2); } if (!windowResult.ResultWindow.ProcessName.ToUpper().Equals(string.Empty)) { windowDisplayText += " (" + windowResult.ResultWindow.ProcessName.ToUpper() + ")"; } int start = 0; textBlock.Inlines.Clear(); if (listOfBoldIndexesForDisplayText.Count() != 0) { foreach (int boldIndex in listOfBoldIndexesForDisplayText) { var r = new Run(windowDisplayText.Substring(start, boldIndex - start)); r.FontSize = 13; r.Foreground = new SolidColorBrush(Color.FromRgb(110,110,110)); textBlock.Inlines.Add(r); System.Diagnostics.Debug.Print(windowDisplayText + " " + windowDisplayText.Length + " " + boldIndex); r = new Run(windowDisplayText.Substring(boldIndex, 1)); r.Text = windowDisplayText.Substring(boldIndex, 1); var b = new Bold(r); b.FontSize = 15; // Different coloring for shortcut results if (windowResult.SearchResultMatchType == WindowSearchResult.SearchType.Shortcut) { b.Foreground = new SolidColorBrush(Color.FromRgb(198, 61, 15)); } textBlock.Inlines.Add(b); start = boldIndex + 1; } if (start < windowDisplayText.Length) { var r = new Run(windowDisplayText.Substring(start, windowDisplayText.Length - start)); r.FontSize = 13; r.Foreground = new SolidColorBrush(Color.FromRgb(110,110,110)); textBlock.Inlines.Add(r); } } else { var r = new Run(windowDisplayText); r.FontSize = 13; textBlock.Inlines.Add(r); } } }
private static void AddMessage(this Paragraph p, string message, bool append, bool isBold) { if (!isBold) { if (!append) p.Inlines.Add(message); else p.Inlines.Add("\n" + message); } else { if (!append) { var bold = new Bold(); bold.Inlines.Add(message); p.Inlines.Add(bold); } else { var bold = new Bold(); bold.Inlines.Add("\n" + message); p.Inlines.Add(bold); } } }
private static Span CreateSpan(InlineType inlineType, string param) { Span span = null; switch (inlineType) { case InlineType.Hyperlink: Hyperlink link = new Hyperlink(); Uri uri; if (Uri.TryCreate(param, UriKind.Absolute, out uri)) { link.NavigateUri = uri; } span = link; break; case InlineType.Bold: span = new Bold(); break; case InlineType.Italic: span = new Italic(); break; case InlineType.Underline: span = new Underline(); break; default: span = new Span(); break; } return span; }
/// <summary> /// Converts an HTML node into an Inline. /// </summary> private static Inline ToInline( HtmlNode node ) { switch ( node.Name ) { case "br": return new LineBreak(); case "a": string text = node.InnerText; string url = node.GetAttributeValue( "href", "" ); if ( string.IsNullOrWhiteSpace( text ) ) { text = url; } var link = new Hyperlink { Inlines = { new Run { Text = text, Foreground = new SolidColorBrush( Colors.Blue ) } }, NavigateUri = new Uri( url, UriKind.Absolute ), TargetName = "42" // can be anything, it just needs to be set }; link.Click += ( _, __ ) => LauncherEx.Launch( url ); return new Span { Inlines = { new Run { Text = " " }, link, new Run { Text = " " }, } }; case "strong": case "b": var bold = new Bold(); foreach ( var child in node.ChildNodes ) { bold.Inlines.Add( ToInline( child ) ); } return bold; case "em": case "i": var italic = new Italic(); foreach ( var child in node.ChildNodes ) { italic.Inlines.Add( ToInline( child ) ); } return italic; case "ul": var unorderedList = new Span(); foreach ( var child in node.ChildNodes ) { var listElem = new Span(); listElem.Inlines.Add( new Run { Text = "● " } ); listElem.Inlines.Add( ToInline( child ) ); unorderedList.Inlines.Add( listElem ); unorderedList.Inlines.Add( new LineBreak() ); } return unorderedList; case "ol": var orderedList = new Span(); for ( int n = 0; n < node.ChildNodes.Count; n++ ) { var listElem = new Span(); listElem.Inlines.Add( new Run { Text = n.ToString() + " " } ); listElem.Inlines.Add( ToInline( node.ChildNodes[n] ) ); orderedList.Inlines.Add( listElem ); orderedList.Inlines.Add( new LineBreak() ); } return orderedList; case "h1": return new Run { Text = node.InnerText + Environment.NewLine, FontWeight = FontWeights.Bold, FontSize = 32 }; case "h2": return new Run { Text = node.InnerText + Environment.NewLine, FontWeight = FontWeights.SemiBold, FontSize = 24 }; case "h3": return new Run { Text = node.InnerText + Environment.NewLine, FontWeight = FontWeights.SemiBold, FontSize = 19 }; case "h4": return new Run { Text = node.InnerText + Environment.NewLine, FontWeight = FontWeights.Medium, FontSize = 17 }; case "h5": return new Run { Text = node.InnerText + Environment.NewLine, FontWeight = FontWeights.Medium, FontSize = 16 }; case "div": case "p": case "blockquote": var container = new Span(); foreach ( var child in node.ChildNodes ) { container.Inlines.Add( ToInline( child ) ); } container.Inlines.Add( new LineBreak() ); container.Inlines.Add( new LineBreak() ); return container; } return new Run { Text = node.PreviousSibling == null ? node.InnerText.TrimStart() : node.InnerText }; }
private void PopulateDocument() { listOfFunFacts.FontSize = 14; listOfFunFacts.MarkerStyle = TextMarkerStyle.Circle; listOfFunFacts.ListItems.Add(new ListItem(new Paragraph(new Run("Fixed documents are for WYSIWYG print ready docs!")))); listOfFunFacts.ListItems.Add(new ListItem(new Paragraph(new Run("The API supports tables and embedded figures!")))); listOfFunFacts.ListItems.Add(new ListItem(new Paragraph(new Run("Flow documents are read only!")))); listOfFunFacts.ListItems.Add(new ListItem(new Paragraph(new Run("BlokcUIContainer allows you to embed WPF controls in the document!")))); Run prefix = new Run("This paragraph was generated "); Bold b = new Bold(); Run infix = new Run("dynamically"); infix.Foreground = Brushes.Red; infix.FontSize = 30; b.Inlines.Add(infix); Run suffix = new Run(" at runtime!"); paraBodyText.Inlines.Add(prefix); paraBodyText.Inlines.Add(infix); paraBodyText.Inlines.Add(suffix); }
public Inline StringToRun(String s, Brush b) { Inline ret = null; const string strUrlRegex = "(?i)\\b((?:[a-z][\\w-]+:(?:/{1,3}|[a-z0-9%])|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\".,<>?«»“”‘’]))"; var reg = new Regex(strUrlRegex); s = s.Trim(); //b = Brushes.Black; Inline r = new Run(s); if (reg.IsMatch(s)) { b = Brushes.LightBlue; var h = new Hyperlink(r); h.RequestNavigate += HRequestNavigate; try { h.NavigateUri = new Uri(s); } catch (UriFormatException) { s = "http://" + s; try { h.NavigateUri = new Uri(s); } catch (Exception) { r.Foreground = b; //var ul = new Underline(r); } } ret = h; } else { if (s.Equals(Program.LobbyClient.Username)) { b = Brushes.Blue; ret = new Bold(r); } else { Boolean fUser = false; if (listBox1.Items.Cast<NewUser>().Any(u => u.User.User == s)) { b = Brushes.LightGreen; ret = new Bold(r) {ToolTip = "Click to whisper"}; r.Cursor = Cursors.Hand; r.Background = Brushes.White; r.MouseEnter += delegate { r.Background = new RadialGradientBrush(Colors.DarkGray, Colors.WhiteSmoke); }; r.MouseLeave += delegate { r.Background = Brushes.White; }; fUser = true; } if (!fUser) { ret = new Run(s); } } } ret.Foreground = b; return ret; }
/// <summary> /// Parses an html string to an InlineCollection. The opening tags /// and closing tags MUST match, otherwise the result is undefined. /// </summary> /// <param name="html"></param> /// <remarks> /// The following HTML tags are supported: /// a -> Hyperlink /// b -> Bold /// i -> Italic /// u -> Underline /// br -> LineBreak (close tag optional) /// (plain text) -> Run /// /// The following WPF elements that are valid child elements of Span /// are not supported by this method: /// Figure, Floater, InlineUIContainer. /// </remarks> /// <returns></returns> private static Inline ConvertHtmlToInlines(string html) { if (html == null) throw new ArgumentNullException("html"); // Maintain a stack of the top Span element. For example, // <b><a href="somewhere">click me</a> if you <i>want</i>.</b> // would push an element to the stack for each open tag, and // pop an element from the stack for each close tag. Stack<Span> elementStack = new Stack<Span>(); Span top = new Span(); elementStack.Push(top); for (int index = 0; index < html.Length; ) { int k1 = html.IndexOf('<', index); if (k1 == -1) // all text { top.Inlines.Add(new Run(html.Substring(index))); break; } if (k1 > index) // at least some text { top.Inlines.Add(new Run(html.Substring(index, k1 - index))); index = k1; } // Now 'index' points to '<'. Search for '>'. int k2 = html.IndexOf('>', index + 1); if (k2 == -1) // '<' without '>' { top.Inlines.Add(new Run(html.Substring(index))); break; } string tagString = html.Substring(k1 + 1, k2 - k1 - 1); HtmlElement tag = HtmlElement.Parse(tagString); string tagName = (tag != null) ? tag.Name.ToLowerInvariant() : null; if (tagName == null) // parse failed; output as is { top.Inlines.Add(new Run(html.Substring(k1, k2 - k1 + 1))); } else if (tagName != "" && tagName[0] == '/') // close tag { if (tagName == "/a" && top is Hyperlink || tagName == "/b" && top is Bold || tagName == "/i" && top is Italic || tagName == "/u" && top is Underline || tagName == "/span" && top is Span) // TBD: might pop top element { elementStack.Pop(); top = elementStack.Peek(); } else { // unmatched close tag; output as is. top.Inlines.Add(new Run(html.Substring(k1, k2 - k1 + 1))); } } else // open tag or open-close tag (e.g. <br/>) { Inline element = null; switch (tagName) { case "span": element = new Span(); break; case "a": { Hyperlink hyperlink = new Hyperlink(); if (tag.Attributes != null) { foreach (HtmlAttribute attr in tag.Attributes) { if (attr.Name == "href") hyperlink.NavigateUri = new Uri(attr.Value, UriKind.RelativeOrAbsolute); } } element = hyperlink; } break; case "b": element = new Bold(); break; case "i": element = new Italic(); break; case "u": element = new Underline(); break; case "br": break; } if (element != null) // supported element { // Check global attributes. if (tag.Attributes != null) { foreach (HtmlAttribute attr in tag.Attributes) { if (attr.Name == "title") { ToolTipService.SetShowDuration(element, 60000); element.ToolTip = attr.Value; } } } top.Inlines.Add(element); if (element is Span && // not br html[k2 - 1] != '/') // not self-closed tag { elementStack.Push((Span)element); top = (Span)element; } } else // unsupported element, treat as text { top.Inlines.Add(new Run(html.Substring(k1, k2 - k1 + 1))); } } index = k2 + 1; } // Return the root element. Note that some open tags may not be // closed, but we ignore that. while (elementStack.Count > 0) { top = elementStack.Pop(); } return top; // .Inlines; }
public FlowDocument BuildCleanerDetails(cleaner c) { FlowDocument doc = new FlowDocument(); Paragraph p = new Paragraph(); // header Run label = new Run(); label.Text = c.label; label.FontSize = 20; Bold label_bold = new Bold(label); p.Inlines.Add(label_bold); p.Inlines.Add(new LineBreak()); // cleaner description p.Inlines.Add(new Run(c.description)); p.Inlines.Add(new LineBreak()); p.Inlines.Add(new LineBreak()); p.Inlines.Add(new LineBreak()); // cleaner options foreach (option o in c.option) { label = new Run(); label.Text = o.label + ": "; //label.FontSize = 20; label_bold = new Bold(label); p.Inlines.Add(label_bold); p.Inlines.Add(new Run(o.description)); p.Inlines.Add(new LineBreak()); p.Inlines.Add(new LineBreak()); } doc.Blocks.Add(p); return doc; }