### Install Aspose.HTML for Java via Gradle
Source: https://github.com/aspose-html/aspose.html-for-java/blob/master/docs/installation.md
Integrate Aspose.HTML for Java into your project by adding the Aspose repository and the necessary dependency to your build.gradle file. This enables the use of the library's features for HTML manipulation.
```gradle
repositories {
maven {
url = uri('https://repository.aspose.com/repo/')
}
}
dependencies {
implementation "com.aspose:aspose-html:25.12"
}
```
--------------------------------
### Install Aspose.HTML for Java via Maven
Source: https://github.com/aspose-html/aspose.html-for-java/blob/master/docs/installation.md
Incorporate Aspose.HTML for Java into your Maven project by specifying the Aspose repository and dependency within your pom.xml file. This setup allows for direct utilization of the library's extensive HTML functionalities.
```xml
snapshotsrepohttp://repository.aspose.com/repo/com.asposeaspose-html25.12jdk16
```
--------------------------------
### Install Aspose.HTML for Java using Gradle
Source: https://github.com/aspose-html/aspose.html-for-java/blob/master/README.md
This snippet shows how to add the Aspose.HTML for Java library as a dependency in a Gradle build script. It specifies the group, artifact, version, and classifier for the dependency.
```java
compile(group: 'com.aspose', name: 'aspose-html', version: '25.12', classifier: 'jdk16')
```
--------------------------------
### Convert EPUB to PDF
Source: https://context7.com/aspose-html/aspose.html-for-java/llms.txt
Converts electronic publication (EPUB) files to PDF format for document distribution.
```APIDOC
## Convert EPUB to PDF
### Description
Converts electronic publication (EPUB) files to PDF format for document distribution.
### Method
POST
### Endpoint
/convert/epub-to-pdf
### Parameters
#### Query Parameters
- **outputPath** (string) - Required - The path where the output PDF file will be saved.
#### Request Body
- **fileInputStream** (file) - Required - The EPUB file to convert.
- **options** (object) - Optional - PDF save options. (Specific fields depend on `PdfSaveOptions`)
### Request Example
```json
{
"outputPath": "output.pdf",
"options": {}
}
```
(Note: The actual file upload would be handled via multipart/form-data in a real HTTP request.)
### Response
#### Success Response (200)
- **message** (string) - A confirmation message indicating the successful conversion.
#### Response Example
```json
{
"message": "PDF file created at output.pdf"
}
```
```
--------------------------------
### Convert MHTML to PDF
Source: https://context7.com/aspose-html/aspose.html-for-java/llms.txt
Transforms MHTML web archive files into PDF documents.
```APIDOC
## Convert MHTML to PDF
### Description
Transforms MHTML web archive files into PDF documents.
### Method
POST
### Endpoint
/convert/mhtml-to-pdf
### Parameters
#### Query Parameters
- **outputPath** (string) - Required - The path where the output PDF file will be saved.
#### Request Body
- **fileInputStream** (file) - Required - The MHTML file to convert.
- **options** (object) - Optional - PDF save options. (Specific fields depend on `PdfSaveOptions`)
### Request Example
```json
{
"outputPath": "output.pdf",
"options": {}
}
```
(Note: The actual file upload would be handled via multipart/form-data in a real HTTP request.)
### Response
#### Success Response (200)
- **message** (string) - A confirmation message indicating the successful conversion.
#### Response Example
```json
{
"message": "PDF file created at output.pdf"
}
```
```
--------------------------------
### Convert EPUB to PDF using Java
Source: https://context7.com/aspose-html/aspose.html-for-java/llms.txt
Shows how to convert an EPUB file to a PDF document using the `Converter.convertEPUB()` method. This is suitable for document distribution in a widely accessible format.
```java
import com.aspose.html.converters.Converter;
import com.aspose.html.saving.PdfSaveOptions;
// Open an existing EPUB file for reading
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("input.epub");
// Create PDF save options
PdfSaveOptions options = new PdfSaveOptions();
// Convert EPUB to PDF
Converter.convertEPUB(fileInputStream, options, "output.pdf");
// Output: PDF file created at "output.pdf"
```
--------------------------------
### Download Web Page Content in Java
Source: https://github.com/aspose-html/aspose.html-for-java/blob/master/README.md
This Java code example shows how to download the content of a web page and save it as an HTML file using Aspose.HTML for Java. It initializes an HTMLDocument from a URL and saves it to a specified path.
```java
import com.aspose.html.HTMLDocument;
// Initialize an HTML document from a URL
final HTMLDocument document = new HTMLDocument("https://docs.aspose.com/html/net/message-handlers/");
// Prepare a path to save the downloaded file
String savePath = "root/result.html";
// Save the HTML document to the specified file
document.save(savePath);
```
--------------------------------
### Convert Markdown to HTML using Java
Source: https://context7.com/aspose-html/aspose.html-for-java/llms.txt
Demonstrates how to convert a Markdown file to an HTML document using the `Converter.convertMarkdown()` method. This is useful for web publishing or further processing of Markdown content.
```java
import com.aspose.html.converters.Converter;
// Prepare Markdown content
String markdownCode = "### Hello, World! \n" +
"[visit applications](https://products.aspose.app/html/family)";
// Save Markdown to file
try (java.io.FileWriter fileWriter = new java.io.FileWriter("document.md")) {
fileWriter.write(markdownCode);
}
// Convert Markdown to HTML
Converter.convertMarkdown("document.md", "output.html");
// Output: HTML file created at "output.html"
```
--------------------------------
### Convert Markdown to HTML
Source: https://context7.com/aspose-html/aspose.html-for-java/llms.txt
Transforms Markdown files into HTML documents for web publishing or further processing.
```APIDOC
## Convert Markdown to HTML
### Description
Transforms Markdown files into HTML documents for web publishing or further processing.
### Method
POST (or a custom method if the API is not strictly RESTful, but based on the Java method signature, it implies an operation)
### Endpoint
/convert/markdown
### Parameters
#### Query Parameters
- **inputPath** (string) - Required - The path to the input Markdown file.
- **outputPath** (string) - Required - The path where the output HTML file will be saved.
### Request Body
(This method appears to operate on file paths directly, so a request body might not be applicable in a typical RESTful sense. If it were a web API, it might accept file content or paths in the body.)
### Request Example
(Assuming a hypothetical REST API endpoint)
```json
{
"inputPath": "document.md",
"outputPath": "output.html"
}
```
### Response
#### Success Response (200)
- **message** (string) - A confirmation message indicating the successful conversion.
#### Response Example
```json
{
"message": "HTML file created at output.html"
}
```
```
--------------------------------
### Navigate HTML DOM with Aspose.HTML for Java
Source: https://context7.com/aspose-html/aspose.html-for-java/llms.txt
This example showcases how to traverse the Document Object Model (DOM) of an HTML document using the `HTMLDocument` class and its element traversal methods. It demonstrates accessing child and sibling elements to extract text content, requiring the Aspose.HTML library.
```java
import com.aspose.html.HTMLDocument;
import com.aspose.html.dom.Element;
// Initialize document from HTML code
String htmlCode = "Hello,World!";
HTMLDocument document = new HTMLDocument(htmlCode, ".");
// Get the first child element of the body
Element element = document.getBody().getFirstElementChild();
System.out.println(element.getTextContent());
// Output: Hello,
// Get the next sibling element
element = element.getNextElementSibling();
System.out.println(element.getTextContent());
// Output: World!
```
--------------------------------
### Convert MHTML to PDF using Java
Source: https://context7.com/aspose-html/aspose.html-for-java/llms.txt
Illustrates the conversion of MHTML web archive files to PDF documents using the `Converter.convertMHTML()` method. This preserves the content of web archives in a printable format.
```java
import com.aspose.html.converters.Converter;
import com.aspose.html.saving.PdfSaveOptions;
// Open an existing MHTML file for reading
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("sample.mht");
// Create PDF save options
PdfSaveOptions options = new PdfSaveOptions();
// Convert MHTML to PDF
Converter.convertMHTML(fileInputStream, options, "output.pdf");
// Output: PDF file created at "output.pdf"
```
--------------------------------
### Query HTML Elements with XPath using Aspose.HTML for Java
Source: https://context7.com/aspose-html/aspose.html-for-java/llms.txt
This example demonstrates advanced element selection within an HTML document by executing XPath expressions using the `evaluate()` method. It iterates through the results of the XPath query and prints the text content of the matched nodes, showcasing powerful data extraction capabilities with Aspose.HTML.
```java
import com.aspose.html.HTMLDocument;
import com.aspose.html.dom.Node;
import com.aspose.html.dom.xpath.IXPathResult;
import com.aspose.html.dom.xpath.XPathResultType;
// Prepare HTML code
String htmlCode = "
\n" +
"
Hello!
\n" +
"
\n" +
"
\n" +
" World!\n" +
"
\n";
// Initialize document
HTMLDocument document = new HTMLDocument(htmlCode, ".");
// Evaluate XPath expression
IXPathResult result = document.evaluate(
"//*[@class='happy']//span",
document,
null,
XPathResultType.Any,
null
);
// Iterate over results
for (Node node; (node = result.iterateNext()) != null; ) {
System.out.println(node.getTextContent());
}
// Output: Hello!
// Output: World!
```
--------------------------------
### Convert HTML5 Canvas with JavaScript to PDF using Aspose.HTML for Java
Source: https://context7.com/aspose-html/aspose.html-for-java/llms.txt
Renders HTML content, including HTML5 Canvas elements with JavaScript, to a PDF document. This example demonstrates creating an HTML file with a canvas and JavaScript, then converting it to PDF. Requires Aspose.HTML for Java.
```java
import com.aspose.html.HTMLDocument;
import com.aspose.html.converters.Converter;
import com.aspose.html.saving.PdfSaveOptions;
// Prepare HTML5 Canvas with JavaScript
String htmlCode = "" +
"";
// Save HTML to file
try (java.io.FileWriter fileWriter = new java.io.FileWriter("canvas.html")) {
fileWriter.write(htmlCode);
}
// Initialize document and convert
HTMLDocument document = new HTMLDocument("canvas.html");
Converter.convertHTML(document, new PdfSaveOptions(), "canvas-output.pdf");
// Output: PDF with rendered canvas containing "Hello World" text
```
--------------------------------
### Convert HTML to Image (PNG/JPEG/BMP/TIFF/GIF) using Aspose.HTML for Java
Source: https://context7.com/aspose-html/aspose.html-for-java/llms.txt
Shows how to convert HTML content into various image formats like PNG, JPEG, BMP, TIFF, and GIF using Aspose.HTML for Java. The `Converter.convertHTML()` method is utilized with `ImageSaveOptions` to specify the desired output format. The code demonstrates conversion to PNG and provides an example for JPEG.
```java
import com.aspose.html.HTMLDocument;
import com.aspose.html.converters.Converter;
import com.aspose.html.rendering.image.ImageFormat;
import com.aspose.html.saving.ImageSaveOptions;
// Initialize an HTML document
HTMLDocument document = new HTMLDocument("Hello,World!", ".");
// Initialize ImageSaveOptions with desired format
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Png);
// Convert HTML to PNG image
Converter.convertHTML(document, options, "output.png");
// Output: PNG image file created at "output.png"
// For JPEG format:
ImageSaveOptions jpegOptions = new ImageSaveOptions(ImageFormat.Jpeg);
Converter.convertHTML(document, jpegOptions, "output.jpg");
```
--------------------------------
### Convert SVG to PDF using Java
Source: https://context7.com/aspose-html/aspose.html-for-java/llms.txt
Demonstrates rendering Scalable Vector Graphics (SVG) documents to PDF format using `Converter.convertSVG()`. This method ensures full preservation of vector graphics.
```java
import com.aspose.html.converters.Converter;
import com.aspose.html.dom.svg.SVGDocument;
import com.aspose.html.saving.PdfSaveOptions;
// Prepare SVG code
String svgCode = "\n";
// Save SVG to file
try (java.io.FileWriter fileWriter = new java.io.FileWriter("document.svg")) {
fileWriter.write(svgCode);
}
// Initialize an SVG document
SVGDocument document = new SVGDocument("document.svg");
// Convert SVG to PDF
Converter.convertSVG(document, new PdfSaveOptions(), "output.pdf");
// Output: PDF file created at "output.pdf"
```
--------------------------------
### Convert SVG to PDF
Source: https://context7.com/aspose-html/aspose.html-for-java/llms.txt
Renders Scalable Vector Graphics (SVG) documents to PDF format with full support for vector graphics preservation.
```APIDOC
## Convert SVG to PDF
### Description
Renders Scalable Vector Graphics (SVG) documents to PDF format with full support for vector graphics preservation.
### Method
POST
### Endpoint
/convert/svg-to-pdf
### Parameters
#### Query Parameters
- **outputPath** (string) - Required - The path where the output PDF file will be saved.
#### Request Body
- **svgDocument** (object) - Required - The SVG document object. This could be represented by its source SVG code or a file path.
- **source** (string) - The SVG code or file path.
- **options** (object) - Optional - PDF save options. (Specific fields depend on `PdfSaveOptions`)
### Request Example
```json
{
"svgDocument": {
"source": ""
},
"outputPath": "output.pdf",
"options": {}
}
```
### Response
#### Success Response (200)
- **message** (string) - A confirmation message indicating the successful conversion.
#### Response Example
```json
{
"message": "PDF file created at output.pdf"
}
```
```
--------------------------------
### Merge Multiple HTML Documents to PDF
Source: https://context7.com/aspose-html/aspose.html-for-java/llms.txt
Merges multiple HTML documents into a single PDF file for batch processing scenarios.
```APIDOC
## Merge Multiple HTML Documents to PDF
### Description
Merges multiple HTML documents into a single PDF file for batch processing scenarios.
### Method
POST
### Endpoint
/merge/html-to-pdf
### Parameters
#### Query Parameters
- **outputPath** (string) - Required - The path where the output merged PDF file will be saved.
#### Request Body
- **htmlDocuments** (array) - Required - An array of HTML documents to merge.
- Each element in the array should represent an HTML document, potentially with its source HTML content and base URI.
- **content** (string) - The HTML content.
- **baseUri** (string) - The base URI for the HTML content.
### Request Example
```json
{
"outputPath": "merged-output.pdf",
"htmlDocuments": [
{
"content": "Hello, World!!",
"baseUri": "."
},
{
"content": "Hello, World!!",
"baseUri": "."
},
{
"content": "Hello, World!!",
"baseUri": "."
}
]
}
```
### Response
#### Success Response (200)
- **message** (string) - A confirmation message indicating the successful merging and PDF creation.
#### Response Example
```json
{
"message": "Single PDF with all three documents merged"
}
```
```
--------------------------------
### Basic HTML Structure with Advanced CSS
Source: https://github.com/aspose-html/aspose.html-for-java/blob/master/Aspose.HTML-for-Java.WebService-on-Docker/assets/index.html
This snippet demonstrates a basic HTML structure with embedded CSS. It includes advanced CSS properties like background images and positioning, intended for introductory purposes. The CSS targets the body and a specific div element.
```css
body { margin-left: 200px; background: #5d9ab2 url("img_tree.png") no-repeat top left; } .center_div { border: 1px solid gray; margin-left: auto; margin-right: auto; width: 90%; background-color: #d0f0f6; text-align: left; padding: 8px; }
```
--------------------------------
### Convert HTML to Markdown using Aspose.HTML for Java
Source: https://context7.com/aspose-html/aspose.html-for-java/llms.txt
Demonstrates converting HTML content to Markdown format with Aspose.HTML for Java. The `Converter.convertHTML()` method is used in conjunction with `MarkdownSaveOptions`, allowing for the configuration of specific Markdown features like links and automatic paragraph conversion. The example includes preparing HTML content and saving it to a Markdown file.
```java
import com.aspose.html.converters.Converter;
import com.aspose.html.saving.MarkdownFeatures;
import com.aspose.html.saving.MarkdownSaveOptions;
// Prepare HTML content
String htmlCode = "
Header 1
" +
"
Header 2
" +
"
Hello, World!!
" +
"aspose";
// Save HTML to file
try (java.io.FileWriter fileWriter = new java.io.FileWriter("input.html")) {
fileWriter.write(htmlCode);
}
// Configure Markdown save options (only convert links and paragraphs)
MarkdownSaveOptions options = new MarkdownSaveOptions();
options.setFeatures(MarkdownFeatures.Link | MarkdownFeatures.AutomaticParagraph);
// Convert HTML to Markdown
Converter.convertHTML("input.html", options, "output.md");
// Output: Markdown file with converted links and paragraphs
```
--------------------------------
### Merge HTML Documents to PDF using Java
Source: https://context7.com/aspose-html/aspose.html-for-java/llms.txt
Explains how to merge multiple HTML documents into a single PDF file using the `HtmlRenderer` class. This is useful for batch processing and consolidating web content.
```java
import com.aspose.html.HTMLDocument;
import com.aspose.html.rendering.HtmlRenderer;
import com.aspose.html.rendering.pdf.PdfDevice;
// Create multiple HTML documents
HTMLDocument document1 = new HTMLDocument("Hello, World!!", ".");
HTMLDocument document2 = new HTMLDocument("Hello, World!!", ".");
HTMLDocument document3 = new HTMLDocument("Hello, World!!", ".");
// Create HTML Renderer instance
HtmlRenderer renderer = new HtmlRenderer();
// Create PDF device for output
PdfDevice device = new PdfDevice("merged-output.pdf");
// Merge all HTML documents to single PDF
renderer.render(device, new HTMLDocument[]{document1, document2, document3});
// Output: Single PDF with all three documents merged
```
--------------------------------
### Convert HTML to PDF using Aspose.HTML for Java
Source: https://context7.com/aspose-html/aspose.html-for-java/llms.txt
Demonstrates converting an HTML document to a PDF file using Aspose.HTML for Java. It allows customization of PDF save options such as resolution, page size, margins, and background color. The `Converter.convertHTML()` method is used for the conversion.
```java
import com.aspose.html.HTMLDocument;
import com.aspose.html.converters.Converter;
import com.aspose.html.drawing.*;
import com.aspose.html.saving.PdfSaveOptions;
// Initialize an HTML document from a file or HTML string
HTMLDocument document = new HTMLDocument("
Hello, World!
", ".");
// Configure PDF save options with custom page settings
PdfSaveOptions options = new PdfSaveOptions();
options.setHorizontalResolution(new Resolution(200, UnitType.AUTO));
options.setVerticalResolution(new Resolution(200, UnitType.AUTO));
options.setBackgroundColor(Color.getAliceBlue());
options.setJpegQuality(100);
options.getPageSetup().setAnyPage(new Page(new Size(500, 300), new Margin(20, 10, 10, 10)));
// Convert HTML to PDF
Converter.convertHTML(document, options, "output.pdf");
// Output: PDF file created at "output.pdf"
```
--------------------------------
### Download and Save Web Pages with Aspose.HTML for Java
Source: https://context7.com/aspose-html/aspose.html-for-java/llms.txt
Loads a web page from a URL and saves it locally using HTMLDocument. Configurable options allow for embedding JavaScript and restricting resource handling to the same host. Requires the Aspose.HTML for Java library.
```java
import com.aspose.html.HTMLDocument;
import com.aspose.html.saving.HTMLSaveOptions;
import com.aspose.html.saving.ResourceHandling;
import com.aspose.html.saving.UrlRestriction;
// Initialize HTML document from URL
HTMLDocument document = new HTMLDocument("https://docs.aspose.com/html/net/message-handlers/");
// Configure save options with embedded JavaScript
HTMLSaveOptions options = new HTMLSaveOptions();
options.getResourceHandlingOptions().setJavaScript(ResourceHandling.Embed);
options.getResourceHandlingOptions().setMaxHandlingDepth(1);
options.getResourceHandlingOptions().setPageUrlRestriction(UrlRestriction.SameHost);
// Save the web page locally
document.save("downloaded-page.html", options);
// Output: Complete web page saved with embedded resources
```
--------------------------------
### Populate HTML Templates with JSON Data using Aspose.HTML for Java
Source: https://context7.com/aspose-html/aspose.html-for-java/llms.txt
This snippet demonstrates how to dynamically generate HTML content by populating an HTML template with data from a JSON source using the `Converter.convertTemplate()` method. It requires the Aspose.HTML library and involves preparing both the JSON data and the HTML template with Mustache-style placeholders.
```java
import com.aspose.html.converters.Converter;
import com.aspose.html.converters.TemplateData;
import com.aspose.html.loading.TemplateLoadOptions;
// Prepare JSON data source
String jsonData = "{\n" +
" 'FirstName': 'John',\n" +
" 'LastName': 'Smith',\n" +
" 'Address': {\n" +
" 'City': 'Dallas',\n" +
" 'Street': 'Austin rd.',\n" +
" 'Number': '200'\n" +
" }\n" +
"}";
try (java.io.FileWriter fileWriter = new java.io.FileWriter("data-source.json")) {
fileWriter.write(jsonData);
}
// Prepare HTML template with placeholders
String template = "
\n";
try (java.io.FileWriter fileWriter = new java.io.FileWriter("template.html")) {
fileWriter.write(template);
}
// Convert template to HTML with data
Converter.convertTemplate(
"template.html",
new TemplateData("data-source.json"),
new TemplateLoadOptions(),
"output.html"
);
// Output: HTML file with "John Smith" and "Austin rd. 200, Dallas"
```
--------------------------------
### Navigate HTML DOM using Aspose.HTML for Java
Source: https://github.com/aspose-html/aspose.html-for-java/blob/master/docs/basic-usage.md
Demonstrates navigating the Document Object Model (DOM) of an HTML document. It parses an HTML string, accesses elements, and retrieves their text content. Requires Aspose.HTML for Java.
```java
import com.aspose.html.HTMLDocument;
import com.aspose.html.dom.Element;
String html_code = "Hello,World!";
HTMLDocument document = new HTMLDocument(html_code, ".");
Element element = document.getBody().getFirstElementChild();
System.out.println(element.getTextContent());
// @output: Hello,
element = element.getNextElementSibling();
System.out.println(element.getTextContent());
// @output: World!
```
--------------------------------
### Convert HTML to PDF using Aspose.HTML for Java
Source: https://github.com/aspose-html/aspose.html-for-java/blob/master/docs/basic-usage.md
Converts an HTML document to a PDF file. Requires the Aspose.HTML for Java library. Takes an HTML document and save options as input, producing a PDF file.
```java
import com.aspose.html.HTMLDocument;
import com.aspose.html.saving.PdfSaveOptions;
import com.aspose.html.converters.Converter;
HTMLDocument document = new HTMLDocument("document.html");
PDFSaveOptions options = new PDFSaveOptions();
Converter.convertHTML(document, options, "output.pdf");
```
--------------------------------
### Convert HTML to DOCX using Aspose.HTML for Java
Source: https://context7.com/aspose-html/aspose.html-for-java/llms.txt
This snippet illustrates the conversion of an HTML document to the Microsoft Word DOCX format using Aspose.HTML for Java. The `Converter.convertHTML()` method is employed with `DocSaveOptions` to facilitate the conversion, making the HTML content editable in Word.
```java
import com.aspose.html.HTMLDocument;
import com.aspose.html.converters.Converter;
import com.aspose.html.saving.DocSaveOptions;
// Initialize an HTML document from a file
HTMLDocument document = new HTMLDocument("input.html");
// Initialize DocSaveOptions
DocSaveOptions options = new DocSaveOptions();
// Convert HTML to DOCX
Converter.convertHTML(document, options, "output.docx");
// Output: DOCX file created at "output.docx"
```
--------------------------------
### Query HTML Elements with CSS Selectors using Aspose.HTML for Java
Source: https://context7.com/aspose-html/aspose.html-for-java/llms.txt
This code snippet illustrates how to select specific HTML elements from a document using CSS selector syntax via the `querySelectorAll()` method. It iterates through the selected elements and prints their inner HTML content, demonstrating targeted data extraction with Aspose.HTML.
```java
import com.aspose.html.HTMLDocument;
import com.aspose.html.HTMLElement;
import com.aspose.html.collections.NodeList;
// Prepare HTML with class attributes
String htmlCode = "
\n" +
"
Hello,
\n" +
"
\n" +
"
\n" +
" World!\n" +
"
\n";
// Initialize document
HTMLDocument document = new HTMLDocument(htmlCode, ".");
// Select all span elements inside elements with class 'happy'
NodeList elements = document.querySelectorAll(".happy span");
// Iterate and print content
elements.forEach(element -> {
System.out.println(((HTMLElement) element).getInnerHTML());
});
// Output: Hello,
// Output: World!
```
--------------------------------
### Convert HTML to Image using Aspose.HTML for Java
Source: https://github.com/aspose-html/aspose.html-for-java/blob/master/docs/basic-usage.md
Renders an HTML document into an image file (e.g., JPEG). Requires the Aspose.HTML for Java library. Accepts an HTML document and image save options, outputting an image file.
```java
import com.aspose.html.HTMLDocument;
import com.aspose.html.saving.ImageSaveOptions;
import com.aspose.html.saving.SaveFormat;
import com.aspose.html.converters.Converter;
HTMLDocument document = new HTMLDocument("document.html");
ImageSaveOptions options = new ImageSaveOptions(SaveFormat.Jpeg);
Converter.convertHTML(document, options, "output.jpg");
```
--------------------------------
### Draw Text on HTML Canvas using Java
Source: https://github.com/aspose-html/aspose.html-for-java/blob/master/Aspose.HTML-for-Java.Example/src/main/resources/canvas.html
This snippet illustrates drawing "Hello, World!" text onto an HTML canvas element. It requires an HTML file with a canvas element and the Aspose.HTML for Java library. The output is the modified HTML content with the drawn text.
```java
var c = document.getElementById("myCanvas");
var context = c.getContext("2d");
context.font = "30px Arial";
context.fillStyle = "red";
context.fillText("Hello, World!", 15, 60);
```
--------------------------------
### Convert HTML to PDF with Single Line of Java Code
Source: https://github.com/aspose-html/aspose.html-for-java/blob/master/README.md
This Java code snippet demonstrates a concise way to convert an HTML string to a PDF document using the Aspose.HTML for Java library. It utilizes the Converter class and specifies output options.
```java
import com.aspose.html.converters.Converter;
import com.aspose.html.saving.PdfSaveOptions;
// Invoke the convertHTML() method to convert the HTML to PDF
Converter.convertHTML("
Convert HTML to PDF!
", ".", new PdfSaveOptions(), "convert-with-single-line.pdf");
```
--------------------------------
### Fill and Submit HTML Forms with Aspose.HTML for Java
Source: https://context7.com/aspose-html/aspose.html-for-java/llms.txt
Programmatically fills and submits HTML forms using FormEditor and FormSubmitter. Supports individual field filling, bulk updates via a map, and processing server responses. Requires Aspose.HTML for Java. Input is an HTML document with forms.
```java
import com.aspose.html.HTMLDocument;
import com.aspose.html.forms.*;
// Load HTML document with form
HTMLDocument document = new HTMLDocument("https://httpbin.org/forms/post");
// Create FormEditor instance
FormEditor editor = FormEditor.create(document, 0);
// Fill form fields individually
InputElement custname = editor.addInput("custname");
custname.setValue("John Doe");
// Fill text area
TextAreaElement comments = editor.getElement(TextAreaElement.class, "comments");
comments.setValue("MORE CHEESE PLEASE!");
// Bulk fill using map
java.util.Map formData = new java.util.HashMap<>();
formData.put("custemail", "john.doe@gmail.com");
formData.put("custtel", "+1202-555-0290");
// Submit form
FormSubmitter submitter = new FormSubmitter(editor);
SubmissionResult result = submitter.submit();
// Check submission result
if (result.isSuccess()) {
if (result.getResponseMessage().getHeaders().getContentType().getMediaType().equals("application/json")) {
System.out.println(result.getContent().readAsString());
}
}
// Output: Form submission response from server
```
--------------------------------
### Load and Convert MHTML to PDF using Aspose.HTML for Java
Source: https://github.com/aspose-html/aspose.html-for-java/blob/master/docs/basic-usage.md
Converts an MHTML file to a PDF document. This function utilizes the Aspose.HTML for Java library. It takes an input stream of an MHTML file and save options, producing a PDF output.
```java
import com.aspose.html.converters.Converter;
import com.aspose.html.saving.PdfSaveOptions;
java.io.FileInputStream fileInputStream = new java.io.FileInputStream($i("sample.mht"));
PdfSaveOptions options = new PdfSaveOptions();
Converter.convertMHTML(fileInputStream, options, $o("sample-output.pdf"));
```
--------------------------------
### Create HTML Document using Aspose.HTML for Java
Source: https://github.com/aspose-html/aspose.html-for-java/blob/master/docs/basic-usage.md
Creates a new HTML document in memory and adds text content to its body. This requires the Aspose.HTML for Java library. The function creates an HTMLDocument object and appends text, saving the result to a file.
```java
import com.aspose.html.HTMLDocument;
import com.aspose.html.dom.Text;
HTMLDocument document = new HTMLDocument();
Text text = document.createTextNode("Hello, World!");
document.getBody().appendChild(text);
document.save($o("create-new-document.html"));
```
--------------------------------
### Validate Web Accessibility (WCAG Compliance) with Aspose.HTML for Java
Source: https://context7.com/aspose-html/aspose.html-for-java/llms.txt
Checks HTML documents for WCAG compliance using AccessibilityValidator and generates detailed reports. Supports validation against all WCAG rules and exporting results to JSON or XML. Requires Aspose.HTML for Java. Input is an HTML document.
```java
import com.aspose.html.HTMLDocument;
import com.aspose.html.accessibility.*;
import com.aspose.html.accessibility.results.RuleValidationResult;
import com.aspose.html.accessibility.results.ValidationResult;
import com.aspose.html.accessibility.saving.ValidationResultSaveFormat;
// Initialize WebAccessibility container
WebAccessibility webAccessibility = new WebAccessibility();
// Create validator for all WCAG rules
AccessibilityValidator validator = webAccessibility.createValidator(ValidationBuilder.getAll());
// Load HTML document
HTMLDocument document = new HTMLDocument("input.html");
// Validate document
ValidationResult validationResult = validator.validate(document);
// Process validation results
if (!validationResult.getSuccess()) {
for (RuleValidationResult detail : validationResult.getDetails()) {
System.out.println(String.format("%s: %s = %s",
detail.getRule().getCode(),
detail.getRule().getDescription(),
detail.getSuccess()
));
}
}
// Export results to JSON or XML
java.io.StringWriter sw = new java.io.StringWriter();
validationResult.saveTo(sw, ValidationResultSaveFormat.JSON);
System.out.println(sw.toString());
// Output: Detailed accessibility validation report
```
--------------------------------
### CSS Styling for Drawing Shapes
Source: https://github.com/aspose-html/aspose.html-for-java/blob/master/Aspose.HTML-for-Java.Example/src/main/resources/drawing.html
This CSS code defines styles for various shapes including squares and circles. It specifies properties like margin, height, width, background-color, and border-radius to create visual elements. These styles can be applied to HTML elements to render the desired shapes.
```css
.square1 { margin-left: 50px; margin-top: -170px; height: 80px; width: 80px; background-color: #c4456d; border-radius: 50%; / / border: 12 px solid #c4456d; }
.square2 { margin-left: 90px; margin-top: 0px; height: 60px; width: 60px; background-color: #fd6696; border-radius: 50%; }
.square3 { margin-left: 155px; margin-top: -20px; height: 40px; width: 40px; background-color: #ffb1ca; border-radius: 50%; }
.circle { margin-left: 440px; margin-top: -115px; height: 30px; width: 30px; background-color: #6dc6bf; border-radius: 50%; }
.frame { margin-top: 100px; margin-left: 150px; font-size: 4em; font-family: Verdana; color: #538caa; }
```
--------------------------------
### Define CSS for HTML Elements in Java
Source: https://github.com/aspose-html/aspose.html-for-java/blob/master/Aspose.HTML-for-Java.Example/src/main/resources/check-color.html
This snippet defines CSS rules for HTML elements using Java. It sets properties like font family, text alignment, padding, border-radius, width, and margin for a 'div' element. It also defines classes for 'bad' and 'good' contrast with specific background colors and font sizes.
```css
div { font-family: sans-serif; text-align: center; font-weight: bold; text-align: center; padding: 10px; border-radius: 15px; width: 300px; margin: auto; }
.bad { background-color: #045DE2; font-size: 14px; }
.good { background-color: #f0f6ff; }
```
--------------------------------
### Run Microbenchmark using Gradle
Source: https://github.com/aspose-html/aspose.html-for-java/blob/master/Aspose.HTML-for-Java.Microbenchmark/README.md
This command executes the microbenchmark tests for the Aspose.HTML for Java library using Gradle. The results are generated in the `build/jmh-reports` directory.
```bash
./gradlew jmh
```
--------------------------------
### Dynamically Show/Hide PDF/XPS Options with JavaScript
Source: https://github.com/aspose-html/aspose.html-for-java/blob/master/Aspose.HTML-for-Java.WebService-on-Docker/src/main/resources/templates/convert.html
This JavaScript code snippet listens for changes in the 'outputFormat' dropdown. It toggles the visibility of elements with the class 'pdf-xps-options' based on whether the selected output format is 'PNG' or any other format (PDF/XPS). This is useful for showing or hiding format-specific settings.
```javascript
document.getElementById('outputFormat').addEventListener('change', function() {
var pdfXpsOptions = document.querySelector('.pdf-xps-options');
if (this.value === 'PNG') {
pdfXpsOptions.style.display = 'none';
} else {
pdfXpsOptions.style.display = 'block';
}
});
```
--------------------------------
### Render Text in Black Color using Aspose.HTML for Java
Source: https://github.com/aspose-html/aspose.html-for-java/blob/master/Aspose.HTML-for-Java.Example/src/main/resources/FirstFile.html
This snippet demonstrates rendering text in black using Aspose.HTML for Java. It implies the use of default or explicitly set black color in CSS or HTML. The Aspose.HTML library is the primary dependency.
```java
/* Java code to render HTML with black text using Aspose.HTML would go here */
// Example:
// Document document = new Document();
// document.setHtml("
This text will be black.
"); // Default color is usually black
// Renderer renderer = new Renderer();
// renderer.renderDocument(document, "output_black.png");
```
--------------------------------
### Render Text in Red Color using Aspose.HTML for Java
Source: https://github.com/aspose-html/aspose.html-for-java/blob/master/Aspose.HTML-for-Java.Example/src/main/resources/FirstFile.html
This snippet explains how to render text in red using Aspose.HTML for Java. It involves specifying the color red via CSS or HTML attributes. The Aspose.HTML library is the necessary dependency.
```java
/* Java code to render HTML with red text using Aspose.HTML would go here */
// Example:
// Document document = new Document();
// document.addStyleSheet("p { color: red; }");
// document.setHtml("
This text will be red.
");
// Renderer renderer = new Renderer();
// renderer.renderDocument(document, "output_red.png");
```
--------------------------------
### Style Photo and Ad Elements in CSS
Source: https://github.com/aspose-html/aspose.html-for-java/blob/master/Aspose.HTML-for-Java.Example/src/main/resources/xpath-image.htm
This CSS snippet sets the width of photo and ad elements to 100%, ensuring they occupy the full available width of their containers. This is a common practice for responsive image and advertisement display.
```css
.photo {
width: 100%;
}
.ad {
width: 100%;
}
```
--------------------------------
### Render Text in Green Color using Aspose.HTML for Java
Source: https://github.com/aspose-html/aspose.html-for-java/blob/master/Aspose.HTML-for-Java.Example/src/main/resources/FirstFile.html
This snippet shows how to render text in green using Aspose.HTML for Java. It leverages CSS to define the text color. No external dependencies are required beyond the Aspose.HTML library.
```css
.st { color: green; }
```
```java
/* Java code to render HTML with the above CSS would go here */
// Example:
// Document document = new Document();
// document.addStyleSheet(".st { color: green; }");
// document.setHtml("
This text will be green.
");
// Renderer renderer = new Renderer();
// renderer.renderDocument(document, "output.png");
```
--------------------------------
### Render Text in Blue Color using Aspose.HTML for Java
Source: https://github.com/aspose-html/aspose.html-for-java/blob/master/Aspose.HTML-for-Java.Example/src/main/resources/FirstFile.html
This snippet illustrates rendering text in blue with Aspose.HTML for Java. It requires defining the color blue in the associated CSS or HTML. The Aspose.HTML library is the core requirement.
```java
/* Java code to render HTML with blue text using Aspose.HTML would go here */
// Example:
// Document document = new Document();
// document.addStyleSheet("p { color: blue; }");
// document.setHtml("
This text will be blue.
");
// Renderer renderer = new Renderer();
// renderer.renderDocument(document, "output_blue.png");
```
--------------------------------
### Apply Flexbox Styling to Header and Footer in CSS
Source: https://github.com/aspose-html/aspose.html-for-java/blob/master/Aspose.HTML-for-Java.Example/src/main/resources/xpath-image.htm
This CSS snippet applies flexbox properties to header and footer elements to center their content both horizontally and vertically. It's useful for creating consistent navigation or branding bars.
```css
header, footer {
display: flex;
justify-content: center;
align-items: center;
}
```
--------------------------------
### Style Row Elements and Links in CSS
Source: https://github.com/aspose-html/aspose.html-for-java/blob/master/Aspose.HTML-for-Java.Example/src/main/resources/xpath-image.htm
This CSS defines styles for row elements and links within a row. It uses flexbox to manage the layout of links, ensuring they distribute evenly and the last link has no right margin. This is effective for creating responsive grids or navigation lists.
```css
.row > a {
margin-right: 10px;
flex-basis: 20%;
}
.row > a:last-child {
margin-right: 0px;
}
.row, .ad-row {
display: flex;
width: 100%;
}
.ad-row {
justify-content: center;
align-items: center;
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.