RtfPipe
| Language | C# (.NET Standard 2.0, .NET Framework 3.5+) |
|---|---|
| License | MIT |
| Repository | github.com/erdomke/RtfPipe |
| Documentation | README |
| Depends on | System.Text.Encoding.CodePages on .NET Core / .NET 5+ |
| Read / write | reads RTF and writes HTML; doesn't write RTF |
RtfPipe parses RTF and renders HTML. It aims to support the core of the RTF 1.9.1 spec: character formatting (bold, italic, colors, fonts, sizes), paragraphs and headings, numbered and bulleted lists, nested tables, hyperlinks, pictures, and HTML encapsulated in RTF by Outlook (which it restores). Complex documents won’t look exactly like they do in Word, but text, structure and common formatting come through.
The last release (2.0) is from 2021 and the repository is quiet, but the library is complete for its purpose and widely used for showing RTF content (e.g. from databases or email) in web pages.
Installation#
dotnet add package RtfPipe
Basic usage: convert an RTF file to HTML#
using System;
using System.IO;
using System.Text;
using RtfPipe;
// legacy code pages (\ansicpg1252 etc.) need this on .NET Core and .NET 5+
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
string rtf = File.ReadAllText("letter.rtf");
string html = Rtf.ToHtml(rtf); // an HTML fragment (<div>...)
File.WriteAllText("letter.html", html);
Console.WriteLine(html.Length);
Rtf.ToHtml accepts a string, a TextReader or a Stream (via implicit conversions to RtfSource).
How to produce a complete HTML document#
var settings = new RtfHtmlSettings().WithFullDocument(); // adds <html>, <head>, <body>
string html = Rtf.ToHtml(rtf, settings);
How to embed pictures as data URIs or save them#
By default pictures become data: URIs. Supply ImageUriGetter to save them as files instead:
int n = 0;
var settings = new RtfHtmlSettings
{
ImageUriGetter = picture =>
{
string ext = picture.MimeType() == "image/png" ? "png" : "jpg";
string name = $"image{++n}.{ext}";
File.WriteAllBytes(Path.Combine("out", name), picture.Bytes);
return name; // used as the src attribute
}
};
string html = Rtf.ToHtml(rtf, settings);
How to write HTML to a stream#
using var input = File.OpenRead("big.rtf");
using var output = new StreamWriter("big.html");
Rtf.ToHtml(input, output);
How to extract plain text#
RtfPipe has no text renderer; convert to HTML and take the text with an HTML parser:
// dotnet add package HtmlAgilityPack
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(Rtf.ToHtml(rtf));
string text = HtmlAgilityPack.HtmlEntity.DeEntitize(doc.DocumentNode.InnerText);
Tips#
- Without the code pages provider, RTF that uses
\'hhescapes in a Windows code page fails or produces wrong characters. - To convert RTF to Markdown, pass RtfPipe’s HTML to a converter such as ReverseMarkdown, or use the author’s BracketPipe library.
- Outlook’s “rich text” message bodies are often compressed RTF; decompress them first (MS-OXRTFCP), then pass the result to RtfPipe.