### Configure Aspose Repository for Gradle Source: https://docs.aspose.com/html/java/getting-started/installation This snippet demonstrates how to configure the Aspose Repository in your Gradle build.gradle script. This ensures that Gradle can access and download Aspose libraries. ```groovy repositories { maven { url = uri('https://repository.aspose.com/repo/') } } ``` -------------------------------- ### Get Accessibility Guideline by Code in Java Source: https://docs.aspose.com/html/java/web-accessibility-rules This Java code snippet illustrates how to obtain an accessibility guideline by its code within a specific principle using Aspose.HTML for Java. It initializes WebAccessibility, retrieves a Principle object by its code, and then uses getGuideline() on the principle to fetch the desired Guideline. The example prints the code, description, and the object itself for guideline '1.1'. ```java import com.aspose.html.accessibility.WebAccessibility; import com.aspose.html.accessibility.rules.Guideline; import com.aspose.html.accessibility.rules.Principle; public class Example_GetAccessibilityGuideline { public static void main(String[] args) { // Initialize a webAccessibility container WebAccessibility webAccessibility = new WebAccessibility(); // Get the principle by code Principle principle = webAccessibility.getRules().getPrinciple("1"); // Get guideline 1.1 Guideline guideline = principle.getGuideline("1.1"); if (guideline != null) { System.out.println(String.format("%s: %s, %s", guideline.getCode(), guideline.getDescription(), guideline )); // @output: 1.1:Text Alternatives } } } ``` -------------------------------- ### Dockerfile for Aspose.HTML for Java Source: https://docs.aspose.com/html/java/getting-started/using-library-in-docker A sample Dockerfile to set up an environment for running Aspose.HTML for Java. It installs necessary dependencies like Microsoft True Type Core Fonts and prepares the Java runtime. ```Dockerfile # Use an official OpenJDK runtime as a parent image FROM openjdk:11-jdk-slim # Set the working directory in the container WORKDIR /app # Install Microsoft True Type Core Fonts RUN apt-get update && apt-get install -y ttf-mscorefonts-installer && apt-get clean # Add your Aspose.HTML for Java application # COPY your-application.jar . # Command to run your application # CMD ["java", "-jar", "your-application.jar"] # This is a placeholder Dockerfile. Replace comments with your actual application setup. ``` -------------------------------- ### Configure Aspose Repository for Maven Source: https://docs.aspose.com/html/java/getting-started/installation This snippet shows how to add the Aspose Repository configuration to your Maven pom.xml file. This allows Maven to download the Aspose.HTML for Java library from Aspose's official repository. ```xml snapshots repo http://repository.aspose.com/repo/ ``` -------------------------------- ### Load Aspose.HTML for Java License from Stream Source: https://docs.aspose.com/html/java/getting-started/licensing This example demonstrates how to apply the Aspose.HTML for Java license from an input stream. This method is useful when the license file is not directly accessible via a file path. ```java com.aspose.html.License license = new com.aspose.html.License(); license.setLicense(new java.io.FileInputStream("Aspose.HTML.lic")); ``` -------------------------------- ### Install Microsoft True Type Core Fonts in Dockerfile Source: https://docs.aspose.com/html/java/getting-started/using-library-in-docker These lines within a Dockerfile install Microsoft True Type Core Fonts and configure font handling. This is crucial for applications that rely on specific fonts for rendering, such as Aspose.HTML. ```dockerfile RUN yum -y --skip-broken install -y ttf-mscorefonts-installer fontconfig RUN fc-list RUN ls ``` -------------------------------- ### Add Aspose.HTML for Java Dependency for Gradle Source: https://docs.aspose.com/html/java/getting-started/installation This snippet shows the Gradle syntax for adding the Aspose.HTML for Java API dependency to your build.gradle script. This includes specifying the group, name, version, and classifier. ```groovy compile(group: 'com.aspose', name: 'aspose-html', version: '20.9.1', classifier: 'jdk16') ``` -------------------------------- ### Java Example: Save File from URL using Aspose.HTML Source: https://docs.aspose.com/html/java/save-file-from-url This Java code snippet demonstrates how to save a file from a given URL to the local file system using the Aspose.HTML for Java library. It requires the Aspose.HTML for Java dependency. The code takes a URL as input and saves the content to a specified output file path. ```java import com.aspose.html.converters.Converter; import java.io.InputStream; public class SaveFileFromUrl { public static void main(String[] args) { // The URL of the file to download String fileUrl = "https://www.example.com/path/to/your/file.pdf"; // The path where the file will be saved locally String outputFilePath = "output/downloaded_file.pdf"; try { // Create an instance of the Converter Converter converter = new Converter(); // Download the file from the URL and save it converter.convert(fileUrl, outputFilePath, null); System.out.println("File saved successfully to: " + outputFilePath); } catch (Exception e) { System.err.println("An error occurred: " + e.getMessage()); e.printStackTrace(); } } } ``` -------------------------------- ### Dockerfile for Aspose.HTML Java Application Source: https://docs.aspose.com/html/java/getting-started/using-library-in-docker This Dockerfile sets up an environment for running an Aspose.HTML for Java application. It installs Java, copies the application JAR, and configures necessary directories and permissions. It's designed for Red Hat Universal Base Image 8. ```dockerfile FROM registry.access.redhat.com/ubi8/ubi:8.9-1028 ENV FID_HOME=/opt/icgccbfid RUN mkdir -p $FID_HOME ENV MEDIA=/media/sf_redhat/ RUN mkdir -p $MEDIA RUN chmod -R 775 $MEDIA COPY ../../assets $MEDIA ENV SERVICE_HOME=$FID_HOME/test-redhat RUN mkdir -p $SERVICE_HOME RUN chmod -R 775 $SERVICE_HOME COPY target/testing-aspose-redhat-jdk-1.0.0.jar $SERVICE_HOME/app.jar ENV APP_PATH=${SERVICE_HOME}/app.jar RUN yum -y --skip-broken install wget RUN cd ~ RUN yum -y install java-1.8.0-openjdk RUN ls # 3. Install Microsoft True Type Core Fonts RUN yum -y --skip-broken install -y ttf-mscorefonts-installer fontconfig RUN fc-list RUN ls RUN yum -y --skip-broken install rpm RUN ls ``` -------------------------------- ### Run Docker Container Command Source: https://docs.aspose.com/html/java/getting-started/using-library-in-docker This command starts a Docker container from a previously built image. It maps host ports to container ports, allowing external access to the application running inside the container, and automatically removes the container when it exits. ```bash docker run -p8080:9999 -p2222:22 --rm my-image ``` -------------------------------- ### Get Accessibility Principle by Code in Java Source: https://docs.aspose.com/html/java/web-accessibility-rules This Java code shows how to retrieve a specific accessibility principle by its code using Aspose.HTML for Java. It initializes the WebAccessibility container, uses getPrinciple() with a given code to fetch the Principle object, and then prints its code and description. The example outputs the code and description for the principle with code '1'. ```java import com.aspose.html.accessibility.WebAccessibility; import com.aspose.html.accessibility.rules.Principle; public class Example_GetAccessibilityPrincipleByCode { public static void main(String[] args) { // Initialize a webAccessibility container WebAccessibility webAccessibility = new WebAccessibility(); // Get the principle by code Principle rule = webAccessibility.getRules().getPrinciple("1"); // Get code and description of principle System.out.println(String.format("%s: %s", rule.getCode(), rule.getDescription() )); // @output: 1:Perceivable } } ``` -------------------------------- ### Add Aspose.HTML for Java Dependency for Maven Source: https://docs.aspose.com/html/java/getting-started/installation This snippet illustrates how to declare the Aspose.HTML for Java API dependency in your Maven pom.xml file. Specify the group ID, artifact ID, version, and classifier to include the library. ```xml com.aspose aspose-html 20.9.1 jdk16 ``` -------------------------------- ### Validate HTML Accessibility and Get Failed Rule Results in Java Source: https://docs.aspose.com/html/java/web-accessibility-validation-results This comprehensive Java example demonstrates validating HTML accessibility using Aspose.HTML. It initializes the WebAccessibility, creates a validator, loads an HTML document, and then iterates through the validation results. Only failed rules are printed, along with their descriptions and the results of individual techniques used to satisfy the success criteria. ```java 1// Validate HTML accessibility using Java and get detailed failed rule results 2 3// Initialize a webAccessibility container 4WebAccessibility webAccessibility = new WebAccessibility(); 5 6// Create an accessibility validator with static instance for all rules 7// from repository that match the builder settings 8AccessibilityValidator validator = webAccessibility.createValidator(ValidationBuilder.getAll()); 9 10String documentPath = $i("input.html"); 11 12// Initialize an object of the HTMLDocument class 13final HTMLDocument document = new HTMLDocument(documentPath); 14ValidationResult validationResult = validator.validate(document); 15 16// Take a list of rules results 17for (RuleValidationResult ruleResult : validationResult.getDetails()) { 18 // List only unsuccessful rule 19 if (!ruleResult.getSuccess()) { 20 // Print the code and description of the rule 21 System.out.println(String.format("%s: %s", 22 ruleResult.getRule().getCode(), 23 ruleResult.getRule().getDescription() 24 )); 25 26 // Print the results of all methods 27 for (ITechniqueResult ruleDetail : ruleResult.getResults()) { 28 // Print the code and description of the criterions 29 StringBuilder str = new StringBuilder(String.format("\n{0}: {1} - {2}", 30 ruleDetail.getRule().getCode(), 31 ruleDetail.getSuccess(), 32 ruleDetail.getRule().getDescription() 33 )); 34 System.out.println(str); 35 } 36 } 37} ``` -------------------------------- ### Convert EPUB to PNG (Default Settings) Source: https://docs.aspose.com/html/java/convert-epub-to-png This section details the step-by-step process and provides a Java code example for converting an EPUB file to a PNG image using default settings with Aspose.HTML for Java. ```APIDOC ## Convert EPUB to PNG (Default Settings) ### Description This endpoint demonstrates the basic conversion of an EPUB file to a PNG image using default settings provided by the Aspose.HTML for Java library. ### Method N/A (This is a code example, not a direct API endpoint) ### Endpoint N/A ### Parameters N/A ### Request Example ```java // Convert EPUB to PNG in Java // Open an existing EPUB file for reading java.io.FileInputStream fileInputStream = new java.io.FileInputStream($i("input.epub")); // Create an instance of the ImageSaveOptions class ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Png); // Call the ҁonvertEPUB() method to convert EPUB to PNG Converter.convertEPUB(fileInputStream, options, $o("input-output.png")); ``` ### Response #### Success Response (File Output) - A PNG image file named 'input-output.png' will be generated at the specified save path. #### Response Example N/A (File output) ``` -------------------------------- ### Get Guideline by Code within Principle Source: https://docs.aspose.com/html/java/web-accessibility-rules This endpoint allows you to retrieve a specific Guideline object using its code, within a given Principle. ```APIDOC ## GET /websites/aspose_html_java/principles/{principleCode}/guidelines/{guidelineCode} ### Description Get a Guideline by its code from a specific Principle. Guidelines are the next level after principles, outlining frameworks and general goals. ### Method GET ### Endpoint /websites/aspose_html_java/principles/{principleCode}/guidelines/{guidelineCode} ### Path Parameters - **principleCode** (String) - Required - The code of the parent Principle (e.g., "1"). - **guidelineCode** (String) - Required - The code of the Guideline (e.g., "1.1"). ### Request Example ```java WebAccessibility webAccessibility = new WebAccessibility(); Principle principle = webAccessibility.getRules().getPrinciple("1"); if (principle != null) { Guideline guideline = principle.getGuideline("1.1"); if (guideline != null) { System.out.println(String.format("%s: %s", guideline.getCode(), guideline.getDescription())); } } ``` ### Response #### Success Response (200) - **Guideline** (object) - The Guideline object matching the provided codes. - **code** (String) - The code of the Guideline. - **description** (String) - The description of the Guideline. - **criteria** (List) - A list of associated Criteria. #### Response Example ```json { "code": "1.1", "description": "Text Alternatives", "criteria": [ // ... criteria details ... ] } ``` ``` -------------------------------- ### Example Output for Color Contrast Accessibility Violation Source: https://docs.aspose.com/html/java/check-color-contract This example shows the expected output when the color contrast in an HTML document fails to meet the specified accessibility criterion (e.g., WCAG 1.4.3). It highlights the rule code, the error message explaining the violation, and the specific HTML snippet that caused the issue. ```text Error in rule G18 : Make sure the contrast ratio between the text (and images of text) and the background behind the text is at least 4.5:1 for text less than 18 points if it is not in bold, and less than 14 points if it is in bold. CSS Rule:
Text with bad contrast
``` -------------------------------- ### Navigate and Handle Async Document Load with ReadyStateChange (Java) Source: https://docs.aspose.com/html/java/create-a-document This Java example demonstrates asynchronous navigation to a URL and handling the document loading process using the `OnReadyStateChange` event. It checks if the document's ready state is 'complete' and prints the OuterHTML, also utilizing `wait()` and `notifyAll()` for synchronization. This approach ensures that the document is fully loaded before its content is accessed. ```java // Create an instance of the HTMLDocument class HTMLDocument document = new HTMLDocument(); // Subscribe to the 'ReadyStateChange' event. This event will be fired during the document loading process document.OnReadyStateChange.add(new DOMEventHandler() { @Override public void invoke(Object sender, Event e) { // Check the value of 'ReadyState' property // This property is representing the status of the document. For detail information please visit https://www.w3schools.com/jsref/prop_doc_readystate.asp if (document.getReadyState().equals("complete")) { System.out.println(document.getDocumentElement().getOuterHTML()); notifyAll(); } } }); // Navigate asynchronously at the specified Uri document.navigate("https://html.spec.whatwg.org/multipage/introduction.html"); synchronized (this) { wait(10000); } ``` -------------------------------- ### Convert HTML to XPS with Detailed Steps using Java Source: https://docs.aspose.com/html/java/convert-html-to-xps This example shows a more detailed process for converting HTML to XPS in Java. It involves creating an HTML file from a string, loading it into an `HTMLDocument` object, initializing `XpsSaveOptions` with default settings, and then using the `Converter.convertHTML` method to perform the conversion. This approach offers more control if specific file handling or options are needed before conversion. ```java 1// Convert HTML to XPS using Java 2 3// Prepare HTML code and save it to a file 4String code = "Hello, World!!"; 5try (java.io.FileWriter fileWriter = new java.io.FileWriter($o("document.html"))) { 6 fileWriter.write(code); 7} 8 9// Initialize an HTML document from the file 10HTMLDocument document = new HTMLDocument($o("document.html")); 11 12// Initialize XpsSaveOptions 13XpsSaveOptions options = new XpsSaveOptions(); 14 15// Convert HTML to XPS 16Converter.convertHTML(document, options, $o("document-output.xps")); ``` -------------------------------- ### Create Accessibility Validator with All Rules in Java Source: https://docs.aspose.com/html/java/accessibility-validator This example shows how to initialize an AccessibilityValidator that encompasses all available accessibility rules. It utilizes the ValidationBuilder.getAll() method to ensure comprehensive validation against all default settings. ```java // Initialize the webAccessibility container WebAccessibility webAccessibility = new WebAccessibility(); // Create an accessibility validator with all rules using the default settings AccessibilityValidator validator = webAccessibility.createValidator(ValidationBuilder.getAll()); ``` -------------------------------- ### Handle Missing Images with Custom MessageHandler in Java Source: https://docs.aspose.com/html/java/environment-configuration This Java example shows how to handle missing image requests using a custom MessageHandler in Aspose.HTML for Java. It prepares HTML with a missing image, sets up a configuration with a LogMessageHandler, and then converts the HTML to PNG, logging the missing image error. ```java 1// Handle missing image requests with a custom MessageHandler in Aspose.HTML for Java 2 3// Prepare HTML code with missing image file 4String code = ""; 5 6try (java.io.FileWriter fileWriter = new java.io.FileWriter($o("document.html"))) { 7 fileWriter.write(code); 8} 9 10// Create an instance of the Configuration class 11Configuration configuration = new Configuration(); 12 13// Add ErrorMessageHandler to the chain of existing message handlers 14INetworkService network = configuration.getService(INetworkService.class); 15LogMessageHandler logHandler = new LogMessageHandler(); 16network.getMessageHandlers().addItem(logHandler); 17 18// Initialize an HTML document with specified configuration 19// During the document loading, the application will try to load the image and we will see the result of this operation in the console 20HTMLDocument document = new HTMLDocument($o("document.html"), configuration); 21 22// Convert HTML to PNG 23Converter.convertHTML(document, new ImageSaveOptions(), $o("output.png")); ``` -------------------------------- ### Save Webpage with Default Save Options Source: https://docs.aspose.com/html/java/website-to-html This example demonstrates how to save a single web page to a local file using the default settings of the Aspose.HTML for Java API. By default, only resources from the same domain as the specified URL will be downloaded. ```APIDOC ## Save Webpage with Default Save Options ### Description Saves a web page from a given URL to a local file using default resource handling options. Resources from external domains are not downloaded. ### Method `document.save(savePath)` ### Endpoint N/A (Local file operation) ### Parameters #### Path Parameters - `savePath` (String) - Required - The local file path where the HTML content will be saved. #### Query Parameters None #### Request Body None ### Request Example ```java // 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); ``` ### Response #### Success Response (200) - `void` - The operation saves the file locally without returning any specific value. ``` -------------------------------- ### Get Accessibility Criterion and Techniques in Java Source: https://docs.aspose.com/html/java/web-accessibility-rules This Java code demonstrates how to use the Aspose.HTML library to retrieve a specific WCAG success criterion by its code. It initializes the WebAccessibility object, navigates through principles and guidelines, and then fetches the criterion. The code prints the criterion's code, description, and level, followed by all its sufficient techniques. ```java /* * Get accessibility criterion and its sufficient techniques in Java */ // Initialize a webAccessibility container WebAccessibility webAccessibility = new WebAccessibility(); // Get the principle by code Principle principle = webAccessibility.getRules().getPrinciple("1"); // Get guideline Guideline guideline = principle.getGuideline("1.1"); // Get criterion by code Criterion criterion = guideline.getCriterion("1.1.1"); if (criterion != null) { System.out.println(String.format("%s: %s - %s", criterion.getCode(), criterion.getDescription(), criterion.getLevel() )); // @output: 1.1.1:Non-text Content - A // Get all Sufficient Techniques and write to console for (IRule technique : criterion.getSufficientTechniques()) System.out.println(String.format("%s: %s", technique.getCode(), technique.getDescription() )); } ``` -------------------------------- ### Convert Markdown to HTML and then to PDF using Java Source: https://docs.aspose.com/html/java/convert-markdown-to-html This Java example illustrates converting a Markdown file to an HTML document in memory using Converter.convertMarkdown, then saving this HTML document as a PDF file. It utilizes PdfSaveOptions for PDF specific settings and requires the Aspose.HTML for Java library. ```java // Convert Markdown to PDF using Java // Convert Markdown to HTML HTMLDocument document = Converter.convertMarkdown($i("nature.md")); // Initialize PdfSaveOptions PdfSaveOptions options = new PdfSaveOptions(); // Convert the HTML document to PDF file format Converter.convertHTML(document, options, $o("nature-output.pdf")); ``` -------------------------------- ### Render HTML to PDF and Adjust to Widest Page in Java Source: https://docs.aspose.com/html/java/fine-tuning-converters This Java code snippet shows how to convert HTML to PDF while adjusting the page size to fit the widest content. It defines HTML content with different widths, initializes an HTMLDocument, configures page setup options to enable auto-adjustment, and renders to PDF. ```java // Render HTML to PDF and adjust to the widest page with Java // Prepare HTML code String code = " \n" + "
First Page
\n" + "
Second Page
\n"; // Initialize an HTML document from HTML code HTMLDocument document = new HTMLDocument(code, "."); // Create an instance of the PdfRenderingOptions class and set a custom page-size PdfRenderingOptions options = new PdfRenderingOptions(); options.getPageSetup().setAnyPage(new Page(new Size(500, 200))); // Enable auto-adjusting for the page size options.getPageSetup().setAdjustToWidestPage(true); // Create an instance of the PdfDevice class and specify options and output file PdfDevice device = new PdfDevice(options, $o("output.pdf")); // Render HTML to PDF document.renderTo(device); ``` -------------------------------- ### Get Principle by Code Source: https://docs.aspose.com/html/java/web-accessibility-rules This endpoint allows you to retrieve a specific Principle object using its unique code. ```APIDOC ## GET /websites/aspose_html_java/principles/{code} ### Description Get a Principle by its code. Principles are the first level of rules, indicating main directions and purposes. ### Method GET ### Endpoint /websites/aspose_html_java/principles/{code} ### Path Parameters - **code** (String) - Required - The code of the Principle (e.g., "1"). ### Request Example ```java WebAccessibility webAccessibility = new WebAccessibility(); Principle principle = webAccessibility.getRules().getPrinciple("1"); if (principle != null) { System.out.println(String.format("%s: %s", principle.getCode(), principle.getDescription())); } ``` ### Response #### Success Response (200) - **Principle** (object) - The Principle object matching the provided code. - **code** (String) - The code of the Principle. - **description** (String) - The description of the Principle. - **guidelines** (List) - A list of associated Guidelines. #### Response Example ```json { "code": "1", "description": "Perceivable", "guidelines": [ { "code": "1.1", "description": "Text Alternatives", "criteria": [ // ... criteria details ... ] } // ... other guidelines ... ] } ``` ``` -------------------------------- ### Apply Aspose.HTML for Java License from File Source: https://docs.aspose.com/html/java/getting-started/licensing This code snippet demonstrates how to apply an Aspose.HTML for Java license by providing the license file name. It assumes the license file is located in the same directory as the JAR file. If using multiple Aspose products, the fully qualified namespace for the License class should be used. ```java import com.aspose.html.License; // ... License license = new License(); license.setLicense("Aspose.HTML.lic"); ``` -------------------------------- ### Save HTML to Markdown Source: https://docs.aspose.com/html/java/save-a-document This example demonstrates how to save an HTML document as a Markdown file. Markdown is a lightweight markup language with plain-text formatting syntax. ```APIDOC ## Save HTML to Markdown ### Description This endpoint saves an HTML document into a Markdown file. This is useful for converting HTML content into a format suitable for documentation or simple text-based content management. ### Method POST (Implicit - used within a Java application context) ### Endpoint Document.save(path, saveFormat) ### Parameters #### Request Body - **document** (HTMLDocument) - The HTML document object to save. - **path** (string) - The file path where the Markdown file will be saved. - **saveFormat** (HTMLSaveFormat) - The format to save the document in. Use `HTMLSaveFormat.Markdown` for Markdown. ### Request Example ```java // Prepare HTML code String html_code = "

