Class CmsHtml2MarkdownConverter

java.lang.Object
org.opencms.util.CmsHtml2MarkdownConverter

public class CmsHtml2MarkdownConverter extends Object
Converts an HTML fragment to Markdown.

This converter is intended for HTML pieces (rich text fragments), not complete HTML pages. It parses the input with Jsoup using Jsoup.parseBodyFragment(String) and renders a common set of Markdown constructs: headings, paragraphs, bold and italic, inline code, links, images, ordered and unordered (including nested) lists, blockquotes, fenced code blocks and horizontal rules.

Tags that are not recognized are passed through, so their textual content is preserved. The main use case is to feed CMS content into LLM prompts in a compact, model friendly form.

Note: only a minimal set of Markdown special characters is escaped in text nodes. Perfect round trip escaping (for example of a leading "#", "-" or ">" at the start of a line) is out of scope. GFM tables, task lists and strikethrough are not supported.

Since:
22.0.0
  • Constructor Details

    • CmsHtml2MarkdownConverter

      Creates a new converter that keeps images and links untouched.

    • CmsHtml2MarkdownConverter

      public CmsHtml2MarkdownConverter(boolean ignoreImages, boolean removeLinks)
      Creates a new converter.

      Parameters:
      ignoreImages - if true, images and their related markup are dropped from the output
      removeLinks - if true, links are rendered as their text only, dropping the link markup
  • Method Details

    • html2markdown

      public static String html2markdown(String html)
      Converts the given HTML fragment to Markdown.

      Parameters:
      html - the HTML fragment to convert
      Returns:
      the Markdown representation of the given HTML fragment
    • html2markdown

      public static String html2markdown(String html, boolean ignoreImages, boolean removeLinks)
      Converts the given HTML fragment to Markdown.

      Parameters:
      html - the HTML fragment to convert
      ignoreImages - if true, images and their related markup are dropped from the output
      removeLinks - if true, links are rendered as their text only, dropping the link markup
      Returns:
      the Markdown representation of the given HTML fragment
    • convert

      public String convert(String html)
      Converts the given HTML fragment to Markdown.

      Parameters:
      html - the HTML fragment to convert
      Returns:
      the Markdown representation of the given HTML fragment