spring

Spring Boot – Convert Markdown to HTML

Converting Markdown to HTML is a process in web development and content management. Markdown, a lightweight markup language, simplifies text formatting, making it popular for writing online documents. Converting Markdown to HTML involves translating Markdown syntax into HTML code, enabling seamless integration of rich text features like headings, lists, and links into web pages. This conversion process ensures compatibility across various platforms and browsers, allowing content creators to focus on creating content without worrying about complex HTML tags. Let us delve into a practical approach to convert Markdown to HTML in Spring boot.

1. Introduction

Markdown is a lightweight markup language that allows users to write plain text documents using a simple and easy-to-read syntax. Created by John Gruber and Aaron Swartz, Markdown is widely used for formatting text on the web, in documentation, and in various other contexts. Here are some benefits of markdown –

  • Simplicity: Markdown’s syntax is intuitive and easy to learn, making it accessible to both beginners and experienced users.
  • Readability: Markdown documents are plain text files, ensuring readability even without specialized software. This simplicity makes collaboration and version control easier.
  • Portability: Markdown files can be opened and edited using any text editor. They can also be converted to HTML, PDF, or other formats, allowing seamless integration into various platforms.
  • Speed: Writing in Markdown is faster than using traditional word processing software because it eliminates the need for mouse interaction and complex formatting menus.
  • Focus on Content: Markdown allows writers to focus on the content rather than formatting, enhancing productivity and creativity.
  • Version Control: Markdown files work well with version control systems like Git, allowing for efficient tracking of changes and collaboration among multiple contributors.
  • Wide Adoption: Markdown is supported by numerous platforms, content management systems, and online services, ensuring its relevance and usability across different applications.

1.1 Syntax

Here is a simple snippet of markdown –

pom.xml

# Heading 1
## Heading 2
### Heading 3

*italic*
**bold**

- Unordered list item 1
- Unordered list item 2

1. Ordered list item 1
2. Ordered list item 2

[Link text](URL)

![Alt text](URL)

> This is a blockquote.

`inline code`

