Converting HTML Text to Markdown

2.8k Views Asked by At

I have an html Text which we get from rich text editor and where I need to convert that rich text to markdown text

for ex :

rich text return

<b> strong </b>
    to 
**strong**

Can any one help me in Android

4

There are 4 best solutions below

0
Gowthaman M On

you can also load from an HTML string:

 String summary = "<html><body>You scored <b>192</b> points.</body></html>";
 webview.loadData(summary, "text/html", null);

(or)

For example (< Android Nougat):

myTextView.setText(Html.fromHtml("<h2>Title</h2><br><p>Description here</p>"));

For example (>= Android Nougat):

myTextView.setText(Html.fromHtml("<h2>Title</h2><br><p>Description here</p>", Html.FROM_HTML_MODE_COMPACT));

My suggestion is better to use webview.because table tags and some more tags are not showing in Textview... Webview doc

1
Sabbir Ahmed On

Try this code

TextView textView = (TextView) findViewById(R.id.textView);
String htmlText = "<b> strong </b>";
textView.setText(Html.fromHtml(htmlText).toString());
1
asim On

you can use XSLT for converting html to markdown in java android. here is the example to use in Android.

 void test(String theHTML)
{
    File xsltFile = new File("mardownXSLT.xslt");

    Source xmlSource = new StreamSource(new StringReader(theHTML));
    Source xsltSource = new StreamSource(xsltFile);

    TransformerFactory transFact =
            TransformerFactory.newInstance();
    Transformer trans = transFact.newTransformer(xsltSource);

    StringWriter result = new StringWriter();
    trans.transform(xmlSource, new StreamResult(result));
}
0
Marteng On

You can use the remark library (the download on the page is broken but it's also available on maven central) which also supports GitHub and Multimarkdown flavored markdown. The code could look as follows:

public static void main(String[] args) {
    final String html = "<b>Foo</b>";
    final Remark remark = new com.overzealous.remark.Remark(com.overzealous.remark.Options.github()); // or Options.markdown() or Options.multiMarkdown()
    remark.setCleanedHtmlEchoed(false);
    System.out.println(remark.convert(html));
}

Output: **Foo**