转换Html(富文本编辑器)到docx的Java工具类

背景

  本文是基于Java语言,引入POI从而提供将富文本编辑器内的html内容转换为docx的方式。

效果

  图像备份: 访问

html2docx.jpg

代码

  引入pom坐标

    <dependency>
        <groupId>cn.net.pap</groupId>
        <artifactId>pap4j-common-docx</artifactId>
        <version>0.0.1</version>
    </dependency>

  测试方法

    @Test
    public void html2DocxTest() {
        // 这里是从富文本编辑器里面获得的一个 html。
        String editorHTML = "<p><font color=\"#067d17\">pap.net.cn&nbsp; &nbsp;内容1&nbsp; &nbsp;</font><span style=\"color: rgb(6, 125, 23);\">pap.net.cn</span><span style=\"color: rgb(6, 125, 23);\">&nbsp;</span></p><p><font color=\"#067d17\">内容2&nbsp;</font><img src=\"https://foruda.gitee.com/avatar/1676898910937495644/73661_alexgaoyh_1578916342.png!avatar200\" style=\"width: 200px;\"><font color=\"#067d17\"> 内容3</font></p><p><span style=\"color: rgb(6, 125, 23);\">pap.net.cn</span><span style=\"color: rgb(6, 125, 23);\">&nbsp; &nbsp;</span><font color=\"#067d17\">内容4&nbsp; &nbsp;</font><span style=\"color: rgb(6, 125, 23);\">pap.net.cn</span><span style=\"color: rgb(6, 125, 23);\">&nbsp;</span></p>";
        boolean b = Html2DocxUtils.html2docx2UsingPOI(new StringBuffer(editorHTML), "OUT.docx");
        assertTrue(b);
    }

对比

  在实际开发过程中,最开始计划使用 documents4j 进行转换,但是此方法依赖 Microsoft office,客户环境有可能千奇百怪,故在实际线上环境部署过程中,不再使用此方法,而改为使用poi进行转换处理。

    IConverter converter = LocalConverter.builder().build();
    converter.convert(htmlInputStream).as(DocumentType.HTML).to(outputStream).as(DocumentType.DOCX).execute();
    converter.shutDown();

总结

  本方法依赖 poi 4.1.2版本,支持HTML中存在三方的图像URL。

参考

  1. http://pap-docs.pap.net.cn/
  2. https://gitee.com/alexgaoyh/pap4j-boot3/
  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值