Java Swing RTF RTF2TXT(String Str)

Here you can find the source of RTF2TXT(String Str)

Description

RTFTXT

License

Apache License

Declaration

public static final String RTF2TXT(String Str) throws IOException, BadLocationException 

Method Source Code


//package com.java2s;
/* ===========================================================================
 * Copyright (C) 2015 CapsicoHealth Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.//from  w w w  .j  a  v  a 2 s.c om
 */

import java.io.IOException;

import java.io.StringReader;

import java.util.regex.Pattern;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.rtf.RTFEditorKit;

public class Main {
    protected static final Pattern RTF_CELL_PATTERN = Pattern.compile("\\\\cell\\W|\\}\\{\\\\");

    public static final String RTF2TXT(String Str) throws IOException, BadLocationException {
        if (Str != null && Str.startsWith("{\\rtf1") == true) {
            // There is a "questionable" bug in the RTF-to-Text routine in the Java library. With tables, text in
            // adjacent cells are concatenated without any
            // spacing. So, for example, a table with a cell containing "abc" followed by another call containing "123",
            // after conversion, you'll get "abc123".
            // With this hack, we capture the RTF cell delimiter "\cell$" and replace it with ". \cell$". This will
            // separate text in cells from other text and will
            // allow text processing to give better results.
            Str = RTF_CELL_PATTERN.matcher(Str).replaceAll(". $0");
            RTFEditorKit RTF = new RTFEditorKit();
            Document doc = RTF.createDefaultDocument();
            RTF.read(new StringReader(Str), doc, 0);
            Str = doc.getText(0, doc.getLength());
        }
        return Str;
    }
}

Related

  1. rtfToPlain(String rtf)