Java Code Examples for org.commonmark.renderer.html.HtmlRenderer#render()

The following examples show how to use org.commonmark.renderer.html.HtmlRenderer#render() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MarkdownUtil.java    From Roothub with GNU Affero General Public License v3.0 7 votes vote down vote up
/**
 * 渲染 Markdown
 * @param content
 * @return
 */
public static String render(String content) {
    List<Extension> extensions = Arrays.asList(
            AutolinkExtension.create(),
            TablesExtension.create());

    Parser parser = Parser.builder()
            .extensions(extensions)
            .build();
    // 回车一次就可以实现换行
    HtmlRenderer renderer = HtmlRenderer.builder()
            .softbreak("<br/>")
            .attributeProviderFactory(context -> new MyAttributeProvider())
            .extensions(extensions)
            .build();
    Node document = parser.parse(content == null ? "" : content);
    return renderer.render(document);
}
 
Example 2
Source File: MarkdownController.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@PostMapping("/")
public String markdownRenderer(@RequestBody String payload) {
  // Set up HTML renderer
  // https://github.com/atlassian/commonmark-java#extensions
  List<Extension> extensions =
      Arrays.asList(TablesExtension.create(), StrikethroughExtension.create());
  Parser parser = Parser.builder().extensions(extensions).build();
  Node document = parser.parse(payload);
  HtmlRenderer renderer = HtmlRenderer.builder().extensions(extensions).build();
  // Convert Markdown to HTML
  String converted = renderer.render(document);

  // Use prepackaged policies to sanitize HTML. Cusomized and tighter standards
  // are recommended.
  PolicyFactory policy =
      Sanitizers.FORMATTING
          .and(Sanitizers.BLOCKS)
          .and(Sanitizers.LINKS)
          .and(Sanitizers.IMAGES)
          .and(Sanitizers.TABLES);
  String safeHtml = policy.sanitize(converted);

  return safeHtml;
}
 
Example 3
Source File: FUN_Markdown.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
@Override
public NodeValue exec(NodeValue markdown) {
    if (markdown.getDatatypeURI() != null
            && !markdown.getDatatypeURI().equals(datatypeUri)
            && !markdown.getDatatypeURI().equals("http://www.w3.org/2001/XMLSchema#string")) {
        LOG.debug("The URI of NodeValue1 must be <" + datatypeUri + ">"
                + "or <http://www.w3.org/2001/XMLSchema#string>."
        );
    }
    try {
    	String md = markdown.asNode().getLiteralLexicalForm();
     Parser parser = Parser.builder().build();
     Node document = parser.parse(md);
     HtmlRenderer renderer = HtmlRenderer.builder().build();
     String html = renderer.render(document);
     return new NodeValueString(html);
    } catch (Exception ex) {
        throw new ExprEvalException("FunctionBase: no evaluation", ex);
    }
}
 
Example 4
Source File: FUN_Markdown.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
@Override
public NodeValue exec(NodeValue markdown) {
    if (markdown.getDatatypeURI() != null
            && !markdown.getDatatypeURI().equals(datatypeUri)
            && !markdown.getDatatypeURI().equals("http://www.w3.org/2001/XMLSchema#string")) {
        LOG.debug("The URI of NodeValue1 must be <" + datatypeUri + ">"
                + "or <http://www.w3.org/2001/XMLSchema#string>."
        );
    }
    try {
    	String md = markdown.asNode().getLiteralLexicalForm();
     Parser parser = Parser.builder().build();
     Node document = parser.parse(md);
     HtmlRenderer renderer = HtmlRenderer.builder().build();
     String html = renderer.render(document);
     return new NodeValueString(html);
    } catch (Exception ex) {
        throw new ExprEvalException("FunctionBase: no evaluation", ex);
    }
}
 
