In order to pretty-print HTML code using Java code, we can make use of the jsoup library.
Maven Dependency (add in pom.xml):<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.16.1</version>
</dependency>
Gradle Dependency (add in build.gradle):
implementation group: 'org.jsoup', name: 'jsoup', version: '1.16.1'
Now, let's take a look at a code example.
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
public class JavaHTMLPrettyPrint {
public static void main(String[] args) {
String html = "<html><head><title>Code2care Examples</title></head><body><h1>Welcome to Code2care</h1></body></html>";
Document document = Jsoup.parse(html);
document.outputSettings().indentAmount(4).prettyPrint(true);
String prettyHtml = doc.html();
System.out.println(prettyHtml);
}
}
Output:
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!

Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!