Search code examples
javartfrichtext

Java 8: how to convert plain UTF-8 text into RTF (with symbols > 127)?


I've found many "how to RTF -> plain text" with RTFEditorKit, but no one "plain->rtf". I wouldn't to do it manually, because in my case we have to convert all chars over than 128 to hex strings to get correct RTF file. I would want to do it with some library.

I'm trying to do it with RTFEditorKit:

String orig = "Hello Привет こんにちは";
InputStream is = new ByteArrayInputStream(orig.getBytes(StandardCharsets.UTF_8));
// String tmpStr = is.getText("UTF-8"); // here is correct tmpStr

RTFEditorKit rtfParser = new RTFEditorKit();
javax.swing.text.Document doc = rtfParser.createDefaultDocument();

rtfParser.read(is, doc, 0); 
int docLen = doc.getLength(); // !!! here is docLen = 0

OutputStream os = new ByteArrayOutputStream();
rtfParser.write(os, doc, 0, docLen, );

But cannot read plain text into Document object.


Solution

  • I am not sure I can pinpoint where things are going wrong in your code but this works for me. I insert the string into the Document:

    String orig = "Hello Привет こんにちは";
    
    RTFEditorKit rtfParser = new RTFEditorKit();
    javax.swing.text.Document doc = rtfParser.createDefaultDocument();
    
    doc.insertString(0, orig, null); 
    int docLen = doc.getLength(); 
    
    OutputStream os = Files.newOutputStream(Paths.get("test.rtf"), StandardOpenOption.CREATE);
    
    rtfParser.write(os, doc, 0, docLen);