作者:姑另静乖_606 | 来源:互联网 | 2023-08-07 10:48
这里我们通过commonmark-java实现。geihub地址:https:github.comcommonmarkcommonmark-java对应依赖:
这里我们通过commonmark-java实现。
geihub地址:https://github.com/commonmark/commonmark-java
对应依赖:
com.atlassian.commonmarkcommonmark0.15.2com.atlassian.commonmarkcommonmark-ext-heading-anchor0.15.2com.atlassian.commonmarkcommonmark-ext-gfm-tables0.15.2
对应工具类:
import org.commonmark.Extension;
import org.commonmark.ext.gfm.tables.TableBlock;
import org.commonmark.ext.gfm.tables.TablesExtension;
import org.commonmark.ext.heading.anchor.HeadingAnchorExtension;
import org.commonmark.node.Link;
import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.AttributeProvider;
import org.commonmark.renderer.html.AttributeProviderContext;
import org.commonmark.renderer.html.AttributeProviderFactory;
import org.commonmark.renderer.html.HtmlRenderer;import java.util.*;public class MarkdownUtil {/*** 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标题生成idSet headingAnchorExtensions = Collections.singleton(HeadingAnchorExtension.create());//转换table的HTMLList 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() {@Overridepublic AttributeProvider create(AttributeProviderContext context) {return new CustomAttributeProvider();}}).build();return renderer.render(document);}/*** 处理标签的属性*/static class CustomAttributeProvider implements AttributeProvider {@Overridepublic void setAttributes(Node node, String tagName, Map attributes) {//改变a标签的target属性为_blankif (node instanceof Link) {attributes.put("target", "_blank");}if (node instanceof TableBlock) {attributes.put("class", "ui celled table");}}}}