views:

161

answers:

3

I need to convert HTML to plain text. My only requirement of formatting is to retain new lines in the plain text. New lines should be displayed not only in the case of < br > but other tags, eg. < tr/>, < /p> leads to a new line too.

Sample HTML pages for testing are: "http://www.particle.kth.se/~lindsey/JavaCourse/Book/Part1/Java/Chapter09/scannerConsole.html" or "http://www.javadb.com/write-to-file-using-bufferedwriter" . Note that these are only random urls.

I have tried out various libraries (JSoup, Javax.swing, Apache utils) mentioned in the following thread to convert HTML to plain text. Ref : "http://stackoverflow.com/questions/240546/removing-html-from-a-java-string"

Example using JSoup:

public class JSoupTest {

 @Test
 public void SimpleParse() {
  try {
   Document doc = Jsoup.connect("http://www.particle.kth.se/~lindsey/JavaCourse/Book/Part1/Java/Chapter09/scannerConsole.html").get();
   System.out.print(doc.text());

  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

Example with HTMLEditorKit:

import javax.swing.text.html.*;
import javax.swing.text.html.parser.*;

public class Html2Text extends HTMLEditorKit.ParserCallback {
 StringBuffer s;

 public Html2Text() {}

 public void parse(Reader in) throws IOException {
   s = new StringBuffer();
   ParserDelegator delegator = new ParserDelegator();
   // the third parameter is TRUE to ignore charset directive
   delegator.parse(in, this, Boolean.TRUE);
 }

 public void handleText(char[] text, int pos) {
   s.append(text);
 }

 public String getText() {
   return s.toString();
 }

 public static void main (String[] args) {
   try {
     // the HTML to convert
    URL  url = new URL("http://www.javadb.com/write-to-file-using-bufferedwriter");
    URLConnection conn = url.openConnection();
    BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
    String inputLine;
    String finalContents = "";
    while ((inputLine = reader.readLine()) != null) {
     finalContents += "\n" + inputLine.replace("<br", "\n<br");
    }
    BufferedWriter writer = new BufferedWriter(new FileWriter("samples/testHtml.html"));
    writer.write(finalContents);
    writer.close();

     FileReader in = new FileReader("samples/testHtml.html");
     Html2Text parser = new Html2Text();
     parser.parse(in);
     in.close();
     System.out.println(parser.getText());
   }
   catch (Exception e) {
     e.printStackTrace();
   }
 }
}


+2  A: 

I would guess you could use the ParserCallback.

You would need to add code to support the tags that require special handling. There are:

  1. handleStartTag
  2. handleEndTag
  3. handleSimpleTag

callbacks that should allow you to check for the tags you want to monitor and then append a newline character to your buffer.

camickr
I don't know how to do that. Instead I just prefixed all the required tags like <br>, <p> , etc.. with a \n . And then let the parser perform the parsing. Still the final string returned does not contain the new line chars at the mentioned positions.
Aniket
+1  A: 

You can use XSLT for this purpose. Take a look at this link which addresses a similar problem.

Hope it is helpful.

Suresh Kumar
.... assuming the HTML is well-formed.
Ira Baxter
A: 

I would use SAX. If your document is not well-formed XHTML, I would transform it with JTidy.

mrrtnn