富文本转HTML字符串

富文本转HTML字符串

最近工作中遇到需要将富文本内容在浏览器展示 写了个一个基于jsoup的转换工具类

依赖

<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.15.3</version>
</dependency>
public class RichTextToHtmlConverter {

    public static String convert(String title, String richText, String createTime) {
        String result = preProcessImg(richText);
        StringBuilder htmlBuilder = new StringBuilder(result);
        int bodyTagIndex = result.indexOf("<body>");
        if (-1 != bodyTagIndex) {
            String titleStr = "<div style='text-align:center;'><h3 style='margin:auto;'>" + title + "</h3></div>" +
                    "<div style='text-align:center; height:15px;'><span style='float:right; color:gray;'><i>发布时间:</i>" + createTime + "</span></div>";
            htmlBuilder.insert(bodyTagIndex + 6, titleStr);
        }
        return htmlBuilder.toString();
    }

    private static String preProcessImg(String richText) {
        Document document = Jsoup.parse(richText);
        Elements elements = document.getAllElements();
        for (Element element : elements) {
            if ("img".equalsIgnoreCase(element.tagName())) {
                String imgPath = element.attr("src");
                if (!StringUtil.isEmpty(imgPath)) {
                    String base64 = imgToBase64(imgPath);
                    element.attr("src", base64);
                }
            }
        }
        return document.outerHtml().replaceAll("\n", "");
    }

    private static String imgToBase64(String imagePath) {
        BufferedImage image;
        try {
            image = ImgUtil.read(new URL(imagePath));
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        return ImgUtil.toBase64DataUri(image, ImgUtil.IMAGE_TYPE_JPG);
    }

}

如果遇到内容在转JSON串的时候被转义 使用 org.apache.commons.lang 包下的StringEscapeUtils.unescapeJavaScript() 转义一下即可

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值