Hello, World!

"; // Initialize a document from a string variable HTMLDocument document = new HTMLDocument(html_code, "."); // Save the document as a Markdown file document.save($o("save-to-MD.md"), HTMLSaveFormat.Markdown); ``` ### Response #### Success Response (200) - **None** (The operation saves a file to the specified path.) #### Response Example (No explicit response body, file is saved to disk.) ``` -------------------------------- ### Get Elements by Tag Name - Java Source: https://docs.aspose.com/html/java/edit-a-document Illustrates how to retrieve a list of all elements that have a specific tag name using Document.getElementsByTagName() in Java. This is useful for iterating over elements of the same type. ```java import com.aspose.html.dom.Document; import com.aspose.html.HTMLCollection; import com.aspose.html.HTMLElement; // Assuming 'document' is an instance of com.aspose.html.Document public class GetElementsByTagNameExample { public static void main(String[] args) { // Create a new HTML document Document document = new Document(); // Add some paragraph elements to the document for (int i = 0; i < 3; i++) { HTMLElement p = (HTMLElement) document.createElement("p"); p.setTextContent("Paragraph " + (i + 1)); document.getBody().appendChild(p); } // Get all elements with the tag name 'p' HTMLCollection paragraphs = document.getElementsByTagName("p"); System.out.println("Found " + paragraphs.getLength() + " paragraph elements."); // Iterate over the collection and print content for (int i = 0; i < paragraphs.getLength(); i++) { HTMLElement paragraph = (HTMLElement) paragraphs.item(i); System.out.println(" - " + paragraph.getTextContent()); } // Clean up the document document.dispose(); } } ``` -------------------------------- ### Get Element by ID - Java Source: https://docs.aspose.com/html/java/edit-a-document Shows how to retrieve the first HTML element that has a specific ID using Document.getElementById() in Java. Returns null if no element with the specified ID is found. ```java import com.aspose.html.dom.Document; import com.aspose.html.HTMLElement; // Assuming 'document' is an instance of com.aspose.html.Document public class GetElementByIdExample { public static void main(String[] args) { // Create a new HTML document Document document = new Document(); // Add an element with an ID to the document for demonstration HTMLElement elementWithId = (HTMLElement) document.createElement("div"); elementWithId.setAttribute("id", "uniqueId"); elementWithId.setTextContent("This element has a unique ID."); document.getBody().appendChild(elementWithId); // Get the element by its ID HTMLElement foundElement = (HTMLElement) document.getElementById("uniqueId"); if (foundElement != null) { System.out.println("Element found: " + foundElement.getTagName()); } else { System.out.println("Element not found."); } // Try to get an element that does not exist HTMLElement nonExistentElement = (HTMLElement) document.getElementById("nonExistentId"); if (nonExistentElement == null) { System.out.println("Element with nonExistentId was not found, as expected."); } // Clean up the document document.dispose(); } } ``` -------------------------------- ### Build Docker Image Command Source: https://docs.aspose.com/html/java/getting-started/using-library-in-docker This command builds a Docker image from a Dockerfile located in the current directory. It tags the image with a specified name, allowing for easy reference when running containers. ```bash docker build -t my-image . ``` -------------------------------- ### Accessing Accessibility Rules in Java Source: https://docs.aspose.com/html/java/web-accessibility-rules Demonstrates how to initialize a WebAccessibility container and access the AccessibilityRules repository to retrieve WCAG 2.0 principles and rules using the Aspose.HTML for Java API. ```java import com.aspose.html.accessibility.AccessibilityRules; import com.aspose.html.accessibility.containers.WebAccessibility; // Initialize WebAccessibility container WebAccessibility accessibility = new WebAccessibility(); // Get the AccessibilityRules repository AccessibilityRules rules = accessibility.getRules(); // Get a Principle by its code // Principle principle = rules.getPrinciple("1"); // Example: Principle 1 - Perceivable // Get all Principles // IList principles = rules.getPrinciples(); // Get specific rules by codes // IList specificRules = rules.getRules("1.1.1", "1.2.3"); // Example: "1.1.1", "1.2.3" ``` -------------------------------- ### Set and Get Attribute - Java Source: https://docs.aspose.com/html/java/edit-a-document Demonstrates setting and retrieving the value of an attribute on a specified HTML element using Element.setAttribute() and Element.getAttribute() in Java. This is essential for managing element properties. ```java import com.aspose.html.dom.Document; import com.aspose.html.HTMLElement; // Assuming 'document' is an instance of com.aspose.html.Document public class AttributeExample { public static void main(String[] args) { // Create a new HTML document Document document = new Document(); // Create a new paragraph element HTMLElement paragraph = (HTMLElement) document.createElement("p"); // Set an attribute 'id' with value 'myParagraph' paragraph.setAttribute("id", "myParagraph"); // Set another attribute 'class' with value 'highlight' paragraph.setAttribute("class", "highlight"); // Get the value of the 'id' attribute String idValue = paragraph.getAttribute("id"); System.out.println("ID attribute value: " + idValue); // Output: ID attribute value: myParagraph // Get the value of the 'class' attribute String classValue = paragraph.getAttribute("class"); System.out.println("Class attribute value: " + classValue); // Output: Class attribute value: highlight // Clean up the document document.dispose(); } } ``` -------------------------------- ### Convert HTML to XPS in One Line Source: https://docs.aspose.com/html/java/convert-html-to-xps This method demonstrates the simplest way to convert HTML to XPS using the static `convertHTML` method of the `Converter` class. It takes the HTML content, a base URI, XpsSaveOptions, and the output file path as arguments. ```APIDOC ## Convert HTML to XPS Using Java (One Line) ### Description Converts an HTML string to an XPS file with a single line of Java code using the `Converter.convertHTML` method. ### Method `Converter.convertHTML(String content, String baseUri, XpsSaveOptions options, String outputPath)` ### Endpoint N/A (This is a library method call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java // Convert HTML to XPS using Java // Invoke the convertHTML() method to convert HTML to XPS Converter.convertHTML("