Example 5
Source File: FileViewFragment.java    From lbry-android with MIT License 6 votes vote down vote up
private String buildMarkdownHtml(String markdown) {
    Parser parser = Parser.builder().build();
    Node document = parser.parse(markdown);
    HtmlRenderer renderer = HtmlRenderer.builder().build();
    String markdownHtml = renderer.render(document);

    return "<!doctype html>\n" +
            "        <html>\n" +
            "          <head>\n" +
            "            <meta charset=\"utf-8\"/>\n" +
            "            <meta name=\"viewport\" content=\"width=device-width, user-scalable=no\"/>\n" +
            "            <style type=\"text/css\">\n" +
            "              body { font-family: 'Inter', sans-serif; margin: 16px }\n" +
            "              img { width: 100%; }\n" +
            "              pre { white-space: pre-wrap; word-wrap: break-word }\n" +
            "            </style>\n" +
            "          </head>\n" +
            "          <body>\n" +
            "            <div id=\"content\">\n" +
            markdownHtml +
            "            </div>\n" +
            "          </body>\n" +
            "        </html>";
}
 
Example 6
Source File: TaleUtils.java    From tale with MIT License 6 votes vote down vote up
/**
 * markdown转换为html
 *
 * @param markdown
 * @return
 */
public static String mdToHtml(String markdown) {
    if (StringKit.isBlank(markdown)) {
        return "";
    }

    List<Extension> extensions = Arrays.asList(TablesExtension.create());
    Parser          parser     = Parser.builder().extensions(extensions).build();
    Node            document   = parser.parse(markdown);
    HtmlRenderer    renderer   = HtmlRenderer.builder().extensions(extensions).build();
    String          content    = renderer.render(document);
    content = Commons.emoji(content);

    // 支持网易云音乐输出
    if (TaleConst.BCONF.getBoolean("app.support_163_music", true) && content.contains("[mp3:")) {
        content = content.replaceAll("\\[mp3:(\\d+)\\]", "<iframe frameborder=\"no\" border=\"0\" marginwidth=\"0\" marginheight=\"0\" width=350 height=106 src=\"//music.163.com/outchain/player?type=2&id=$1&auto=0&height=88\"></iframe>");
    }
    // 支持gist代码输出
    if (TaleConst.BCONF.getBoolean("app.support_gist", true) && content.contains("https://gist.github.com/")) {
        content = content.replaceAll("&lt;script src=\"https://gist.github.com/(\\w+)/(\\w+)\\.js\">&lt;/script>", "<script src=\"https://gist.github.com/$1/$2\\.js\"></script>");
    }

    return content;
}
 
Example 7
Source File: RenderMarkdown.java    From symja_android_library with GNU General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) {
	Set<Extension> EXTENSIONS = Collections.singleton(TablesExtension.create());
	Parser parser = Parser.builder().extensions(EXTENSIONS).build();
	Node document = parser.parse(TABLE);
	HtmlRenderer renderer = HtmlRenderer.builder().extensions(EXTENSIONS).build();
	String html = renderer.render(document);
	System.out.println(html);
}
 
Example 8
Source File: MarkDownUtil.java    From My-Blog with Apache License 2.0 5 votes vote down vote up
/**
 * 转换md格式为html
 *
 * @param markdownString
 * @return
 */
public static String mdToHtml(String markdownString) {
    if (StringUtils.isEmpty(markdownString)) {
        return "";
    }
    java.util.List<Extension> extensions = Arrays.asList(TablesExtension.create());
    Parser parser = Parser.builder().extensions(extensions).build();
    Node document = parser.parse(markdownString);
    HtmlRenderer renderer = HtmlRenderer.builder().extensions(extensions).build();
    String content = renderer.render(document);
    return content;
}
 
Example 9
Source File: AndroidSupportTest.java    From commonmark-java with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void parseWithExtensionsTest(Extension extension) throws Exception {
    Parser parser = Parser.builder()
            .extensions(Collections.singletonList(extension))
            .build();

    Node document = parser.parse(spec);
    assertNotNull(document);

    HtmlRenderer renderer = HtmlRenderer.builder()
            .extensions(Collections.singletonList(extension))
            .build();

    String renderedString = renderer.render(document);
    assertNotNull(renderedString);
}
 
