word转html并用jsoup解析
背景描述
项目上需要将word格式导入并展示到前端,且后台不使用本地临时文件夹。解析word转html使用aspose组件,解析html使用jsoup。
aspose解析doc文档
1 pom文档
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.12.1</version>
</dependency>
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-words</artifactId>
<version>19.12</version>
<classifier>jdk17</classifier>
</dependency>
2 读取doc文件将文件转为html并保存到内存流中
// 1.获取doc文档转为aspose对象
Document doc = new Document("C:\\Users\\shower\\Desktop\\slf4j技术分享.docx");
// 2.设置doc转html配置
HtmlSaveOptions saveOptions = new HtmlSaveOptions();
saveOptions.setExportTextInputFormFieldAsText(false);
saveOptions.setExportImagesAsBase64(true);
// 3.内存流保存
ByteArrayOutputStream baos = new ByteArrayOutputStream();
doc.save(baos, saveOptions);
3 Jsoup解析html,并替换src
org.jsoup.nodes.Document htmlDoc = Jsoup.parse(baos.toString());
if (htmlDoc !=null){
Elements elements = htmlDoc.getElementsByTag("img");
for (Element element:elements) {
String oldSrc = element.attr("src");
System.out.println(oldSrc);
String newSrc = uploadFile(oldSrc);
element.attr("src",newSrc);
}
System.out.println(htmlDoc.toString());
}