Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting txt to rtf

Tags:

c#

wpf

rtf

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.

like image 763
marseilles84 Avatar asked May 23 '12 18:05

marseilles84


2 Answers

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;
}
like image 70
Antonio Bakula Avatar answered Sep 30 '22 11:09

Antonio Bakula


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");
}
like image 36
Chris W Avatar answered Sep 30 '22 10:09

Chris W