org.commonmark.renderer.html.HtmlRenderer Java Examples

The following examples show how to use org.commonmark.renderer.html.HtmlRenderer. 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: MockBodyPost.java    From Natty with GNU General Public License v3.0 6 votes vote down vote up
public MockBodyPost(String bodyMarkdown) {

        super("","",null,null,
                1, 1, "", bodyMarkdown, null, null, null, "", "");
        SOUser asker = new SOUser("testUser",-1,1,"registered");
        SOUser answerer = new SOUser("testUser",-1,1,"unregistered");

        setAnswerCreationDate(Instant.now());
        setQuestionCreationDate(Instant.EPOCH);
        setAsker(asker);
        setAnswerer(answerer);

        Parser parser = Parser.builder().build();
        Node document = parser.parse(bodyMarkdown);
        HtmlRenderer renderer = HtmlRenderer.builder().build();
        setBody(renderer.render(document));

    }
 
Example #3
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 #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: 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 #6
Source File: ParserTest.java    From commonmark-java with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void ioReaderTest() throws IOException {
    Parser parser = Parser.builder().build();

    InputStream input1 = TestResources.getSpec().openStream();
    Node document1;
    try (InputStreamReader reader = new InputStreamReader(input1, Charset.forName("UTF-8"))) {
        document1 = parser.parseReader(reader);
    }

    String spec = TestResources.readAsString(TestResources.getSpec());
    Node document2 = parser.parse(spec);

    HtmlRenderer renderer = HtmlRenderer.builder().escapeHtml(true).build();
    assertEquals(renderer.render(document2), renderer.render(document1));
}
 
Example #7
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 #8
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 #9
Source File: MarkDownProvider.java    From mvvm-template with GNU General Public License v3.0 6 votes vote down vote up
protected static void render(@NonNull TextView textView, String markdown, int width) {
    List<Extension> extensions = Arrays.asList(
            StrikethroughExtension.create(),
            AutolinkExtension.create(),
            TablesExtension.create(),
            InsExtension.create(),
            EmojiExtension.create(),
            MentionExtension.create(),
            YamlFrontMatterExtension.create());
    Parser parser = Parser.builder()
            .extensions(extensions)
            .build();
    try {
        Node node = parser.parse(markdown);
        String rendered = HtmlRenderer
                .builder()
                .extensions(extensions)
                .build()
                .render(node);
        HtmlHelper.htmlIntoTextView(textView, rendered, (width - (textView.getPaddingStart() + textView.getPaddingEnd())));
    } catch (Exception ignored) {
        HtmlHelper.htmlIntoTextView(textView, markdown, (width - (textView.getPaddingStart() + textView.getPaddingEnd())));
    }
}
 
Example #10
Source File: AndroidSupportTest.java    From commonmark-java with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void htmlRendererTest() throws Exception {
    Parser parser = Parser.builder().build();
    HtmlRenderer renderer = HtmlRenderer.builder().build();

    String renderedString = renderer.render(parser.parse(spec));

    assertNotNull(renderedString);
}
 
Example #11
Source File: ImageAttributesExtension.java    From commonmark-java with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void extend(HtmlRenderer.Builder rendererBuilder) {
    rendererBuilder.attributeProviderFactory(new AttributeProviderFactory() {
        @Override
        public AttributeProvider create(AttributeProviderContext context) {
            return ImageAttributesAttributeProvider.create();
        }
    });
}
 
Example #12
Source File: HeadingAnchorExtension.java    From commonmark-java with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void extend(HtmlRenderer.Builder rendererBuilder) {
    rendererBuilder.attributeProviderFactory(new AttributeProviderFactory() {
        @Override
        public AttributeProvider create(AttributeProviderContext context) {
            return HeadingIdAttributeProvider.create(defaultId, idPrefix, idSuffix);
        }
    });
}
 
Example #13
Source File: HeadingAnchorConfigurationTest.java    From commonmark-java with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private HtmlRenderer buildRenderer(String defaultId, String prefix, String suffix) {
    Extension ext = HeadingAnchorExtension.builder()
            .defaultId(defaultId)
            .idPrefix(prefix)
            .idSuffix(suffix)
            .build();
    return HtmlRenderer.builder()
            .extensions(Arrays.asList(ext))
            .build();
}
 