Example 10
Source File: DocumentationPod.java    From symja_android_library with GNU General Public License v3.0 5 votes vote down vote up
private static String generateHTMLString(final String markdownStr) {
	Set<Extension> EXTENSIONS = Collections.singleton(TablesExtension.create());
	Parser parser = Parser.builder().extensions(EXTENSIONS).build();
	Node document = parser.parse(markdownStr);
	HtmlRenderer renderer = HtmlRenderer.builder().extensions(EXTENSIONS).build();
	return renderer.render(document);
}
 
Example 11
Source File: MyUtils.java    From Jantent with MIT License 5 votes vote down vote up
/**
 * markdown转换为html
 *
 * @param markdown
 * @return
 */
public static String mdToHtml(String markdown) {
    if (StringUtils.isBlank(markdown)) {
        return "";
    }
    List<Extension> extensions = Arrays.asList(TablesExtension.create());
    Parser          parser     = Parser.builder().extensions(extensions).build();
    Node document = parser.parse(markdown);
    HtmlRenderer renderer = HtmlRenderer.builder()
            .attributeProviderFactory(context -> new LinkAttributeProvider())
            .extensions(extensions).build();
    String content = renderer.render(document);
    content = Commons.emoji(content);
    return content;
}
 
Example 12
Source File: MdToHtml.java    From xian with Apache License 2.0 5 votes vote down vote up
/**
 * @param md the markdown string.
 * @return converted html
 */
public static String mdToHtml(String md) {
    Parser parser = Parser.builder().build();
    Node document = parser.parse(md);
    HtmlRenderer renderer = HtmlRenderer.builder().build();
    return renderer.render(document);
}
 
Example 13
Source File: TaleUtils.java    From my-site with Apache License 2.0 5 votes vote down vote up
/**
 * markdown转换为html
 *
 * @param markdown
 * @return
 */
public static String mdToHtml(String markdown) {
    if (StringUtils.isBlank(markdown)) {
        return "";
    }
    java.util.List<Extension> extensions = Arrays.asList(TablesExtension.create());
    Parser parser = Parser.builder().extensions(extensions).build();
    Node document = parser.parse(markdown);
    HtmlRenderer renderer = HtmlRenderer.builder().extensions(extensions).build();
    String content = renderer.render(document);
    content = Commons.emoji(content);
    return content;
}
 
Example 14
Source File: MarkDownUtils.java    From My-Blog-layui with Apache License 2.0 5 votes vote down vote up
/**
 * 转换md格式为html
 *
 * @param markdownString
 * @return
 */
public static String mdToHtml(String markdownString) {
    if (StringUtils.isEmpty(markdownString)) {
        return "";
    }
    List<Extension> extensions = Arrays.asList(TablesExtension.create());
    Parser parser = Parser.builder().extensions(extensions).build();
    Node document = parser.parse(markdownString);
    HtmlRenderer renderer = HtmlRenderer.builder().extensions(extensions).build();
    return renderer.render(document);
}
 
Example 15
Source File: MarkDownProcessor.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private String processCommonMark(String source) {
  Set<Extension> extensions = Collections.singleton(TablesExtension.create());
  Parser parser = Parser.builder().extensions(extensions).build();
  Node document = parser.parse(source);
  HtmlRenderer renderer = HtmlRenderer.builder().extensions(extensions).build();
  String html = renderer.render(document);
  html = html.replace("<table>", "<table class=\"grid\">");
  return html;  
}
 
Example 16
Source File: HierarchicalTableGenerator.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
public Cell addMarkdown(String md) {
  try {
    Parser parser = Parser.builder().build();
    Node document = parser.parse(md);
    HtmlRenderer renderer = HtmlRenderer.builder().escapeHtml(true).build();
    String html = renderer.render(document);  
    pieces.addAll(htmlToParagraphPieces(html));
  } catch (Exception e) {
    e.printStackTrace();
  }
  return this;
}
 