Convert HTML to XPS!

", ".", new XpsSaveOptions(), "convert-with-single-line.xps"); ``` ### Response #### Success Response (200) N/A (This is a library method call, success is indicated by the absence of exceptions and the creation of the output file). #### Response Example N/A ``` -------------------------------- ### Load Aspose.HTML for Java License from File Source: https://docs.aspose.com/html/java/getting-started/licensing This snippet shows how to set the Aspose.HTML for Java license by providing the license file's path. The license file can be placed in the same folder as the JAR file, and only the filename needs to be specified. ```java com.aspose.html.License license = new com.aspose.html.License(); license.setLicense("Aspose.HTML.lic"); ``` -------------------------------- ### Apply Custom User Stylesheet to HTML and Convert to PDF (Java) Source: https://docs.aspose.com/html/java/environment-configuration This Java code snippet demonstrates how to apply a custom user stylesheet to an HTML document before converting it to PDF. It involves creating a Configuration, obtaining the IUserAgentService, setting a user stylesheet using setUserStyleSheet(), and then converting the HTML document to PDF. Dependencies include Aspose.HTML for Java libraries. ```java 1// Apply a custom user stylesheet to HTML content and convert it to PDF using Java 2 3// Prepare HTML code and save it to a file 4String code = "Hello, World!!!"; 5 6try (java.io.FileWriter fileWriter = new java.io.FileWriter($o("user-agent-stylesheet.html"))) { 7 fileWriter.write(code); 8} 9 10// Create an instance of the Configuration class 11Configuration configuration = new Configuration(); 12 13// Get the IUserAgentService 14IUserAgentService userAgent = configuration.getService(IUserAgentService.class); 15 16// Set a custom color to the element 17userAgent.setUserStyleSheet("span { color: green; }"); 18 19// Initialize an HTML document with specified configuration 20HTMLDocument document = new HTMLDocument($o("user-agent-stylesheet.html"), configuration); 21 22// Convert HTML to PDF 23Converter.convertHTML(document, new PdfSaveOptions(), $o("user-agent-stylesheet_out.pdf")); ``` -------------------------------- ### Access Element Inner HTML - Java Source: https://docs.aspose.com/html/java/edit-a-document Demonstrates how to get the markup contained within an HTML element using the Element.innerHTML property in Java. This allows you to retrieve or modify the HTML content of an element. ```java import com.aspose.html.dom.Document; import com.aspose.html.HTMLElement; // Assuming 'document' is an instance of com.aspose.html.Document public class InnerHtmlExample { public static void main(String[] args) { // Create a new HTML document Document document = new Document(); // Create a div element and set its inner HTML HTMLElement divElement = (HTMLElement) document.createElement("div"); divElement.setInnerHTML("

