-2

I received RTF format text from API (WPF,C#). I want to convert it to plain text and display in Textview. I tried all the possible ways but didn't the success.

rtf text : 0x7B5C727466315C616E73695C616E7369637067313235325C64656666305C6465666C616E67313033337B5C666F6E7474626C7B5C66305C666E696C5C666368617273657430204D6963726F736F66742053616E732053657269663B7D7D5C766965776B696E64345C7563315C706172645C66305C667331382068656C6C6F5C70617220207D

in API side we are able to convert it to below code. but I want to convert it to android side

ASCIIEncoding ascii = new ASCIIEncoding();
    Archonix.Controls.RichTextBox rtbnote;
                                byte[] note;
                                rtbnote = new Controls.RichTextBox();
                                note = (dr["AlertNote"]) as byte[];
                                rtbnote.Rtf = ascii.GetString(note);
                                string tempRtfText = rtbnote.Rtf;
                                string tempRegularText = rtbnote.Text;
                                objAlertList.AlertNote = tempRegularText;
Nirav Joshi
  • 1,713
  • 15
  • 28

1 Answers1

2

That is not RTF. That is a hex-encoding of bytes.

The bytes are text (and RTF is text), so you must decode the hex string first:

public static void main(String[] args) {
    String hex = "0x7B5C727466315C616E73695C616E7369637067313235325C6465" +
                 "6666305C6465666C616E67313033337B5C666F6E7474626C7B5C66" +
                 "305C666E696C5C666368617273657430204D6963726F736F667420" +
                 "53616E732053657269663B7D7D5C766965776B696E64345C756331" +
                 "5C706172645C66305C667331382068656C6C6F5C70617220207D";
    byte[] bytes = hexStringToByteArray(hex.substring(2));
    String text = new String(bytes, StandardCharsets.US_ASCII);
    System.out.println(text);
}
public static byte[] hexStringToByteArray(String s) {
    int len = s.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                             + Character.digit(s.charAt(i+1), 16));
    }
    return data;
}

Note: hexStringToByteArray taken from Convert a string representation of a hex dump to a byte array using Java?

Output

{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 Microsoft Sans Serif;}}\viewkind4\uc1\pard\f0\fs18 hello\par  }

Now that is RTF.

As for parsing the RTF and extracting text, see Java RTF Parser or do a web search.

Andreas
  • 154,647
  • 11
  • 152
  • 247