基本上,我有一个 RichTextBox,我想将其格式化内容转换为 HTML,以便可以将其作为电子邮件发送。
我当前使用的方法根本没有给出任何格式:
string message = new TextRange(messageTextBox.Document.ContentStart,
messageTextBox.Document.ContentEnd).Text;
所以我四处搜索并发现 这个,但是,它已有 5 多年的历史,并且在评论中,MSFT 用户评论说不再支持它 - “此示例已从我们的示例中删除设置并不再受支持”
,并且它生成的 HTML 格式比现代 HTML 或 XHTML 更旧,最好使用现代 HTML 或 XHTML。
谁能告诉我如何将 RichTextBox 的格式化内容转换为 HTML?
(因此,当电子邮件发送时,收件人会看到带格式的电子邮件)
Basically, I have a RichTextBox and I want to convert the formatted contents of it to HTML so it can be sent as an email.
The method I am currently using does not give any formatting at all:
string message = new TextRange(messageTextBox.Document.ContentStart,
messageTextBox.Document.ContentEnd).Text;
So I searched around and found this, however, it is over 5 years old and in the comments an MSFT user has commented saying that it is no longer supported - "This sample has been removed from our sample set and is no longer supported"
, and the HTML it generates is in an older format than modern HTML or XHTML which would be better to have.
Can anybody show me how I can convert the formatted contents of a RichTextBox to HTML?
(So when the email is sent it the recipient sees the email with formatting)
发布评论
评论(3)
一般技术是使用
XamlWriter
将FlowDocument
内容转换为 XML 流,然后使用 XSLT 转换将 XML 转换为 HTML。这并不是一个很好的答案,但那是因为任何给定的 FlowDocument 都有大量可能的 HTML 表示形式。例如,此转换将每个顶级
Section
转换为div
,将每个Paragraph
转换为p
,以及每个Run
到一个span
,其类会告诉您它是斜体、粗体、下划线还是上述的任意组合。它对于我编写它的目的很有用,但将其称为有损转换是一种轻描淡写的说法:这是我编写的用于执行转换的值转换器 - 请注意,为了使用值转换器,您还必须破解并实现将内容公开为依赖属性的
RichTextBox
版本。确实,整个项目很痛苦。The general technique is to use a
XamlWriter
to convert theFlowDocument
content to a stream of XML, and then to use an XSLT transform to convert the XML to HTML. That's not much of an answer, but that's because there's a huge range of possible HTML representations of any given FlowDocument.This transform, for instance, converts every top-level
Section
to adiv
, everyParagraph
to ap
, and everyRun
to aspan
whose class tells you whether or not it's italicized, bold-faced, or underlined, or any combination of the above. It was useful for the purpose I wrote it for, but to call it a lossy transformation is an understatement:Here's a value converter I wrote to do the conversion - note that in order to use the value converter, you also have to hack around and implement a version of
RichTextBox
that exposes the content as a dependency property. Really this whole project was a pain.我认为上面的 XSLT 表的扩展版本可能会有所帮助。不完美但稍微更全面。引用此答案的另一个答案的扩展的扩展。
Extended version of XSLT sheet above I thought might help. Not perfect but slightly more comprehensive. Extension of an extension of another answer referencing this one.
对于那些正在寻找 .Net Core (APS.Net Core) 解决方案的人 - nuget MarkupConverter 为我解决了这个问题。添加依赖引用
然后使用
For those who is looking for solution for .Net Core (APS.Net Core) - nuget MarkupConverter did the trick for me. Add dependency reference
Then use it