This is bold text inside the div.

"); // Append the div to the body document.getBody().appendChild(divElement); // Get the inner HTML of the div String innerHtmlContent = divElement.getInnerHTML(); System.out.println("Inner HTML of the div: " + innerHtmlContent); // Output: Inner HTML of the div:

This is bold text inside the div.

// Clean up the document document.dispose(); } } ``` -------------------------------- ### Convert HTML to PDF using Aspose.HTML for Java Source: https://docs.aspose.com/html/java/faq This snippet demonstrates the basic conversion of an HTML file to a PDF document using Aspose.HTML for Java. It requires the `Converter` class and `PdfSaveOptions`. The input is an HTML file path and the output is a PDF file path. ```java Converter.convertHTML(Input("document.html"), new PdfSaveOptions(), Output("output.pdf")); ``` -------------------------------- ### Save HTML to MHTML Source: https://docs.aspose.com/html/java/save-a-document This example shows how to convert and save an HTML document into a single MHTML (MHT) file. MHTML is a web-page archive format that stores all resources within a single file. ```APIDOC ## Save HTML to MHTML ### Description This endpoint converts an HTML document into an MHTML file. MHTML is a web archive format that encapsulates the HTML content and its associated resources into a single file. ### Method POST (Implicit - used within a Java application context) ### Endpoint Document.save(path, saveFormat) ### Parameters #### Request Body - **document** (HTMLDocument) - The HTML document object to save. - **path** (string) - The file path where the MHTML file will be saved. - **saveFormat** (HTMLSaveFormat) - The format to save the document in. Use `HTMLSaveFormat.MHTML` for MHTML. ### Request Example ```java // Prepare a simple HTML file with a linked document java.nio.file.Files.write( java.nio.file.Paths.get($o("document.html")), "

