반응형
commonmark 라이브러리 사용
pom.xml
<dependency>
<groupId>com.atlassian.commonmark</groupId>
<artifactId>commonmark</artifactId>
<version>0.16.1</version>
</dependency>
Basic
public class MarkdownToHtml {
public static void main(String[] args) {
Parser parser = Parser.builder().build();
Node document = parser.parse("This is *Sparta*");
HtmlRenderer renderer = HtmlRenderer.builder().build();
String html = renderer.render(document);
System.out.println(html); // <p>This is <em>Sparta</em></p>
}
}
Customize HTML rendering
public class MarkdownToHtml {
public static void main(String[] args) {
HtmlRenderer renderer = HtmlRenderer
.builder()
.nodeRendererFactory(context -> new NodeRenderer() {
@Override
public Set<Class<? extends Node>> getNodeTypes() {
return Set.of(Heading.class, FencedCodeBlock.class);
}
@Override
public void render(Node node) {
HtmlWriter writer = context.getWriter();
if (node instanceof Heading) {
// writer.line(); // newline
writer.tag("h3");
writer.text(((Text) node.getFirstChild()).getLiteral());
writer.tag("/h3");
}
if (node instanceof FencedCodeBlock) {
FencedCodeBlock codeBlock = (FencedCodeBlock) node;
writer.tag("pre", Map.of("class", codeBlock.getInfo()));
writer.tag("code");
writer.text(codeBlock.getLiteral());
writer.tag("/code");
writer.tag("/pre");
}
}
})
.build();
Parser parser = Parser.builder().build();
Node document = parser.parse("### Hello\n```groovy\nprintln('Hello World')\n```");
String html = renderer.render(document);
System.out.println(html); // <h3>Hello</h3><pre class="groovy"><code>println('Hello World')
}
}
참고
반응형
'Development > Java' 카테고리의 다른 글
[Java] Apache HttpClient (0) | 2020.12.28 |
---|---|
[Java] JWT(Json Web Token) (0) | 2020.12.28 |
[Java] VisualVM 사용하기 (0) | 2019.09.30 |
[Java] JDK 버전별 신규 기능 (0) | 2019.04.21 |
[Java] XML 파싱 (0) | 2019.03.20 |