word转html并用jsoup解析

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());
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值