Java – Pretty Print HTML

In Java, we can use jsoup, a Java HTML parser, to parse a HTML code and pretty print it.

pom.xml

  <dependency>
      <groupId>org.jsoup</groupId>
      <artifactId>jsoup</artifactId>
      <version>1.12.1</version>
  </dependency>
JavaPrettyPrintHTML.java

package com.mkyong;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

public class JavaPrettyPrintHTML {

    public static void main(String[] args) {

        String html = "<html><body><h1>hello world</h1></body></html>";
        System.out.println(html);           // original

        Document doc = Jsoup.parse(html);   // pretty print HTML
        System.out.println(doc.toString());

    }

}

Output


<html><body><h1>hello world</h1></body></html>

<html>
 <head></head>
 <body>
  <h1>hello world</h1>
 </body>
</html>

References

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar