All formats

RtfPipe

LanguageC# (.NET Standard 2.0, .NET Framework 3.5+)
LicenseMIT
Repositorygithub.com/erdomke/RtfPipe
DocumentationREADME
Depends onSystem.Text.Encoding.CodePages on .NET Core / .NET 5+
Read / writereads 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#

Shell
dotnet add package RtfPipe

Basic usage: convert an RTF file to HTML#

C#
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#

C#
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:

C#
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#

C#
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:

C#
// dotnet add package HtmlAgilityPack
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(Rtf.ToHtml(rtf));
string text = HtmlAgilityPack.HtmlEntity.DeEntitize(doc.DocumentNode.InnerText);

Tips#