How to Create HTML in Java Programmatically

HTML (HyperText Markup Language) is the standard for building web pages, and generating HTML programmatically is a common task in modern Java applications. If you need to create HTML files dynamically for reports, templates, or data-driven content, using a DOM-based API gives you full control over structure and styling.

In this guide, you’ll learn how to create HTML in Java programmatically, add elements using DOM manipulation, and save HTML files to disk. Using Aspose.HTML for Java , you can build and modify HTML documents directly via DOM APIs without relying on external tools or browsers. So, let’s create a new HTML document!


How to Generate an HTML File in Java (Basic Example)

Create a new HTML document from scratch using Java. Learn how to initialize a document, add basic content, and generate a valid HTML file:


Java code to create a new HTML file

// Initialize an empty HTML document using Aspose.HTML for Java API
HTMLDocument document = new HTMLDocument();

// Create a text node and add it to the document body
Text text = document.createTextNode("Hello, Aspose.HTML for Java!");
document.getBody().appendChild(text);

// Save the HTML document to disk
document.save("create-new-document.html");

  1. Create an HTML document from scratch using the HTMLDocument() constructor from Aspose.HTML for Java API. This creates an empty HTML document with proper HTML structure including <html>, <head>, and <body> elements.
  2. Work with the document by adding elements, text content, and styles using DOM manipulation methods. You can create HTML elements, set attributes, and build your document structure programmatically.
  3. Save the HTML file with the save() method to write the document to disk. The file will be saved in standard HTML format compatible with all modern web browsers.

How to Add Elements to HTML in Java Using DOM

When you need to generate HTML programmatically for reports, templates, or dynamic content, DOM-based manipulation gives you full control over structure and styling. Using Aspose.HTML for Java API, you can build a complete HTML document, inject CSS styles, add elements, and save it as a file – all without relying on external editors.

In this example, you’ll learn how to create an HTML file and add styled elements to it, then save the result to disk. This section covers DOM manipulation techniques for building structured HTML content.


Java code to create and populate HTML file with elements

// Create an empty HTML document using Aspose.HTML for Java API
HTMLDocument document = new HTMLDocument();

// Create and add CSS styles to the document head
Element style = document.createElement("style");
style.setTextContent(
	"body { font-family: Arial; margin: 40px; }" +
	".title { color: darkblue; }" +
	".highlight { color: green; font-weight: bold; }"
);

// Find the document header element and append the style element
Element head = document.getElementsByTagName("head").get_Item(0);
head.appendChild(style);

// Create a heading element with CSS class
HTMLHeadingElement h1 = (HTMLHeadingElement) document.createElement("h1");
h1.setClassName("title");
h1.appendChild(document.createTextNode("Create HTML with Java"));

// Create a paragraph element with CSS class
HTMLParagraphElement p = (HTMLParagraphElement) document.createElement("p");
p.setClassName("highlight");
Text text = document.createTextNode("This HTML file was generated programmatically using Aspose.HTML for Java.");
p.appendChild(text);

// Append elements to the document body
document.getBody().appendChild(h1);
document.getBody().appendChild(p);

// Save the HTML document to a file
document.save("output.html");

Steps to Create and Populate HTML Document in Java

  1. Use the HTMLDocument() constructor without parameters to create an empty HTML document using Aspose.HTML for Java API. This creates a new HTML document with default HTML structure.
  2. Access the <head> element using the getElementsByTagName() method and append a <style> element to define CSS rules for the document. This allows you to style your HTML content.
  3. Use the createElement() method of the Document class to create new HTML elements such as <h1> and <p>. You can create any HTML element supported by the standard.
  4. Assign CSS classes to elements with the setClassName() method to apply styles. This helps maintain consistent styling across your document.
  5. Use the createTextNode() method to generate text content for the created elements. This creates text nodes that can be added to HTML elements.
  6. Insert text nodes into elements using the appendChild() method. This adds the text content to your HTML elements.
  7. Access the document’s <body> element via the getBody() method and append the created elements to it. This adds your content to the visible part of the page.
  8. Call the save() method to write the resulting HTML document to a file. The file will be saved in standard HTML format.

To learn more about Aspose.HTML API, please visit our documentation guide. From the Create and Load HTML Document in Java article, you will find information on how to load a document from a file, URL and stream or create it from scratch. The Edit HTML Document documentation article gives you comprehensive information on how to read or edit the Document Object Model using Aspose.HTML for Java API. You will explore how to create HTML elements and how to work with them – modify the document by inserting new nodes, removing, or editing the content of existing nodes.


Frequently Asked Questions

1. How to create an HTML file in Java programmatically?
You can create an HTML file in Java by initializing an HTMLDocument object, adding elements using DOM methods like createElement() and appendChild(), and saving the result with the save() method. Libraries like Aspose.HTML for Java simplify this process by providing a complete API for HTML generation.

2. How to add CSS styles to an HTML document in Java?
To add CSS styles, create a <style> element using the createElement() method and append it to the <head> section of the document. Then assign class names to elements using setClassName() to apply the styles.

3. How to manipulate HTML DOM in Java?
You can manipulate the HTML DOM in Java using methods like createElement(), createTextNode(), appendChild(), and setAttribute(). These methods allow you to dynamically build and modify the structure and content of an HTML document.

4. What is the best library to create HTML in Java?
Several libraries support HTML generation in Java, but Aspose.HTML for Java is a powerful option for creating, editing, and converting HTML documents with full DOM support and no external dependencies.


Get Started with Aspose.HTML for Java Library

Aspose.HTML for Java is an advanced web scraping and HTML parsing library. One can create, edit, navigate through nodes, extract data and convert HTML, XHTML, and MHTML files to PDF, Images, and other formats. Moreover, it also handles CSS, HTML Canvas, SVG, XPath, and JavaScript out-of-the-box to extend manipulation tasks. It’s a standalone API and does not require any software installation.
You can download its latest version directly from Aspose Maven Repository and install it within your Maven-based project by adding the following configurations to the pom.xml.


Repository

<repository>
<id>AsposeJavaAPI</id>
<name>Aspose Java API</name>
<url>https://repository.aspose.com/repo/</url>
</repository>

Dependency

<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-html</artifactId>
<version>version of aspose-html API</version>
<classifier>jdk17</classifier>
</dependency>

Other Supported Features – Java HTML API

Use Aspose.HTML for Java to parse, manipulate, and convert HTML-based documents. Fast, safe and simple!