Create and Load HTML Documents in Java

Aspose.HTML for Java lets you create an HTML document from scratch or load HTML from a file, URL, string, or stream. The HTMLDocument class represents the document as an in-memory DOM tree that you can inspect, edit, save, or pass to a converter.

Choose an HTMLDocument constructor that matches the input source. Use new HTMLDocument() for an empty document, new HTMLDocument(pathOrUrl) for a file or URL, and new HTMLDocument(html, baseUrl) or new HTMLDocument(stream, baseUrl) for in-memory content. A valid base URL is required to resolve relative resource paths. After creating or editing the document, call save() to write it to a file.

Source or taskRecommended API
Create an empty HTML documentnew HTMLDocument()
Build HTML with DOM methodsHTMLDocument, createTextNode(), appendChild()
Load an HTML file or URLnew HTMLDocument(pathOrUrl)
Create HTML from a stringnew HTMLDocument(html, baseUrl)
Create HTML from a streamnew HTMLDocument(stream, baseUrl)
Create an SVG document from markupnew SVGDocument(svg, baseUrl)
Start event-based document loadingHTMLDocument.navigate() with OnReadyStateChange or OnLoad

Create and Load HTML Documents

The HTMLDocument API follows familiar WHATWG DOM and HTML concepts, including documents, elements, attributes, text nodes, and child nodes. After creating or loading a document, you can use the DOM API to read or modify its content.

Create an Empty HTML Document

Use the default HTMLDocument() constructor when you need an empty document that can be populated later:

  1. Create an HTMLDocument with the default constructor.
  2. Add elements, attributes, text, or styles when required.
  3. Call save() to write the document to an output file.
1// Create an empty HTML document using Java
2
3// Initialize an empty HTML Document
4HTMLDocument document = new HTMLDocument();
5
6// Save the document to disk
7document.save("create-empty-document.html");

After saving, create-empty-document.html contains the initial <html>, <head>, and <body> structure:

1<html>
2    <head></head>
3    <body></body>
4</html>

For additional saving options, see Save HTML Document in Java.

Create a New HTML Document with DOM Nodes

Use DOM methods when the document structure must be generated programmatically:

  1. Create an empty HTMLDocument.
  2. Create a text node with createTextNode().
  3. Add the node to the document body with appendChild().
  4. Save the generated HTML document.
 1// Create an HTML document using Java
 2
 3// Initialize an empty HTML document
 4HTMLDocument document = new HTMLDocument();
 5
 6// Create a text node and add it to the document
 7Text text = document.createTextNode("Hello, World!");
 8document.getBody().appendChild(text);
 9
10// Save the document to disk
11document.save("create-new-document.html");

The example saves create-new-document.html with the text Hello, World! in the document body. For element, attribute, and CSS editing patterns, see Edit HTML Document in Java.

Load HTML from a File

Use the HTMLDocument(String) constructor when the source HTML already exists on disk:

  1. Prepare the path to the source HTML file.
  2. Create an HTMLDocument from the file path.
  3. Read, edit, save, or convert the loaded document.

The following example creates a small source file, loads it, and prints the root element markup:

 1// Load HTML from a file using Java
 2
 3// Prepare the "load-from-file.html" file
 4try (java.io.FileWriter fileWriter = new java.io.FileWriter("load-from-file.html")) {
 5    fileWriter.write("Hello, World!");
 6}
 7
 8// Load HTML from the file
 9HTMLDocument document = new HTMLDocument("load-from-file.html");
10
11// Write the document content to the output stream
12System.out.println(document.getDocumentElement().getOuterHTML());

Load HTML from a URL

Pass a remote page URL to HTMLDocument when the application needs to load web content directly:

  1. Pass the page URL to an HTMLDocument constructor.
  2. Let Aspose.HTML load the document and accessible linked resources.
  3. Read the DOM, edit it, extract markup, save the page, or convert it.

If the URL cannot be reached, the constructor throws a DOMException with the NetworkError code.

