Main Tutorials

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 Author

author image
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

Subscribe
Notify of
1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Sayyed
2 years ago

String html = “<h1>hello world</h1>” It add html tags and all . Is there anyway to just prettyprint what ever is passed ?