我需要一个用于HTML2RTF的简单转换器,
我尝试运行以下代码....但是此代码示例出现错误
码:
import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.text.Document;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.rtf.RTFEditorKit;
public class converter {
private static Pattern htmlTrimPattern = Pattern.compile(".*<body>(.*)</body>.*", Pattern.DOTALL);
public static void main(String[] args)
{
toRtf("<!DOCTYPE html>\n" +
"<html>\n" +
"<body>\n" +
"\n" +
"<h1>My First Heading</h1>\n" +
"\n" +
"<p>My first paragraph.</p>\n" +
"\n" +
"</body>\n" +
"</html>\n");
}
public static String toRtf(String html) {
ByteArrayInputStream input= new ByteArrayInputStream(html.getBytes());
StringWriter writer = new StringWriter();
try {
RTFEditorKit rtfEditorKit = new RTFEditorKit();
HTMLEditorKit htmlEditorKit = new HTMLEditorKit();
Document htmlDoc = htmlEditorKit.createDefaultDocument();
htmlEditorKit.read(input, htmlDoc, 0);
rtfEditorKit.write(writer, htmlDoc, 0, htmlDoc.getLength());
} catch (Exception ex) {
System.out.println("Error"+ex);
}
System.out.println(writer.toString());
return writer.toString();
}
}
错误:
Errorjava.io.IOException: RTF is an 8-bit format
我究竟做错了什么?谷歌在这种情况下不是我的朋友,我希望你能帮助我:)
最佳答案
RTF是8位格式,但是您正在将内容发送到Writer
,这是“用于写入字符流的类”。尝试采用write()
的ByteArrayOutputStream
变体:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
…
rtfEditorKit.write(baos, htmlDoc, 0, htmlDoc.getLength());
…
System.out.println(baos.toString());
安慰:
{\ rtf1 \ ansi
{\ fonttbl \ f0 \ fnil等距;}
\ par
我的第一个标题我的第一段。
}