如何将 RTF 字符串转换为 Markdown 字符串(以及转换回来)(C# .NET Core 或 JS)

2024-01-10

问题:

如何在 C# 或 JS 中将 RTF 字符串转换为 Markdown 字符串(以及转换回来),最好不要包装 exe?


我有一个使用 .NET 的旧产品RichTextBox控制。使用它的表单将其输出保存在 Microsoft 专有的格式中RTF格式 https://en.wikipedia.org/wiki/Rich_Text_Format。这里有一个小example of the output它可以生成:

{\\rtf1\\ansi\\ansicpg1252\\uc1\\htmautsp\\deff2{\\fonttbl{\\f0\\fcharset0 Times New Roman;}{\\f2\\fcharset0 GenericSansSerif;}}{\\colortbl\\red0\\green0\\blue0;\\red255\\green255\\blue255;}\\loch\\hich\\dbch\\pard\\plain\\ltrpar\\itap0{\\lang1033\\fs18\\f2\\cf0 \\cf0\\ql{\\f2 {\\ltrch Some content here }\\li0\\ri0\\sa0\\sb0\\fi0\\ql\\par}\r\n}\r\n}

我的 C# .NET Core Web 应用程序需要能够使用此存储的 RTF 在网页上显示“富文本编辑器”,能够更新值,并以仍可以由旧版使用的格式保存产品。

不幸的是,我无法找到可以使用 RTF 作为输入的现有/现代 Web 组件。大多数似乎使用 Markdown 或自定义 JSON 格式。

理想情况下,我想:

  1. Convert the existing RTF to Markdown using either:
    • 服务器端,使用C#
    • 客户端,使用JS
  2. 将 Markdown 与我找到的现有富文本编辑 Web 组件之一结合使用。
  3. 保存时,在保留之前将 Web 组件的 Markdown 转换为 RTF

到目前为止,我已经尝试过:

  • Following this CodeProject write-up for creating a custom RTF -> HTML converter: Writing Your Own RTF Converter https://www.codeproject.com/Articles/27431/Writing-Your-Own-RTF-Converter
    • 我可以让它在 .NET Framework 项目中工作,但不能在 .NET Core 项目中工作
  • Using this NuGet Package: RtfPipe https://github.com/erdomke/RtfPipe
    • 在 .NET Core 项目中引发空引用错误
  • Using this Node Module: rtf-to-html https://github.com/iarna/rtf-to-html
    • 仅支持 RTF 的一小部分,创建整个 HTML 文档而不是字符串/子集,打破我的具体示例

Note:我尝试过的东西来自 RTF -> Html,因为我找不到专门针对 RTF -> Markdown 的任何内容。我希望,如果必须的话,我可以这样做:RTF -> HTML -> Markdown(反之亦然)作为最后的手段。


对于您遇到的空引用错误,我们深表歉意RtfPipe https://github.com/erdomke/RtfPipe和.Net Core。这些错误的解决方案现已记录在项目中,并涉及包含 NuGet 包System.Text.Encoding.CodePages并注册代码页提供程序。

#if NETCORE
  // Add a reference to the NuGet package System.Text.Encoding.CodePages for .Net core only
  Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
#endif
var html = Rtf.ToHtml(rtf);

由于 HTML 从技术上讲是 Markdown,因此您可以到此为止。否则,您也可以使用我的将 HTML 转换为 Markdown支架管 https://github.com/erdomke/BracketPipe图书馆。代码看起来像这样。

using BracketPipe;
using RtfPipe;

private string RtfToMarkdown(string source)
{
  using (var w = new System.IO.StringWriter())
  using (var md = new MarkdownWriter(w))
  {
    Rtf.ToHtml(source, md);
    md.Flush();
    return w.ToString();
  }
}

Markdig https://github.com/lunet-io/markdig是一个很好的从 Markdown 到 HTML 的库。但是,对于从 HTML 到 RTF 的转换,我没有任何好的建议。

免责声明:我是该书的作者RtfPipe https://github.com/erdomke/RtfPipe and 支架管 https://github.com/erdomke/BracketPipe开源项目

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将 RTF 字符串转换为 Markdown 字符串(以及转换回来)(C# .NET Core 或 JS) 的相关文章

随机推荐