Example 17
Source File: HeadingAnchorConfigurationTest.java    From commonmark-java with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private String doRender(HtmlRenderer renderer, String text) {
    return renderer.render(PARSER.parse(text));
}
 
Example 18
Source File: TablesTest.java    From commonmark-java with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Test
public void attributeProviderIsApplied() {
    AttributeProviderFactory factory = new AttributeProviderFactory() {
        @Override
        public AttributeProvider create(AttributeProviderContext context) {
            return new AttributeProvider() {
                @Override
                public void setAttributes(Node node, String tagName, Map<String, String> attributes) {
                    if (node instanceof TableBlock) {
                        attributes.put("test", "block");
                    } else if (node instanceof TableHead) {
                        attributes.put("test", "head");
                    } else if (node instanceof TableBody) {
                        attributes.put("test", "body");
                    } else if (node instanceof TableRow) {
                        attributes.put("test", "row");
                    } else if (node instanceof TableCell) {
                        attributes.put("test", "cell");
                    }
                }
            };
        }
    };
    HtmlRenderer renderer = HtmlRenderer.builder()
            .attributeProviderFactory(factory)
            .extensions(EXTENSIONS)
            .build();
    String rendered = renderer.render(PARSER.parse("Abc|Def\n---|---\n1|2"));
    assertThat(rendered, is("<table test=\"block\">\n" +
            "<thead test=\"head\">\n" +
            "<tr test=\"row\">\n" +
            "<th test=\"cell\">Abc</th>\n" +
            "<th test=\"cell\">Def</th>\n" +
            "</tr>\n" +
            "</thead>\n" +
            "<tbody test=\"body\">\n" +
            "<tr test=\"row\">\n" +
            "<td test=\"cell\">1</td>\n" +
            "<td test=\"cell\">2</td>\n" +
            "</tr>\n" +
            "</tbody>\n" +
            "</table>\n"));
}
 
Example 19
Source File: MarkdownToHTML.java    From symja_android_library with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Generate markdown links for Symja function reference.
 * 
 * @param sourceLocation
 *            source directory for funtions (*.md) files
 */
public static void generateHTMLString(final File sourceLocation, String function, boolean javadoc) {
	if (sourceLocation.exists()) {
		// Get the list of the files contained in the package
		final String[] files = sourceLocation.list();
		if (files != null) {
			for (int i = 0; i < files.length; i++) {
				if (files[i].endsWith(".md")) {

					String className = files[i].substring(0, files[i].length() - 3);
					if (className.equals(function)) {
						File file = new File(sourceLocation + "/" + files[i]);
						String html;
						try {
							Set<Extension> EXTENSIONS = Collections.singleton(TablesExtension.create());
							Parser parser = Parser.builder().extensions(EXTENSIONS).build();
							Node document = parser.parse(Files.asCharSource(file, Charsets.UTF_8).read());
							HtmlRenderer renderer = HtmlRenderer.builder().extensions(EXTENSIONS).build();
							html = renderer.render(document);
							if (javadoc) {
								String[] lines = html.split("\\n");
								System.out.println("/**");
								for (int j = 0; j < lines.length; j++) {
									if (!lines[j].startsWith("<h2>")) {
										System.out.println(" * " + lines[j]);
									}
								}
								System.out.println(" */");
							} else {
								System.out.println(html);
							}
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
				}
			}
		}
	}

}
 
Example 20
Source File: InstallService.java    From zrlog with Apache License 2.0 4 votes vote down vote up
public static String renderMd(String md) {
    Parser parser = Parser.builder().build();
    Node document = parser.parse(md);
    HtmlRenderer renderer = HtmlRenderer.builder().build();
    return renderer.render(document);
}