converting txt to rtf

15,191

Solution 1

Just add text into empty RTF template, plain text doesn't have any formating anyway, so let's say that rtf template looks like this (from wikipedia example):

{\rtf1\ansi{\fonttbl\f0\fswiss Helvetica;}\f0\pard _TEXT_CONTENT_HERE_ }

Update: I forgot about new lines, braces and backslashes :)

public static string PlainTextToRtf(string plainText)
{
  string escapedPlainText = plainText.Replace(@"\", @"\\").Replace("{", @"\{").Replace("}", @"\}");
  string rtf = @"{\rtf1\ansi{\fonttbl\f0\fswiss Helvetica;}\f0\pard ";
  rtf += escapedPlainText.Replace(Environment.NewLine, @" \par ");
  rtf += " }";
  return rtf;
}

Solution 2

Antonio's improved method (note that I defined a code page \ansicpg1250):

public static string PlainTextToRtf(string plainText)
{
    if (string.IsNullOrEmpty(plainText))
        return "";

    string escapedPlainText = plainText.Replace(@"\", @"\\").Replace("{", @"\{").Replace("}", @"\}");
    escapedPlainText = EncodeCharacters(escapedPlainText);

    string rtf = @"{\rtf1\ansi\ansicpg1250\deff0{\fonttbl\f0\fswiss Helvetica;}\f0\pard ";
    rtf += escapedPlainText.Replace(Environment.NewLine, "\\par\r\n ") + ;
    rtf += " }";
    return rtf;
}

.

Encode characters (Polish ones) method:

private static string EncodeCharacters(string text)
{
    if (string.IsNullOrEmpty(text))
        return "";

    return text
        .Replace("ą", @"\'b9")
        .Replace("ć", @"\'e6")
        .Replace("ę", @"\'ea")
        .Replace("ł", @"\'b3")
        .Replace("ń", @"\'f1")
        .Replace("ó", @"\'f3")
        .Replace("ś", @"\'9c")
        .Replace("ź", @"\'9f")
        .Replace("ż", @"\'bf")
        .Replace("Ą", @"\'a5")
        .Replace("Ć", @"\'c6")
        .Replace("Ę", @"\'ca")
        .Replace("Ł", @"\'a3")
        .Replace("Ń", @"\'d1")
        .Replace("Ó", @"\'d3")
        .Replace("Ś", @"\'8c")
        .Replace("Ź", @"\'8f")
        .Replace("Ż", @"\'af");
}
Share:
15,191
marseilles84
Author by

marseilles84

Updated on June 04, 2022

Comments

  • marseilles84
    marseilles84 almost 2 years

    I have a bunch of text files that I want to convert to rtf. Just changing the extension in code doesn't work, the underlying file is the same. I need the text to be in rtf format. Anyone know how I can do this?

    The issue is when I load up a plain text file the RichTextBox isn't formatting the new lines so it loads it as one continuous block of text as opposed to inserting the new lines.

    The only solution has been to open the plain text file and "Save As" an rtf.