【问题标题】:How to convert HTML to RTF in UWP如何在 UWP 中将 HTML 转换为 RTF
【发布时间】:2020-02-05 10:39:54
【问题描述】:

我想在 UWP 中将 HTML 转换为 RichTextBlock。我在stackoverflow中找到了一些答案尝试了以下链接中的代码

link

但是当我尝试在 Richtextblock 控件中绑定 html 属性时,它会给出错误提示“使用 XAMLHtml”的命名空间中不存在名称“属性”

我在 XAMLHtml.cs 文件中包含以下代码以将 HTML 转换为 RTF

class XAMLHtml
{
    public class HtmlProperties : DependencyObject
    {
        public static readonly DependencyProperty HtmlProperty =
            DependencyProperty.RegisterAttached(
                "Html",
                typeof(string),
                typeof(HtmlProperties),
                new PropertyMetadata(null, HtmlChanged));

        private static RichTextBlock _currentObject;

        private static void HtmlChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var richText = d as RichTextBlock;
            if (richText == null) return;

            _currentObject = richText;

            //Generate blocks
            var xhtml = e.NewValue as string;
            var blocks = GenerateBlocksForHtml(xhtml);

            _currentObject = null;

            //Add the blocks to the RichTextBlock
            richText.Blocks.Clear();
            foreach (var b in blocks)
                richText.Blocks.Add(b);
        }

        private static List<Block> GenerateBlocksForHtml(string xhtml)
        {
            var blocks = new List<Block>();

            try
            {
                var doc = new HtmlDocument();
                doc.LoadHtml(xhtml);

                var block = GenerateParagraph(doc.DocumentNode);
                blocks.Add(block);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }

            return blocks;
        }

        // TODO this method seams to be removing necessary spaces in #text nodes
        private static string CleanText(string input)
        {
            var clean = Windows.Data.Html.HtmlUtilities.ConvertToText(input);
            //clean = System.Net.WebUtility.HtmlEncode(clean);
            if (clean == "\0")
                clean = "\n";
            return clean;
        }

        private static Block GenerateBlockForTopNode(HtmlNode node)
            => GenerateParagraph(node);


        private static void AddChildren(Paragraph p, HtmlNode node)
        {
            var added = false;
            foreach (var child in node.ChildNodes)
            {
                var i = GenerateBlockForNode(child);
                if (i != null)
                {
                    p.Inlines.Add(i);
                    added = true;
                }
            }
            if (!added)
            {
                p.Inlines.Add(new Run { Text = CleanText(node.InnerText) });
            }
        }

        private static void AddChildren(Span s, HtmlNode node)
        {
            var added = false;

            foreach (var child in node.ChildNodes)
            {
                var i = GenerateBlockForNode(child);
                if (i != null)
                {
                    s.Inlines.Add(i);
                    added = true;
                }
            }
            if (!added)
            {
                s.Inlines.Add(new Run { Text = CleanText(node.InnerText) });
            }
        }

        private static Inline GenerateBlockForNode(HtmlNode node)
        {
            switch (node.Name)
            {


                case "b":
                case "B":
                case "strong":
                case "STRONG":
                    return GenerateBold(node);
                case "i":
                case "I":
                case "em":
                case "EM":
                    return GenerateItalic(node);
                case "u":
                case "U":
                    return GenerateUnderline(node);
                case "br":
                case "BR":
                    return new LineBreak();                                          
                default:
                    return GenerateSpanWNewLine(node);
            }

        }

        private static Inline GenerateBold(HtmlNode node)
        {
            var bold = new Bold();
            AddChildren(bold, node);
            return bold;
        }

        private static Inline GenerateUnderline(HtmlNode node)
        {
            var underline = new Underline();
            AddChildren(underline, node);
            return underline;
        }

        private static Inline GenerateItalic(HtmlNode node)
        {
            var italic = new Italic();
            AddChildren(italic, node);
            return italic;
        }

        private static Block GenerateParagraph(HtmlNode node)
        {
            var paragraph = new Paragraph();
            AddChildren(paragraph, node);
            return paragraph;
        }


        private static Inline GenerateSpanWNewLine(HtmlNode node)
        {
            var span = new Span();
            AddChildren(span, node);
            if (span.Inlines.Count > 0)
                span.Inlines.Add(new LineBreak());
            return span;
        }

    }
}

这是我在 xaml 文件中写的内容

<Page
x:Class="SampleHtml.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
xmlns:converter="using XAMLHtml" 
xmlns:html="using HTMLPage1"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"   
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <RichTextBlock converter:Properties.Html="{Binding HTMLPage1}" Grid.Row="0"/>
</Grid>

这是html文件中的代码

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <p><b>This text is bold</b></p>
    <p><i>This text is italic</i></p>
    <p>This is<sub> subscript</sub> and <sup>superscript</sup></p>
    
</body>
</html>

如果有人可以帮助我,我将不胜感激。谢谢

【问题讨论】:

  • 请分享您编写的代码。
  • 我编辑了帖子并添加了代码

标签: html uwp html-agility-pack richtextblock


【解决方案1】:

这个项目是 UWP 平台的类库。请下载完整的项目并参考它。

我检查了类名是HtmlProperties而不是Properties的代码,所以你需要像下面这样编辑你的xaml代码

<RichTextBlock converter:HtmlProperties.Html="{x:Bind HtmlString}" />

一般我们可以使用WebViewBrush 来获取webview 内容,然后将其设置为Rectangle 控件。更多信息请参考document

【讨论】:

  • 我将其更改为 HtmlProperties 并尝试了两种方法,但仍然出现错误。这是我的文件结构的屏幕截图imgur.com/vBNLxKX
  • 我下载了您的代码并安装了 Html2Xaml 包。但它仍然显示此错误。我需要更改什么吗?
  • 当我没有安装 html2xaml 包时,它给出了 Richtextblock 的错误,说属性“儿童”没有可访问的设置器。还有上面的错误,即名称“属性”不存在在命名空间“using:HtmlToRtf.WinRT_RichTextBlock.Html2Xaml”中仍然存在。
  • html2xaml 包似乎不支持
        html 元素..有没有办法让它工作?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-15
    • 2012-02-17
    • 1970-01-01
    • 2017-12-02
    • 2010-10-01
    • 1970-01-01
    相关资源
    最近更新 更多