Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert RTF to and from plain text

Tags:

javascript

rtf

I have a requirement to convert plain text to and from RTF (RichText Format) using javascript.

I am looking for a function for each conversion, and I am not looking to use a library.

Conversion from plain to RTF

The formatting styles and colours are not important, all that matters is that the plain text i converted into a valid RTF format

Conversion from RTF to plain

Again, the styles are not important. They can be completed removed. All that is required is that all text data remains (no loss of entered data)

like image 912
musefan Avatar asked Apr 28 '15 14:04

musefan


People also ask

How do I convert RTF text to plain text?

On the File tab, choose Options > Mail. Under Compose messages, in the Compose messages in this format list, click HTML, Rich Text, or Plain Text.

How do I convert RTF to word?

Find a desired location to save the file. From within the Save As Window, find the Save File Type field. Select the drop-down arrow, and change the file from Rich Text Format (rtf) to Word Document (doc). Select Save.

How do I change RTF to TXT on Mac?

Change the document format Rich text (. rtf) allows formatting, tables, and images. When you change a rich text document to plain text, the document loses all text styles and formatting options. In the TextEdit app on your Mac, choose Format > Make Plain Text or Format > Make Rich Text.

Are RTF and TXT the same?

Difference Between RTF and TXT The TXT/Text file is a plain text file that does not contain any formatting like italic, bold, and font sizes. RTF has the ability for formatting the text. There are some text editors that may provide the formatting, but it will all be lost once the user saves that TXT file.


1 Answers

I found a c# answer here which was a good starting point, but I needed a Javascript solution.

There is no guarantee that these are 100% reliable, but they seem to work well with the data I have tested on.

function convertToRtf(plain) {
    plain = plain.replace(/\n/g, "\\par\n");
    return "{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang2057{\\fonttbl{\\f0\\fnil\\fcharset0 Microsoft Sans Serif;}}\n\\viewkind4\\uc1\\pard\\f0\\fs17 " + plain + "\\par\n}";
}

function convertToPlain(rtf) {
    rtf = rtf.replace(/\\par[d]?/g, "");
    return rtf.replace(/\{\*?\\[^{}]+}|[{}]|\\\n?[A-Za-z]+\n?(?:-?\d+)?[ ]?/g, "").trim();
}

Here is a working example of them both in action

like image 105
musefan Avatar answered Nov 07 '22 19:11

musefan