Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.
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 task | Recommended API |
|---|---|
| Create an empty HTML document | new HTMLDocument() |
| Build HTML with DOM methods | HTMLDocument,
createTextNode(),
appendChild() |
| Load an HTML file or URL | new HTMLDocument(pathOrUrl) |
| Create HTML from a string | new HTMLDocument(html, baseUrl) |
| Create HTML from a stream | new HTMLDocument(stream, baseUrl) |
| Create an SVG document from markup | new SVGDocument(svg, baseUrl) |
| Start event-based document loading | HTMLDocument.navigate() with OnReadyStateChange or OnLoad |
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.
Use the default HTMLDocument() constructor when you need an empty document that can be populated later:
HTMLDocument with the default constructor.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.
Use DOM methods when the document structure must be generated programmatically:
HTMLDocument. 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.
Use the HTMLDocument(String) constructor when the source HTML already exists on disk:
HTMLDocument from the file path.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());Pass a remote page URL to HTMLDocument when the application needs to load web content directly:
HTMLDocument constructor.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.
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.
Use HTMLDocument(String, String) when the HTML markup is stored in a Java string:
HTMLDocument constructor. 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.
Use HTMLDocument(InputStream, String) when HTML comes from memory, storage, an HTTP response body, or another stream-based source:
HTMLDocument constructor. 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");Use SVGDocument for SVG content. SVG and HTML documents share DOM concepts, but SVG-specific workflows should use the SVG document and element APIs.
SVGDocument.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 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.
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 when the application needs to observe document readiness and continue after the state becomes complete:
CountDownLatch and an empty HTMLDocument.OnReadyStateChange.getReadyState() returns complete, capture the loaded markup and release the latch.navigate() with the target URL.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 OnLoad when the application only needs to react after document loading finishes:
HTMLDocument.OnLoad and process the loaded DOM in the handler.navigate() with the target URL. 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.
| Issue | Cause and fix |
|---|---|
| Relative images, styles, scripts, or fonts are not loaded | A 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 incomplete | The stream starts at its current position. Position it at the content that must be read before creating the document. |
URL loading fails with NetworkError | Check the URL, network access, server availability, redirects, and environment configuration. |
| Saved HTML contains only the initial document structure | Content was not added to the empty document before save() was called. Add DOM nodes or load source HTML first. |
| Asynchronous code reads incomplete markup | Wait for the complete ready state or handle OnLoad before reading the DOM. |
Create an HTMLDocument with the default constructor, add DOM nodes if needed, and call save() with the output path.
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.
Use HTMLDocument(html, baseUrl). The first argument contains the HTML markup, and the second establishes the base URL for resolving relative resources.
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.
Yes. Start loading with navigate(), handle OnReadyStateChange or OnLoad, and use an application-controlled timeout such as CountDownLatch.await(timeout, unit).
Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.