Hello, World!

linked file".getBytes()); // Prepare a simple linked HTML file java.nio.file.Files.write( java.nio.file.Paths.get($o("linked-file.html")), "

Hello, linked file!

".getBytes()); // Load the "document.html" into memory HTMLDocument document = new HTMLDocument($o("document.html")); // Save the document to MHTML format document.save($o("save-to-MTHML.mht"), HTMLSaveFormat.MHTML); ``` ### Response #### Success Response (200) - **None** (The operation saves a file to the specified path.) #### Response Example (No explicit response body, file is saved to disk.) ``` -------------------------------- ### Create HTML for Color Contrast Check in Java Source: https://docs.aspose.com/html/java/check-color-contract This Java code snippet demonstrates how to create an HTML file with specific CSS styles to visually represent good and bad color contrast. This file is then used as input for accessibility checks. ```html
Text with good contrast
Text with bad contrast
``` -------------------------------- ### Convert MHTML to PNG in Java Source: https://docs.aspose.com/html/java/convert-mhtml-to-png This section details the process of converting an MHTML file to a PNG image using the Aspose.HTML for Java library. It outlines the necessary steps and provides a Java code example. ```APIDOC ## Convert MHTML to PNG ### Description This example demonstrates how to convert an MHTML file to a PNG image using the Aspose.HTML for Java library. The process involves opening the MHTML file, initializing `ImageSaveOptions` with the PNG format, and then using the `Converter.convertMHTML()` method. ### Method N/A (This is a code example, not a direct API endpoint call) ### Endpoint N/A ### Parameters N/A ### Request Example ```java // Convert MHTML to PNG using Java // Open an existing MHTML file for reading java.io.FileInputStream fileInputStream = new java.io.FileInputStream("sample.mht"); // Initialize ImageSaveOptions for PNG format ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Png); // Call the convertMHTML() method to convert MHTML to PNG Converter.convertMHTML(fileInputStream, options, "sample-output.png"); ``` ### Response #### Success Response The conversion process results in a PNG image file saved at the specified path (`sample-output.png` in the example). #### Response Example N/A (This is a file operation, not an API response in JSON/XML format) ``` -------------------------------- ### Convert HTML to XPS in One Line using Java Source: https://docs.aspose.com/html/java/convert-html-to-xps This snippet demonstrates the simplest way to convert an HTML string to an XPS file using a single line of Java code. It utilizes the static `convertHTML` method from the `Converter` class, specifying the HTML content, base URI, `XpsSaveOptions`, and the output file path. This method is ideal for quick conversions where default settings are sufficient. ```java 1// Convert HTML to XPS using Java 2 3// Invoke the convertHTML() method to convert HTML to XPS 4Converter.convertHTML("

Convert HTML to XPS!

", ".", new XpsSaveOptions(), $o("convert-with-single-line.xps")); ``` -------------------------------- ### Get Accessibility Rules by Code Source: https://docs.aspose.com/html/java/web-accessibility-rules This endpoint allows you to retrieve a list of accessibility rules based on their codes. It takes an array of rule codes and returns a list of IRule objects that match the provided codes. ```APIDOC ## GET /websites/aspose_html_java/rules ### Description Retrieve and list accessibility rules by code with their descriptions from the rules repository. ### Method GET ### Endpoint /websites/aspose_html_java/rules ### Query Parameters - **rulesCodes** (String[]) - Required - An array of rule codes (e.g., "H2", "1.1"). ### Request Example ```java WebAccessibility webAccessibility = new WebAccessibility(); String[] rulesCodes = new String[]{"H2", "H37", "H30", "1.1", "1.2.1"}; List rules = webAccessibility.getRules().getRules(rulesCodes); for (IRule rule : rules) { System.out.println(String.format("%s: %s", rule.getCode(), rule.getDescription())); } ``` ### Response #### Success Response (200) - **rules** (List) - A list of IRule objects matching the provided codes. - **code** (String) - The code of the rule. - **description** (String) - The description of the rule. #### Response Example ```json [ { "code": "H2", "description": "Combining adjacent image and text links for the same resource" }, { "code": "H37", "description": "Using alt attributes on img elements" }, { "code": "H30", "description": "Providing link text that describes the purpose of a link for anchor elements" }, { "code": "1.1", "description": "Text Alternatives" }, { "code": "1.2.1", "description": "Audio-only and Video-only (Prerecorded)" } ] ``` ``` -------------------------------- ### Convert HTML to DOCX Step-by-Step (Java) Source: https://docs.aspose.com/html/java/convert-html-to-docx This Java code snippet illustrates a more detailed approach to converting an HTML file to a DOCX document. It involves initializing an `HTMLDocument` from a file, creating an instance of `DocSaveOptions`, and then using the `Converter.convertHTML()` method to perform the conversion. This method allows for more control over the conversion process through the `DocSaveOptions` class. ```java // Convert HTML to DOCX using Java // Initialize an HTML document from a file HTMLDocument document = new HTMLDocument($i("canvas.html")); // Initialize DocSaveOptions DocSaveOptions options = new DocSaveOptions(); // Convert HTML to DOCX Converter.convertHTML(document, options, $o("canvas-output.docx")); ```