1// Load HTML from a URL using Java
2
3// Load a document from https://docs.aspose.com/html/files/document.html web page
4HTMLDocument document = new HTMLDocument("https://docs.aspose.com/html/files/document.html");
5
6System.out.println(document.getDocumentElement().getOuterHTML());

Remote loading depends on network access, server availability, redirects, and the processing environment. Use a controlled source when reproducible output is required.

Create HTML from In-Memory Content

When HTML markup already exists as a Java String or InputStream, you do not need to create a temporary source file. Pass the content and a base URL to a specialized constructor. The base URL determines how relative image, stylesheet, script, font, and link paths are resolved.

Create HTML from a String

Use HTMLDocument(String, String) when the HTML markup is stored in a Java string:

  1. Prepare the HTML markup.
  2. Pass the markup and base URL to the HTMLDocument constructor.
  3. Edit, save, or convert the created document.
 1// Create HTML from a string using Java
 2
 3// Prepare HTML code
 4String html_code = "<p>Hello, World!</p>";
 5
 6// Initialize a document from a string variable
 7HTMLDocument document = new HTMLDocument(html_code, ".");
 8
 9// Save the document to disk
10document.save("create-from-string.html");

The example uses . as the base URL because its markup has no linked resources. For HTML containing relative URLs, pass the local directory or remote address against which those URLs should be resolved.

Create HTML from a Stream

Use HTMLDocument(InputStream, String) when HTML comes from memory, storage, an HTTP response body, or another stream-based source:

  1. Prepare or receive the HTML stream.
  2. Ensure the stream is positioned at the content that should be read.
  3. Pass the stream and base URL to the HTMLDocument constructor.
  4. Save, edit, or convert the created document.
 1// Load HTML from a stream using Java
 2
 3// Create a memory stream object
 4String code = "<p>Hello, World! I love HTML!</p>";
 5java.io.InputStream inputStream = new java.io.ByteArrayInputStream(code.getBytes());
 6
 7// Initialize a document from the stream variable
 8HTMLDocument document = new HTMLDocument(inputStream, ".");
 9
10// Save the document to disk
11document.save("load-from-stream.html");

SVG, MHTML, and EPUB Support

Create an SVG Document from a String

Use SVGDocument for SVG content. SVG and HTML documents share DOM concepts, but SVG-specific workflows should use the SVG document and element APIs.

  1. Prepare SVG markup as a string.
  2. Pass the markup and base URL to SVGDocument.
  3. Read, edit, save, or convert the SVG document.

The following example creates an SVG document containing a circle and prints its root markup:

1// Load SVG from a string using Java
2
3// Initialize an SVG document from a string object
4SVGDocument document = new SVGDocument("<svg xmlns='http://www.w3.org/2000/svg'><circle cx='50' cy='50' r='40'/></svg>", ".");
5
6// Write the document content to the output stream
7System.out.println(document.getDocumentElement().getOuterHTML());

MHTML and EPUB Input

MHTML is a web archive that can contain HTML and related resources in one file. EPUB is an electronic publication format used by eReaders and reading applications. Do not pass these formats to the HTMLDocument constructors described on this page. To convert them, use the format-specific Converter.convertMHTML() or Converter.convertEPUB() methods. See Converting Between Formats in Java for complete workflows.

Load HTML Asynchronously

Loading a remote document may involve the HTML source, linked resources, and scripts. Use the HTMLDocument.navigate() method to start loading into an existing document, and handle completion through OnReadyStateChange or OnLoad. Both examples below use CountDownLatch with a timeout so the calling thread does not wait indefinitely.

Use OnReadyStateChange

Use OnReadyStateChange when the application needs to observe document readiness and continue after the state becomes complete:

  1. Create a CountDownLatch and an empty HTMLDocument.
  2. Subscribe to OnReadyStateChange.
  3. When getReadyState() returns complete, capture the loaded markup and release the latch.
  4. Call navigate() with the target URL.
  5. Wait up to the selected timeout before reading the captured result.

