How to pretty print HTML using Java Code

In order to pretty-print HTML code using Java code, we can make use of the jsoup library.

Maven Dependency (add in pom.xml):

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);
        String prettyHtml = doc.html();
Formatted HTML using Java Code

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail:

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap