Skip to content

Instantly share code, notes, and snippets.

@lnicola
Created June 20, 2014 16:09
Show Gist options
  • Save lnicola/fc6ebebcc9606f63bd51 to your computer and use it in GitHub Desktop.
Save lnicola/fc6ebebcc9606f63bd51 to your computer and use it in GitHub Desktop.
some code for parsing RTF files
private static string RtfToHtml(string s)
{
s = Regex.Replace(s, @"^\{\\rtf1?" +
@"\\ansi" +
@"(?:\\ansicpg)?" +
@"(?:\\lang\d+)?" +
@"(?:\\noproof\d+)?" +
@"(?:\\uc\d )?", "");
var header =
@"(?:\\deff(?<default_font>\d+))?" +
@"\{\\fonttbl" +
@"\{(?:" +
@"\\f(?<font_index>\d+)" +
@"(?:\\fnil)?" +
@"(?:\\fcharset\d+)?" +
@"(?:\\fprq\d+)? " +
@"(?<font_face>(\w+\s*)+);)*}}" +
@"{\\colortbl;\s*" +
@"(?:" +
@"\\red(?<red>\d+)" +
@"\\green(?<green>\d+)" +
@"\\blue(?<blue>\d+);)+}" +
@"\s*" +
@"(?:\\f(?<default_font>\d+)\s*)?" +
@"(?:\\fs(?<font_size>\d+)\s*)?" +
@"(?<text>(?:.|\n)*)}$";
var m = Regex.Match(s, header);
s = m.Groups["text"].Value;
var currentFont = m.Groups["default_font"].Value;
var fontSize = m.Groups["font_size"].Value;
var sb = new StringBuilder();
sb.Append("<html><head><style type=\"text/css\">\n");
for (var i = 0; i < m.Groups["font_face"].Captures.Count; i++)
sb.Append(String.Format(".f{0} {{ font-family: {1}; }}\n", m.Groups["font_index"].Captures[i], m.Groups["font_face"].Captures[i]));
sb.Append(".c0 { color: rgb(0, 0, 0); }\n");
for (var i = 0; i < m.Groups["red"].Captures.Count; i++)
sb.Append(String.Format(".c{0} {{ color: rgb({1}, {2}, {3}); }}\n", i + 1, m.Groups["red"].Captures[i], m.Groups["green"].Captures[i], m.Groups["blue"].Captures[i]));
sb.Append(String.Format("</style></head><body><pre><span class=\"f{0}\">", m.Groups["default_font"]));
s = Regex.Replace(s, @"\\tab ", "&nbsp;&nbsp;&nbsp;&nbsp;");
s = Regex.Replace(s, @"\\cf(?<font_index>\d+) ", "</span><span class=\"c${font_index}\">");
s = Regex.Replace(s, "\r\n", "");
s = Regex.Replace(s, @"\\par ", Environment.NewLine);
s = Regex.Replace(s, @"\\{", "{");
s = Regex.Replace(s, @"\\}", "}");
sb.Append(s);
return sb.ToString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment