Skip to content

Instantly share code, notes, and snippets.

@aspose-com-gists
Last active September 11, 2026 11:17
Show Gist options
  • Select an option

  • Save aspose-com-gists/4894789d0ac2fff5ce86f091716a3f50 to your computer and use it in GitHub Desktop.

Select an option

Save aspose-com-gists/4894789d0ac2fff5ce86f091716a3f50 to your computer and use it in GitHub Desktop.
This Gist contains examples Aspose.HTML Web Accessibility

Code Examples for Checking Web Accessibility

This gist repository contains Java examples that accompany the Web Accessibility chapter in the Aspose.HTML for Java documentation. These examples demonstrate how to validate HTML content for accessibility in accordance with the WCAG standard, enabling the identification of errors and warnings.

What's Included?

This repository contains Java examples that demonstrate how to implement and manage web accessibility features in HTML documents using the Aspose.HTML library for Java. Here you will find code that illustrates:

  • Check web documents against WCAG (Web Content Accessibility Guidelines) standards using built-in validators and predefined rule sets.
  • Check for alternative text in image elements to ensure accessibility for screen readers.
  • Evaluate color contrast and compare it to accessibility standards, and assess multimedia elements to ensure they comply with accessibility guidelines.
  • Create reports that detail accessibility violations found in an HTML document.
  • Customize availability checking and use specific rule sets to control the level and focus of analysis.
  • Access accessibility principles, guidelines, and criteria directly through the Aspose.HTML for Java API.

About Aspose.HTML for Java

Aspose.HTML for Java is a powerful, on-premise Java library for parsing, navigating, processing, rendering, and converting HTML documents. The library provides a comprehensive set of features for checking web accessibility, allowing developers to audit HTML content for WCAG (Web Content Accessibility Guidelines) compliance. Its APIs enable you to programmatically check for accessibility violations and generate detailed reports to ensure your web content is accessible to all users.

How to Use These Examples

  1. Install the latest Aspose.HTML for Java.
  2. Add the Aspose repository configuration and API dependency as described in the installation guide.
  3. Explore the contents of this repository and copy the corresponding code into your project.
  4. Adjust the paths, parameters, and inputs to suit your environment.
  5. Run your project to see the example in action.

You can download a free trial of Aspose.HTML for Java and use a temporary license for unrestricted access.

Documentation

Detailed explanations and full context for each example can be found in the Web Accessibility sections of the official documentation.

Other Related Resources

Prerequisites

To run the examples, you need:

  • J2SE 1.8 or higher.
  • Supported OS: Windows, macOS, Linux.
  • Development Environment: Any Java IDE (e.g., IntelliJ IDEA, Eclipse, NetBeans).
  • Build tool: Maven or Gradle for dependency management.
Aspose.HTML for Java - Web Accessibility
// Validate HTML image alt text accessibility with detailed error reporting
// Learn more: https://docs.aspose.com/html/java/screen-reader-accessibility/
// Prepare a path to a source HTML file
String documentPath = "alt-tag.html";
// Create a WebAccessibility instance
WebAccessibility webAccessibility = new WebAccessibility();
// Get from the rules list Principle "1. Perceivable"
// by code "1" and get guideline "1.1 Text Alternatives"
Guideline guideline = webAccessibility.getRules()
.getPrinciple("1").getGuideline("1.1");
// Create an accessibility validator - pass the found guideline
// as parameters and specify the full validation settings
AccessibilityValidator validator = webAccessibility.createValidator(
guideline,
ValidationBuilder.getAll()
);
// Initialize an HTMLDocument object
final HTMLDocument document = new HTMLDocument(documentPath);
ValidationResult validationResult = validator.validate(document);
if (!validationResult.getSuccess()) {
// Get all the result details
for (RuleValidationResult ruleResult : validationResult.getDetails()) {
// If the result of the rule is unsuccessful
if (!ruleResult.getSuccess()) {
// Get an errors list
for (ITechniqueResult result : ruleResult.getErrors()) {
// Check the type of the erroneous element, in this case,
// we have an error in the HTML Element
if (result.getError().getTarget().getTargetType() == TargetTypes.HTMLElement) {
HTMLElement rule = (HTMLElement) result.getError().getTarget().getItem();
System.out.println(String.format("Error in rule %s : %s",
result.getRule().getCode(),
result.getError().getErrorMessage()
));
System.out.println(String.format("HTML Element: %s",
rule.getOuterHTML()
));
}
}
}
}
}
// Check color contrast on an HTML document using Java
// Learn more: https://docs.aspose.com/html/java/check-color-contrast/
// Prepare a path to a source HTML file
String documentPath = "check-color.html";
// Create a WebAccessibility instance
WebAccessibility webAccessibility = new WebAccessibility();
// Get Principle "1.Perceivable" by code "1" and get guideline "1.4"
Guideline guideline = webAccessibility.getRules()
.getPrinciple("1").getGuideline("1.4");
// Get criterion by code, for example 1.4.3
Criterion criterion = guideline.getCriterion("1.4.3");
// Create an accessibility validator for the selected criterion
// and enable all validation settings
AccessibilityValidator validator = webAccessibility.createValidator(
criterion,
ValidationBuilder.getAll()
);
final HTMLDocument document = new HTMLDocument(documentPath);
ValidationResult validationResult = validator.validate(document);
if (!validationResult.getSuccess()) {
// Get all result details
for (RuleValidationResult ruleResult : validationResult.getDetails()) {
// If the result of the rule is unsuccessful
if (!ruleResult.getSuccess()) {
// Get errors list
for (ITechniqueResult result : ruleResult.getErrors()) {
// Check the type of the erroneous element, in this case
// we have an error in the html element rule
if (result.getError().getTarget().getTargetType() == TargetTypes.HTMLElement) {
// Element of file with error
HTMLElement rule = (HTMLElement) result.getError().getTarget().getItem();
System.out.println(String.format("Error in rule %s : %s",
result.getRule().getCode(), result.getError().getErrorMessage()));
System.out.println(String.format("HTML Element: %s",
rule.getOuterHTML()));
}
}
}
}
}
// Validate HTML accessibility for color contrast in Java using WCAG criteria
// Learn more: https://docs.aspose.com/html/java/check-color-contrast/
// Prepare a path to a source HTML file
String documentPath = "check-color.html";
// Create a WebAccessibility instance
WebAccessibility webAccessibility = new WebAccessibility();
// Get Principle "1.Perceivable" by code "1" and get guideline "1.4"
Guideline guideline = webAccessibility.getRules()
.getPrinciple("1").getGuideline("1.4");
// Get criterion by code, for example 1.4.3
Criterion criterion143 = guideline.getCriterion("1.4.3");
// Get criterion by code, for example 1.4.6
Criterion criterion146 = guideline.getCriterion("1.4.6");
// Create an accessibility validator for the selected criteria
// and enable all validation settings
List<IRule> rules = new List<>();
rules.add(criterion143);
rules.add(criterion146);
AccessibilityValidator validator = webAccessibility.createValidator(
rules,
ValidationBuilder.getAll()
);
final HTMLDocument document = new HTMLDocument(documentPath);
ValidationResult validationResult = validator.validate(document);
if (!validationResult.getSuccess()) {
System.out.println(validationResult.saveToString());
}
// Validate an HTML document using specific rule codes with Java
// Learn more: https://docs.aspose.com/html/java/web-accessibility-rules/
String htmlPath = "input.html";
// Create a WebAccessibility instance
WebAccessibility webAccessibility = new WebAccessibility();
// List of necessary rules for checking (rule code according to the specification)
String[] rulesCode = new String[]{"H2", "H37", "H67", "H86"};
// Get the required IList<IRule> rules from the rules reference
List<IRule> rules = webAccessibility.getRules().getRules(rulesCode);
// Create an accessibility validator, pass the found rules as parameters,
// and specify the full validation settings
AccessibilityValidator validator = webAccessibility.createValidator(
rules, ValidationBuilder.getAll());
// Initialize an object of the HTMLDocument
final HTMLDocument document = new HTMLDocument(htmlPath);
// Check the document
ValidationResult validationResult = validator.validate(document);
// Return the result in string format
// SaveToString - return only errors and warnings
System.out.println(validationResult.saveToString());
// Validate HTML for multimedia accessibility using Java
// Learn more: https://docs.aspose.com/html/java/screen-reader-accessibility/
// Initialize a WebAccessibility container
WebAccessibility webAccessibility = new WebAccessibility();
// Get from the rules list Principle "1.Perceivable" by code "1"
// and get guideline "1.2 Time-based Media"
Guideline guideline = webAccessibility.getRules()
.getPrinciple("1").getGuideline("1.2");
// Create an accessibility validator, pass the found guideline
// as parameters, and specify the full validation settings
AccessibilityValidator validator = webAccessibility.createValidator(
guideline,
ValidationBuilder.getAll()
);
// Initialize an HTMLDocument object
final HTMLDocument document = new HTMLDocument("https://www.youtube.com/watch?v=Yugq1KyZCI0");
ValidationResult validationResult = validator.validate(document);
// Checking for success
if (!validationResult.getSuccess()) {
// Get all result details
for (RuleValidationResult ruleResult : validationResult.getDetails()) {
// If the result of the rule is unsuccessful
if (!ruleResult.getSuccess()) {
// Get an errors list
for (ITechniqueResult result : ruleResult.getErrors()) {
// Check the type of the erroneous element
if (result.getError().getTarget().getTargetType() == TargetTypes.HTMLElement) {
HTMLElement rule = (HTMLElement) result.getError().getTarget().getItem();
System.out.println(String.format("Error in rule %s : %s",
result.getRule().getCode(),
result.getError().getErrorMessage()
));
System.out.println(String.format("HTML Element: %s",
rule.getOuterHTML()
));
}
}
}
}
}
// Validate HTML for accessibility in Java and export all errors and warnings as an XML
// Learn more: https://docs.aspose.com/html/java/web-accessibility-validation-results/
String htmlPath = "input.html";
final HTMLDocument document = new HTMLDocument(htmlPath);
AccessibilityValidator validator = new WebAccessibility().createValidator();
ValidationResult validationresult = validator.validate(document);
final java.io.StringWriter sw = new java.io.StringWriter();
validationresult.saveTo(sw, ValidationResultSaveFormat.XML);
String xml = sw.toString();
System.out.println(xml);
DocumentBuilderFactory documentBuildFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuildFactory.newDocumentBuilder();
documentBuilder.parse(new java.io.ByteArrayInputStream(xml.getBytes()));
// Validate HTML for accessibility in Java and export all errors and warnings as a string
// Learn more: https://docs.aspose.com/html/java/web-accessibility-validation-results/
String htmlPath = "input.html";
final HTMLDocument document = new HTMLDocument(htmlPath);
AccessibilityValidator validator = new WebAccessibility().createValidator();
ValidationResult validationresult = validator.validate(document);
// get rules errors in string format
String content = validationresult.saveToString();
// SaveToString - return only errors and warnings
// if everything is ok, it will return "validationResult:true"
System.out.println(content);
// Check HTML for WCAG compliance and output failed rule codes and error messages
// Learn more: https://docs.aspose.com/html/java/web-accessibility-check/
// Create a WebAccessibility instance
WebAccessibility webAccessibility = new WebAccessibility();
// Create an accessibility validator with static instance
// for all rules from repository that match the builder settings
AccessibilityValidator validator = webAccessibility.createValidator(ValidationBuilder.getAll());
String documentPath = "input.html";
// Initialize an object of the HTMLDocument class
final HTMLDocument document = new HTMLDocument(documentPath);
ValidationResult validationResult = validator.validate(document);
for (RuleValidationResult ruleResult : validationResult.getDetails()) {
// list only unsuccessful rule
if (!ruleResult.getSuccess()) {
// print the code and description of the rule
System.out.println(String.format("%s: %s = %s",
ruleResult.getRule().getCode(),
ruleResult.getRule().getDescription(),
ruleResult.getSuccess()
));
// print the results of methods with errors
for (ITechniqueResult ruleDetail : ruleResult.getErrors()) {
// print the code and description of the method
StringBuilder str = new StringBuilder(String.format("\n%s: %s - %s",
ruleDetail.getRule().getCode(),
ruleDetail.getSuccess(),
ruleDetail.getRule().getDescription()
));
// get an error object
IError error = ruleDetail.getError();
// get a target object
Target target = error.getTarget();
// get error type and message
str.append(String.format("\n\n\t%s : %s",
error.getErrorTypeName(),
error.getErrorMessage()
));
if (target != null) {
// Checking the type of the contained object for casting and working with it
if (target.getTargetType() == TargetTypes.CSSStyleRule) {
ICSSStyleRule cssRule = (ICSSStyleRule) target.getItem();
str.append(String.format("\n\n\t%s",
cssRule.getCSSText()
));
}
if (ruleDetail.getError().getTarget().getTargetType() == TargetTypes.CSSStyleSheet) {
str.append(String.format("\n\n\t%s",
((ICSSStyleSheet) target.getItem()).getTitle()
));
}
if (ruleDetail.getError().getTarget().getTargetType() == TargetTypes.HTMLElement) {
str.append(String.format("\n\n\t%s",
((HTMLElement) target.getItem()).getOuterHTML()
));
}
}
System.out.println(str);
}
}
}
// Validate HTML accessibility using Java and get detailed failed rule results
// Learn more: https://docs.aspose.com/html/java/web-accessibility-validation-results/
// Create a WebAccessibility instance
WebAccessibility webAccessibility = new WebAccessibility();
// Create an accessibility validator with static instance for all rules
// from repository that match the builder settings
AccessibilityValidator validator = webAccessibility.createValidator(ValidationBuilder.getAll());
String documentPath = "input.html";
// Initialize an object of the HTMLDocument class
final HTMLDocument document = new HTMLDocument(documentPath);
ValidationResult validationResult = validator.validate(document);
// Take a list of rules results
for (RuleValidationResult ruleResult : validationResult.getDetails()) {
// List only unsuccessful rule
if (!ruleResult.getSuccess()) {
// Print the code and description of the rule
System.out.println(String.format("%s: %s",
ruleResult.getRule().getCode(),
ruleResult.getRule().getDescription()
));
// Print the results of all methods
for (ITechniqueResult ruleDetail : ruleResult.getResults()) {
// Print the code, status, and description of each technique
StringBuilder str = new StringBuilder(String.format("%n%s: %s - %s",
ruleDetail.getRule().getCode(),
ruleDetail.getSuccess(),
ruleDetail.getRule().getDescription()
));
System.out.println(str);
}
}
}
// Check website for WCAG compliance in Java
// Learn more: https://docs.aspose.com/html/java/web-accessibility-check/
// Create a WebAccessibility instance
WebAccessibility webAccessibility = new WebAccessibility();
// Create an accessibility validator with static instance
// for all rules from repository that match the builder settings
AccessibilityValidator validator = webAccessibility.createValidator(ValidationBuilder.getAll());
// Initialize an HTMLDocument object
final HTMLDocument document = new HTMLDocument("https://products.aspose.com/html/net/generators/video/");
ValidationResult validationResult = validator.validate(document);
// Checking for success
if (!validationResult.getSuccess()) {
// Get a list of Details
for (RuleValidationResult detail : validationResult.getDetails()) {
System.out.println(String.format("%s: %s = %s",
detail.getRule().getCode(),
detail.getRule().getDescription(),
detail.getSuccess()
));
}
}
// Get accessibility criterion and its sufficient techniques in Java
// Learn more: https://docs.aspose.com/html/java/web-accessibility-rules/
// Create a WebAccessibility instance
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()
));
}
// Get accessibility guideline by code from WCAG principle in Aspose.HTML for Java
// Learn more: https://docs.aspose.com/html/java/web-accessibility-rules/
// 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
}
// Get accessibility principle by code from WCAG rules in Aspose.HTML for Java
// Learn more: https://docs.aspose.com/html/java/web-accessibility-rules/
// Create a WebAccessibility instance
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
// Retrieve and list accessibility rules by code with their descriptions from the rules repository
// Learn more: https://docs.aspose.com/html/java/web-accessibility-rules/
// Create a WebAccessibility instance
WebAccessibility webAccessibility = new WebAccessibility();
// List of rule codes can contain both technique codes and principles,
// guidelines and criteria - all rules that implement the interface IRule
String[] rulesCodes = new String[]{"H2", "H37", "H30", "1.1", "1.2.1"};
// Get a list of IRule objects; if a rule with the specified code is not found,
// it will not be in the list
List<IRule> rules = webAccessibility.getRules().getRules(rulesCodes);
// Get code and description of rule
for (IRule rule : rules) {
System.out.println(String.format("%s: %s",
rule.getCode(),
rule.getDescription()
));
}
// Validate HTML against WCAG rules using Java
// Learn more: https://docs.aspose.com/html/java/web-accessibility-validation-results/
// Create a WebAccessibility instance
WebAccessibility webAccessibility = new WebAccessibility();
// Create an accessibility validator with static instance for all rules
// from repository that match the builder settings
AccessibilityValidator validator = webAccessibility.createValidator(ValidationBuilder.getAll());
// Prepare a path to a source HTML file
String documentPath = "input.html";
// Initialize an object of the HTMLDocument class
final HTMLDocument document = new HTMLDocument(documentPath);
ValidationResult validationResult = validator.validate(document);
// Checking for success
if (!validationResult.getSuccess()) {
// Get a list of RuleValidationResult Details
for (RuleValidationResult detail : validationResult.getDetails()) {
System.out.println(String.format("%s: %s = %s",
detail.getRule().getCode(),
detail.getRule().getDescription(),
detail.getSuccess()));
}
}
// Check HTML document for WCAG compliance in Java and log each rule code, description, and pass status
// Learn more: https://docs.aspose.com/html/java/web-accessibility/
// Create a WebAccessibility instance
WebAccessibility webAccessibility = new WebAccessibility();
// Create an accessibility validator
AccessibilityValidator validator = webAccessibility.createValidator();
// Prepare a path to a source HTML file
String documentPath = "test-checker.html";
// Initialize an HTMLDocument object
final HTMLDocument document = new HTMLDocument(documentPath);
ValidationResult result = validator.validate(document);
// Checking for success
if (!result.getSuccess()) {
for (RuleValidationResult detail : result.getDetails()) {
// ... do the analysis here...
System.out.println(String.format("%s: %s = %s",
detail.getRule().getCode(),
detail.getRule().getDescription(),
detail.getSuccess()
));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment