什么是 rtf 格式? rtf 是一种富文本格式 Rich Text Format,可以包含文字 图片 等内容。rtf 可以用 word 或者 wps 直接打开,也可以用文本编辑器打开,如果用文本编辑器打开则可以显示其源码。rtf 源码格式解析可以参考这里。
用 Java 代码解析 rtf 格式,可以用 Apache Tika 解析,且支持 rtf 格式,但是网上可参考的文档较少。但是网上 doc 转成 html 的参考文档较多,因此可采用如下步骤:
- 将 rtf 转成 doc 格式
- 将 doc 格式转换成 html
步骤 1 较为简单,可以先用 word 或者 wps 打开 rtf 文件,然后 文件 另存为 doc 即可。如果一个文件可以这样操作,如果有多上百个文件这样操作肯定较为繁琐,可以查看这篇文章,批量将 rtf 另存为 doc 格式。
步骤 2 可以参考网上的这篇文章, 通过 Apache POI 将 doc 转成 html 格式,且样式图片不会丢失。
对于步骤 2 中网上那篇文章将 doc 转 html 时,提取了其中的图片,然后 html 引入了图片的相对位置。其实还有一种办法,是将图片转成 base64 编码,直接内嵌在 html 网页中。代码如下:
首先导入依赖,这里采用的是 poi 3.17 版本,其他版本也可以。
<dependencies> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.17</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.17</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-scratchpad</artifactId> <version>3.17</version> </dependency> </dependencies>