【发布时间】:2014-11-15 09:32:40
【问题描述】:
我需要将 HTML 转换为 RTF,我正在使用此代码:
private static String convertToRTF(String htmlStr) {
OutputStream os = new ByteArrayOutputStream();
HTMLEditorKit htmlEditorKit = new HTMLEditorKit();
RTFEditorKit rtfEditorKit = new RTFEditorKit();
String rtfStr = null;
htmlStr = htmlStr.replaceAll("<br.*?>", "#NEW_LINE#");
htmlStr = htmlStr.replaceAll("</p>", "#NEW_LINE#");
htmlStr = htmlStr.replaceAll("<p.*?>", "");
InputStream is = new ByteArrayInputStream(htmlStr.getBytes());
try {
Document doc = htmlEditorKit.createDefaultDocument();
htmlEditorKit.read(is, doc, 0);
rtfEditorKit.write(os, doc, 0, doc.getLength());
rtfStr = os.toString();
rtfStr = rtfStr.replaceAll("#NEW_LINE#", "\\\\par ");
} catch (IOException e) {
e.printStackTrace();
} catch (BadLocationException e) {
e.printStackTrace();
}
return rtfStr;
}
问题是当我尝试转换具有这样的项目符号或数字的 HTML 时:
- 一个
- 两个
这是 HTML:
<html><head>
<style>
<!--
-->
</style>
</head>
<body contenteditable="true">
<p style="text-align: left;">
<ol>
<li><font face="'Segoe UI'">one</font></li>
<li><font face="'Segoe UI'">two</font></li>
</ol>
</p>
这是转换结果:
两个
RTF:
{\rtf1\ansi
{\fonttbl\f0\fnil Monospaced;\f1\fnil 'Segoe UI';}
\par
\f1 one\f1 two\par \par
}
如何转换数字和项目符号?
【问题讨论】:
-
@JimGarrison 是的,我做到了!我在java代码中找不到任何解决方案!
-
1.您的
\pars 已关闭。 2. 您想跟踪正确的数字并将它们作为文本插入,还是想使用 RTF 列表来获得自动数字? (后者称为\listlevel。) -
然后为
ol(重置计数器)和li(插入数字)添加处理。 -
@Jongware 你能写一个答案吗?
-
您是否考虑过使用合适的 HTML 解析器,例如 jsoup?