The enclosing method must handle or declare InterruptedException because it calls CountDownLatch.await().

 1import com.aspose.html.HTMLDocument;
 2import com.aspose.html.dom.events.DOMEventHandler;
 3import com.aspose.html.dom.events.Event;
 4
 5import java.util.concurrent.CountDownLatch;
 6import java.util.concurrent.TimeUnit;
 7
 8CountDownLatch loadCompleted = new CountDownLatch(1);
 9StringBuilder outerHTML = new StringBuilder();
10HTMLDocument document = new HTMLDocument();
11
12document.OnReadyStateChange.add(new DOMEventHandler() {
13    @Override
14    public void invoke(Object sender, Event event) {
15        if ("complete".equals(document.getReadyState())) {
16            outerHTML.setLength(0);
17            outerHTML.append(document.getDocumentElement().getOuterHTML());
18            loadCompleted.countDown();
19        }
20    }
21});
22
23document.navigate("https://docs.aspose.com/html/files/document.html");
24
25if (!loadCompleted.await(10, TimeUnit.SECONDS)) {
26    throw new IllegalStateException("The HTML document did not load within 10 seconds.");
27}
28
29System.out.println(outerHTML);

Use the OnLoad Event

Use OnLoad when the application only needs to react after document loading finishes:

  1. Create a latch and an empty HTMLDocument.
  2. Subscribe to OnLoad and process the loaded DOM in the handler.
  3. Call navigate() with the target URL.
  4. Wait for the event or stop after the configured timeout.
 1import com.aspose.html.HTMLDocument;
 2import com.aspose.html.dom.events.DOMEventHandler;
 3import com.aspose.html.dom.events.Event;
 4
 5import java.util.concurrent.CountDownLatch;
 6import java.util.concurrent.TimeUnit;
 7
 8CountDownLatch loadCompleted = new CountDownLatch(1);
 9HTMLDocument document = new HTMLDocument();
10
11document.OnLoad.add(new DOMEventHandler() {
12    @Override
13    public void invoke(Object sender, Event event) {
14        System.out.println(document.getDocumentElement().getOuterHTML());
15        loadCompleted.countDown();
16    }
17});
18
19document.navigate("https://docs.aspose.com/html/files/document.html");
20
21if (!loadCompleted.await(10, TimeUnit.SECONDS)) {
22    throw new IllegalStateException("The HTML document did not load within 10 seconds.");
23}

OnReadyStateChange can run more than once as the document moves through its readiness states. OnLoad is simpler when only completion matters. In both cases, perform dependent work after the relevant event rather than relying on a fixed Thread.sleep() delay.

Common Document Creation Issues

IssueCause and fix
Relative images, styles, scripts, or fonts are not loadedA string or stream was loaded without a suitable base URL. Pass the directory or address used to resolve relative resource paths.
A stream-based document is empty or incompleteThe stream starts at its current position. Position it at the content that must be read before creating the document.
URL loading fails with NetworkErrorCheck the URL, network access, server availability, redirects, and environment configuration.
Saved HTML contains only the initial document structureContent was not added to the empty document before save() was called. Add DOM nodes or load source HTML first.
Asynchronous code reads incomplete markupWait for the complete ready state or handle OnLoad before reading the DOM.

FAQ

How do I create an empty HTML document in Java?

Create an HTMLDocument with the default constructor, add DOM nodes if needed, and call save() with the output path.

How do I load an HTML file or webpage in Java?

Pass a local file path or webpage URL to an HTMLDocument constructor. After loading, you can read or modify the DOM, save the document, or convert it.

How do I create an HTML document from a string?

Use HTMLDocument(html, baseUrl). The first argument contains the HTML markup, and the second establishes the base URL for resolving relative resources.

Why does an HTML string or stream need a base URL?

The base URL resolves relative paths to images, stylesheets, scripts, fonts, links, and other resources. It can point to a local directory or remote address, depending on the source content.

Can I load HTML without waiting indefinitely?

Yes. Start loading with navigate(), handle OnReadyStateChange or OnLoad, and use an application-controlled timeout such as CountDownLatch.await(timeout, unit).

Other Platforms

Related Articles