使用Java对Markdown与Html内容进行互转

白色玫瑰 程序猿

时间: 2023-07-11 阅读: 1 字数:6595

{}
使用Java对Markdown与Html内容进行互转一、Markdown转Html1.pom.xml引入2.测试类MarkdownToHtmlUtils.java二、Html转Markdown1.maven的pom.xml引入如下2.测试类HtmlToMarkdownUtils.java 一、Markdown转Html 1.pom....

目录

使用Java对Markdown与Html内容进行互转

<a href="#MarkdownHtml_3">一、Markdown转Html</a>

<a href="#1pomxml_5">1.pom.xml引入</a>    <a href="#2MarkdownToHtmlUtilsjava_29">2.测试类MarkdownToHtmlUtils.java</a>      <a href="#HtmlMarkdown_117">二、Html转Markdown</a>   

<a href="#1mavenpomxml_119">1.maven的pom.xml引入如下</a>    <a href="#2HtmlToMarkdownUtilsjava_127">2.测试类HtmlToMarkdownUtils.java</a>      

<hr color="#000000" size="1"">

一、Markdown转Html

1.pom.xml引入

   <!--引入Markdown转HTML的插件-->
   <dependency>
     <groupId>com.atlassian.commonmark</groupId>
     <artifactId>commonmark</artifactId>
     <version>0.17.0</version>
   </dependency>
    
   <!--扩展 标题-->
   <dependency>
     <groupId>com.atlassian.commonmark</groupId>
     <artifactId>commonmark-ext-heading-anchor</artifactId>
     <version>0.17.0</version>
   </dependency>
    
   <!--扩展 表格-->
   <dependency>
     <groupId>com.atlassian.commonmark</groupId>
     <artifactId>commonmark-ext-gfm-tables</artifactId>
     <version>0.17.0</version>
   </dependency>

2.测试类MarkdownToHtmlUtils.java

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.commonmark.Extension;
import org.commonmark.ext.gfm.tables.TableBlock;
import org.commonmark.ext.gfm.tables.TablesExtension;
import org.commonmark.ext.heading.anchor.HeadingAnchorExtension;
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;
 
/**
 */
public class MarkdownToHtmlUtils {
 
   /**
    * markdown格式转换成HTML格式
    * @param markdown
    * @return
    */
   public static String markdownToHtml(String markdown) {
      Parser parser = Parser.builder().build();
      Node document = parser.parse(markdown);
      HtmlRenderer renderer = HtmlRenderer.builder().build();
      return renderer.render(document);
   }
 
   /**
    * 增加扩展[标题锚点,表格生成]
    * Markdown转换成HTML
    * @param markdown
    * @return
    */
   public static String markdownToHtmlExtensions(String markdown) {
      //h标题生成id
      Set<Extension> headingAnchorExtensions = Collections.singleton(HeadingAnchorExtension.create());
      //转换table的HTML
//      List<Extension> tableExtension = Arrays.asList(TablesExtension.create());
      List<Extension> tableExtension = Collections.singletonList(TablesExtension.create());
      Parser parser = Parser.builder()
            .extensions(tableExtension)
            .build();
      Node document = parser.parse(markdown);
      HtmlRenderer renderer = HtmlRenderer.builder()
            .extensions(headingAnchorExtensions)
            .extensions(tableExtension)
            .attributeProviderFactory(new AttributeProviderFactory() {
               public AttributeProvider create(AttributeProviderContext context) {
                  return new CustomAttributeProvider();
               }
            })
            .build();
      return renderer.render(document);
   }
 
   /**
    * 处理标签的属性
    */
   static class CustomAttributeProvider implements AttributeProvider {
      @Override
      public void setAttributes(Node node, String tagName, Map<String, String> attributes) {
         //改变a标签的target属性为_blank
         if (node instanceof Link) {
            attributes.put("target", "_blank");
         }
         if (node instanceof TableBlock) {
            attributes.put("class", "ui celled table");
         }
      }
   }
 
   public static void main(String[] args) throws IOException {
      String src = "# 一、标题\n ## 1.测试\n ```这是一段测试的文本```";
      System.out.println(markdownToHtmlExtensions(src));
   }
 
}

二、Html转Markdown

1.maven的pom.xml引入如下

    <dependency>
       <groupId>io.github.furstenheim</groupId>
       <artifactId>copy_down</artifactId>
       <version>1.0</version>
    </dependency>

2.测试类HtmlToMarkdownUtils.java

import io.github.furstenheim.CopyDown;
import io.github.furstenheim.Options;
import io.github.furstenheim.OptionsBuilder;

public class HtmlToMarkdownUtils {
    
    public static void main(String[] args) throws InterruptedException {
        String htmlStr ="
# 一、标题

## 1.测试

<code>这是一段测试的文本</code>
";
        System.out.println(htmlTansToMarkdown(htmlStr));
    }
    
    public static String htmlTansToMarkdown(String htmlStr) {
        OptionsBuilder optionsBuilder = OptionsBuilder.anOptions();
        Options options = optionsBuilder.withBr("-")
            // more options
            .build();
        CopyDown converter = new CopyDown(options);
        String markdownText = converter.convert(htmlStr);
        return markdownText;
   }

}

原文地址:https://blog.csdn.net/jxlhljh/article/details/124506103?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522168905673016800227434001%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=168905673016800227434001&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_ecpm_v1~rank_v31_ecpm-6-124506103-null-null.142^v88^control_2,239^v2^insert_chatgpt&utm_term=markdown

本文章网址:https://www.sjxi.cn/detil/9e7f2cb0a1b34bef91a5a67a51b6936a

打赏作者

本站为非盈利网站,如果您喜欢这篇文章,欢迎支持我们继续运营!

最新评论
当前未登陆哦
登陆后才可评论哦

湘ICP备2021009447号

×

(穷逼博主)在线接单

QQ: 1164453243

邮箱: abcdsjx@126.com

前端项目代做
前后端分离
Python 爬虫脚本
Java 后台开发
各种脚本编写
服务器搭建
个人博客搭建
Web 应用开发
Chrome 插件编写
Bug 修复