MarkDown转换成HTML工具类

MarkDownToHTML

依赖

<dependency>
	<groupId>com.atlassian.commonmark</groupId>
	<artifactId>commonmark</artifactId>
	<version>0.10.0</version>
</dependency>

<dependency>
	<groupId>com.atlassian.commonmark</groupId>
	<artifactId>commonmark-ext-heading-anchor</artifactId>
	<version>0.10.0</version>
</dependency>

<dependency>
	<groupId>com.atlassian.commonmark</groupId>
	<artifactId>commonmark-ext-gfm-tables</artifactId>
	<version>0.10.0</version>
</dependency>

转换代码

/**
 * MarkDown转HTML工具类
 * @author xiaobai
 * @date 2020/8/9 17:26
 */
public class MarkdownUtils {
     

    /**
     * markdown格式转换成HTML格式
     * @param markdown
     * @return
     */
    public static String markdownToHtml(String markdown) {
     
        Parser parser = Parser.builder().build();
        Node document = parser.parse(markdown);
        HtmlRenderer renderer = HtmlRenderer.builder().build();
        return renderer.render(document);
    }

    /**
     * 增加扩展[标题锚点,表格生成]
     * Markdown转换成HTML
     * @param markdown
     * @return
     */
    public static String markdownToHtmlExtensions(String markdown) {
     
        //h标题生成id
        Set<Extension> headingAnchorExtensions = Collections.singleton(HeadingAnchorExtension.create());
        //转换table的HTML
        List<Extension> tableExtension = Arrays.asList(TablesExtension.create());
        Parser parser = Parser.builder()
                .extensions(tableExtension)
                .build();
        Node document = parser.parse(markdown);
        HtmlRenderer renderer = HtmlRenderer.builder()
                .extensions(headingAnchorExtensions)
                .extensions(tableExtension)
                .attributeProviderFactory(new AttributeProviderFactory() {
     
                    public AttributeProvider create(AttributeProviderContext context) {
     
                        return new CustomAttributeProvider();
                    }
                })
                .build();
        return renderer.render(document);
    }

    /**
     * 处理标签的属性
     */
    static class CustomAttributeProvider implements AttributeProvider {
     
        @Override
        public void setAttributes(Node node, String tagName, Map<String, String> attributes) {
     
            //改变a标签的target属性为_blank
            if (node instanceof Link) {
     
                attributes.put("target", "_blank");
            }
            if (node instanceof TableBlock) {
     
                attributes.put("class", "ui celled table");
            }
        }
    }
}

你可能感兴趣的:(Java工具类,java)