Example #14
Source File: HeadingAnchorConfigurationTest.java    From commonmark-java with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void testDefaultConfigurationHasNoAdditions() {
    HtmlRenderer renderer = HtmlRenderer.builder()
            .extensions(Arrays.asList(HeadingAnchorExtension.create()))
            .build();
    assertThat(doRender(renderer, "# "), equalTo("<h1 id=\"id\"></h1>\n"));
}
 
Example #15
Source File: TaskListItemsExtension.java    From commonmark-java with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void extend(HtmlRenderer.Builder rendererBuilder) {
    rendererBuilder.nodeRendererFactory(new HtmlNodeRendererFactory() {
        @Override
        public NodeRenderer create(HtmlNodeRendererContext context) {
            return new TaskListItemHtmlNodeRenderer(context);
        }
    });
}
 
Example #16
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 #17
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 #18
Source File: TablesExtension.java    From commonmark-java with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void extend(HtmlRenderer.Builder rendererBuilder) {
    rendererBuilder.nodeRendererFactory(new HtmlNodeRendererFactory() {
        @Override
        public NodeRenderer create(HtmlNodeRendererContext context) {
            return new TableHtmlNodeRenderer(context);
        }
    });
}
 
Example #19
Source File: MarkdownUtil.java    From pybbs with GNU Affero General Public License v3.0 5 votes vote down vote up
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 #20
Source File: DocMaker.java    From jeka with Apache License 2.0 5 votes vote down vote up
private String mdToHtml(String mdContent, String title) {
    final StringBuilder sb = new StringBuilder();
    final String rawHeader = new String(JkUtilsPath.readAllBytes(htmlTemplates.resolve("header.html")), UTF8);
    sb.append( rawHeader.replace("${title}", title).replace("${version}", version) );
    final Parser parser = Parser.builder().build();
    final Node document = parser.parse(mdContent);
    final List<MenuItem> menuItems = addAnchorAndNumberingToHeaders(document);
    addMenu(document, menuItems);
    final HtmlRenderer renderer = HtmlRenderer.builder().build();
    sb.append(renderer.render(document));
    sb.append( new String(JkUtilsPath.readAllBytes(htmlTemplates.resolve("footer.html")), UTF8) );
    return sb.toString();
}
 
Example #21
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 #22
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 #23
Source File: StrikethroughExtension.java    From commonmark-java with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void extend(HtmlRenderer.Builder rendererBuilder) {
    rendererBuilder.nodeRendererFactory(new HtmlNodeRendererFactory() {
        @Override
        public NodeRenderer create(HtmlNodeRendererContext context) {
            return new StrikethroughHtmlNodeRenderer(context);
        }
    });
}
 
Example #24
Source File: InsExtension.java    From commonmark-java with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void extend(HtmlRenderer.Builder rendererBuilder) {
    rendererBuilder.nodeRendererFactory(new HtmlNodeRendererFactory() {
        @Override
        public NodeRenderer create(HtmlNodeRendererContext context) {
            return new InsHtmlNodeRenderer(context);
        }
    });
}
 
Example #25
Source File: MarkDownProvider.java    From mvvm-template with GNU General Public License v3.0 5 votes vote down vote up
@NonNull public static String stripMdText(String markdown) {
    if (!InputHelper.isEmpty(markdown)) {
        Parser parser = Parser.builder().build();
        Node node = parser.parse(markdown);
        return stripHtml(HtmlRenderer.builder().build().render(node));
    }
    return "";
}
 
Example #26
Source File: MarkDownProvider.java    From mvvm-template with GNU General Public License v3.0 5 votes vote down vote up
public static void stripMdText(@NonNull TextView textView, String markdown) {
    if (!InputHelper.isEmpty(markdown)) {
        Parser parser = Parser.builder().build();
        Node node = parser.parse(markdown);
        textView.setText(stripHtml(HtmlRenderer.builder().build().render(node)));
    }
}
 
Example #27
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 #28
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 #29
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 #30
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;
}