Java Parse Markdown to HTML using CommonMark

Tags: CommonMark Java CommonMark Markdown HTML Convert Parser Parse HtmlRenderer

In this Java tutorial we learn how to convert a markdown string into HTML string using the CommonMark Java library.

How to add CommonMark library to the Java project

To use the CommonMark Java library in the Gradle build project, add the following dependency into the build.gradle file.

implementation 'org.commonmark:commonmark:0.17.2'

To use the CommonMark Java library in the Maven build project, add the following dependency into the pom.xml file.

<dependency>
    <groupId>org.commonmark</groupId>
    <artifactId>commonmark</artifactId>
    <version>0.17.2</version>
</dependency>

To have more information about the CommonMark Java library you can visit the project repository at github.com/commonmark/commonmark-java

How to convert markdown string to HTML string in Java

In the following Java example code we show you how to use the Parser and HtmlRenderer of the CommonMark library to convert a given String in markdown syntax into a String in HTML format.

ParseMarkdownToHTML.java

import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;

public class ParseMarkdownToHTML {
    public static void main(String... args) {
        String markdownValue = "# heading h1\n"
                + "## heading h2\n"
                + "### heading h3\n"
                + "#### heading h4\n"
                + "---";

        String htmlValue = convertMarkdownToHTML(markdownValue);

        System.out.println("Markdown String:");
        System.out.println(markdownValue);
        System.out.println("HTML String:");
        System.out.println(htmlValue);
    }

    public static String convertMarkdownToHTML(String markdown) {
        Parser parser = Parser.builder().build();
        Node document = parser.parse(markdown);
        HtmlRenderer htmlRenderer = HtmlRenderer.builder().build();
        return htmlRenderer.render(document);
    }
}
The output is:
Markdown String:
# heading h1
## heading h2
### heading h3
#### heading h4
---
HTML String:
<h1>heading h1</h1>
<h2>heading h2</h2>
<h3>heading h3</h3>
<h4>heading h4</h4>
<hr />

Happy Coding 😊