所需依赖:
<dependency> <groupId>com.atlassian.commonmark</groupId> <artifactId>commonmark</artifactId> <version>0.11.0</version> </dependency>
代码示例:
import org.commonmark.node.Image; 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.Map; public class Md2Html { public static void main(String[] args){ Parser parser = Parser.builder().build(); Node document = parser.parse("```java\n" + " // 根据 id 获取课程 \n" + " @Override\n" + " @GetMapping(\"/coursebase/get/{courseId}\")\n" + " public CourseBase getCourseBaseById(@PathVariable(\"courseId\") String courseId) throws RuntimeException {\n" + " return courseService.getCourseBaseById(courseId);\n" + " }\n" + "```"); HtmlRenderer renderer = HtmlRenderer.builder(). attributeProviderFactory(new AttributeProviderFactory() { @Override public AttributeProvider create(AttributeProviderContext attributeProviderContext) { return new AttributeProvider() { // 自定义标签属性 可用单独类继承 AttributeProvider 接口 @Override public void setAttributes(Node node, String s, Map<String, String> map) { if (node instanceof Image) { map.put("style", "width:150px;height:200px;position:relative;left:50%;margin-left:-100px;"); } if (node instanceof Link) { map.put("target", "_blank"); } } }; } }). build(); /* lamada 改写 * HtmlRenderer renderer = HtmlRenderer.builder(). attributeProviderFactory(attributeProviderContext -> (node, s, map) -> { if (node instanceof Image) { map.put("style", "width:150px;height:200px;position:relative;left:50%;margin-left:-100px;"); } if (node instanceof Link) { map.put("target", "_blank"); } }). build(); * */ String mdHtml = renderer.render(document); mdHtml=mdHtml.replace("<pre>", "<pre class=\"fy-prettyprint linenums\">"); System.out.println(mdHtml); } }
效果:
<pre class="fy-prettyprint linenums"><code class="language-java"> // 根据 id 获取课程 @Override @GetMapping("/coursebase/get/{courseId}") public CourseBase getCourseBaseById(@PathVariable("courseId") String courseId) throws RuntimeException { return courseService.getCourseBaseById(courseId); } </code></pre>