\```
Multi-line code block
\```

2. Spring Boot – Convert Markdown to HTML

Let us dive into some practice stuff. If anyone is interested in looking at the project structure refer to the below image.

Spring Boot Convert Markdown to HTML
Fig. 1: Project structure

2.1 Updating the Maven dependencies in pom.xml file

Set up a new Spring Boot project or use an existing one. Include the necessary dependencies in your project’s pom.xml file. We are using the Commonmark library that provides a specification for a consistent markdown syntax, designed to provide unambiguous rules for Markdown formatting.

pom.xml

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
	<groupId>org.commonmark</groupId>
	<artifactId>commonmark</artifactId>
	<version>0.21.0</version>
</dependency>

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-test</artifactId>
	<scope>test</scope>
</dependency>
</dependencies>

2.2 Create a Service Class

The class, Htmlservice, is designed to convert Markdown text to HTML format. It is annotated with @Service, making it a Spring service component that can be easily managed and utilized within the application context.

The class contains a single method called markdownToHtml, which takes a Markdown string as input and returns the corresponding HTML representation. Here’s how the method works –

  • Inside the markdownToHtml method, a Parser object is created using Parser.builder().build(). This object is responsible for parsing the input Markdown string into a structured format represented by a Node object. The Parser processes the Markdown syntax, creating a tree-like structure that represents the document’s elements.
  • After parsing the Markdown content into a Node object, an HtmlRenderer object is instantiated using HtmlRenderer.builder().build(). The HtmlRenderer is responsible for rendering the parsed Node back into an HTML string. The render method of the HtmlRenderer processes the structured Node and generates the corresponding HTML markup.
  • The HTML representation of the input Markdown is returned as a string from the markdownToHtml method. This output can then be used in web applications, etc. where Markdown content needs to be displayed as HTML.

Htmlservice.java

package com.example.markdown.service;

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

@Service
public class Htmlservice {

    public String markdownToHtml(String markdown) {
        Parser parser = Parser.builder().build();
        Node document = parser.parse(markdown);
        return HtmlRenderer.builder().build().render(document);
    }
}

2.3 Create a Controller Class

The Markdowncontroller class serves as a Spring MVC controller responsible for handling HTTP requests related to Markdown conversion in a web application. Annotated with @Controller, it indicates that this class handles web requests.

The class has two instance variables: markdown to store the input Markdown content and html to store the converted HTML output.

The index method, annotated with @GetMapping("/"), handles the initial GET request to the root URL (“/”). It populates the model with the markdown and html attributes, which are then accessed in the corresponding HTML template. The method returns the view name “index”, which is used to render the HTML content.

The post method, annotated with @PostMapping("/"), handles the POST requests to the root URL (“/”). It receives a parameter named input representing the user’s input Markdown content. The method updates the markdown variable with the input value and calls the markdownToHtml method from the injected Htmlservice to convert the Markdown to HTML, storing the result in the `html` variable. Then, it redirects the user back to the root URL (“/”) to display the updated Markdown and HTML content.

Markdowncontroller.java

package com.example.markdown.controller;

import com.example.markdown.service.Htmlservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class Markdowncontroller {

    private String markdown = "";
    private String html = "";

    private final Htmlservice htmlservice;

    @Autowired
    public Markdowncontroller(Htmlservice service) {
        this.htmlservice = service;
    }

    @GetMapping("/")
    public String index(Model model) {
        model.addAttribute("markdown", markdown);
        model.addAttribute("html", html);

        return "index";
    }

    @PostMapping("/")
    public String post(@RequestParam String input) {
        markdown = input;
        html = htmlservice.markdownToHtml(markdown);

        return "redirect:/";
    }
}

2.4 Create Main Class

In this main class, the @SpringBootApplication annotation is used to indicate that this is the main entry point for a Spring Boot application. It enables auto-configuration and component scanning.

The main() method starts the Spring Boot application by calling SpringApplication.run() and passing the main class SpringwebclientdemoApplication.class along with any command-line arguments args.

MarkdownApplication.java

package com.example.markdown;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MarkdownApplication {

    public static void main(String[] args) {
        SpringApplication.run(MarkdownApplication.class, args);
    }
}

2.5 Create an HTML page

Create a thymeleaf template in the src/main/resources/templates folder. The template serves as a welcome page for the user to input the markdown, view the converted HTML, and visualize the HTML output.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Convert markdown to html</title>
</head>
<body>
<h2>Convert markdown to html</h2>
<small>Feel free to add CSS styling!</small>
<form action="/" method="post">
    <div>
        <label for="input">Input markdown</label>
        <textarea id="input" name="input" rows="6"></textarea>
    </div>
    <button type="submit">Convert</button>
</form>
<div>
    <div>
        <label for="markdown">From markdown</label>
        <textarea disabled id="markdown" rows="6" th:text="${markdown}"></textarea>
    </div>
    <div>
        <label for="html">To html</label>
        <textarea disabled id="html" rows="6" th:text="${html}"></textarea>
    </div>
</div>
<div>
    <label>Output html</label>
    <div th:utext="${html}"></div>
</div>
</body>
</html>

3. Output

Start the Spring boot application by running the MarkdownApplication.java class from the IDE and navigate to the browser of your choice. Hit the below url and it will open the index page of the application.

Welcome endpoint

http://localhost:9030/
Spring Boot Convert Markdown to HTML
Fig. 2: Welcome page

Input the same markdown and click on the Convert button. The markdown will be completed into the HTML and visualize the same HTML output at the same time. In addition, there is an embeddable javascript markdown editor that can help you generate markdown content on the fly. You’re free to experiment with but make sure using external libraries sometimes exposes the data to the client.

Note – The application will operate on port 9030. Feel free to modify the port number by adjusting the server.port property in the application.properties file.

application.properties

server.port=8500

4. Conclusion

In conclusion, the integration of Markdown conversion in a web application through the controller and service classes shows the seamless interplay between Java and Spring. By using the Markdown simplicity and Spring framework developers can create dynamic applications that enable users to input Markdown content, easily convert it into HTML, and visualize the results in real-time.

5. Download the Project

This was a tutorial to understand the Markdown to HTML conversion with the help of a Spring boot application.

Download
You can download the full source code of this example here: Spring Boot – Convert Markdown to HTML

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button