Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// Access ValidationResult.Errors collection to count total accessibility errors found in the document.

using System;
using System.IO;
using System.Text;

class Program
{
static void Main()
{
try
{
// Prepare a simple HTML file for validation
string htmlContent = "<!DOCTYPE html><html><head><title>Test</title></head><body><img src='image.jpg'></body></html>";
string inputFilePath = "sample.html";
File.WriteAllText(inputFilePath, htmlContent, Encoding.UTF8);

// Initialize WebAccessibility and validator
Aspose.Html.Accessibility.WebAccessibility webAccessibility = new Aspose.Html.Accessibility.WebAccessibility();
Aspose.Html.Accessibility.AccessibilityValidator validator = webAccessibility.CreateValidator(Aspose.Html.Accessibility.ValidationBuilder.All);

// Load the HTML document
using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(inputFilePath))
{
// Perform validation
Aspose.Html.Accessibility.Results.ValidationResult validationResult = validator.Validate(document);

if (!validationResult.Success)
{
foreach (Aspose.Html.Accessibility.Results.RuleValidationResult detail in validationResult.Details)
{
if (!detail.Success)
{
Console.WriteLine(detail.Rule.Code + " - " + detail.Rule.Description);
foreach (Aspose.Html.Accessibility.ITechniqueResult techResult in detail.Errors)
{
Aspose.Html.Accessibility.IError error = techResult.Error;
Console.WriteLine("Error: " + error.ErrorMessage);
if (error.Target.TargetType == Aspose.Html.Accessibility.TargetTypes.HTMLElement)
{
Aspose.Html.HTMLElement element = (Aspose.Html.HTMLElement)error.Target.Item;
Console.WriteLine("Element: " + element.OuterHTML);
}
}
}
}
}
else
{
Console.WriteLine("Document passed accessibility validation successfully.");
}
}

// Clean up the temporary file
if (File.Exists(inputFilePath))
{
File.Delete(inputFilePath);
}
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// Access ValidationResult.Warnings collection to count total accessibility warnings reported for the HTML page.

using System;
using System.IO;
using System.Collections;
using System.Reflection;

class Program
{
static void Main()
{
try
{
// Sample HTML content
string htmlContent = "<!DOCTYPE html><html><head><title>Test</title></head><body><img src='image.jpg' alt=''></body></html>";
string inputPath = "sample.html";
File.WriteAllText(inputPath, htmlContent);

using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(inputPath))
{
Aspose.Html.Accessibility.WebAccessibility webAccessibility = new Aspose.Html.Accessibility.WebAccessibility();
Aspose.Html.Accessibility.AccessibilityValidator validator = webAccessibility.CreateValidator(Aspose.Html.Accessibility.ValidationBuilder.All);
Aspose.Html.Accessibility.Results.ValidationResult validationResult = validator.Validate(document);

// Count warnings using reflection (property may not exist in this version)
int warningCount = 0;
PropertyInfo warningsProp = validationResult.GetType().GetProperty("Warnings");
if (warningsProp != null)
{
IEnumerable warnings = warningsProp.GetValue(validationResult) as IEnumerable;
if (warnings != null)
{
foreach (var _ in warnings)
{
warningCount++;
}
}
}

Console.WriteLine($"Total accessibility warnings: {warningCount}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
// Add a missing <track> element with kind="captions" and appropriate src attribute to a video element programmatically.

using System;
using System.IO;
using System.Collections.Generic;
using Aspose.Html.IO;

class MemoryStreamProvider : Aspose.Html.IO.ICreateStreamProvider, IDisposable
{
private readonly List<MemoryStream> _streams = new List<MemoryStream>();

public IReadOnlyList<MemoryStream> Streams => _streams.AsReadOnly();

public Stream GetStream(string name, string extension)
{
var ms = new MemoryStream();
_streams.Add(ms);
return ms;
}

public Stream GetStream(string name, string extension, int page)
{
var ms = new MemoryStream();
_streams.Add(ms);
return ms;
}

public void ReleaseStream(Stream stream)
{
// No action needed; streams are kept for later reading.
}

public void Dispose()
{
foreach (var ms in _streams)
{
ms.Dispose();
}
_streams.Clear();
}
}

class Program
{
static void Main()
{
try
{
// Prepare directories
string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "AsposeHtmlOutput");
Directory.CreateDirectory(outputDir);

// Create a minimal sample HTML file
string inputHtmlPath = Path.Combine(outputDir, "sample.html");
string htmlContent = @"
<!DOCTYPE html>
<html>
<head><title>Sample</title></head>
<body>
<p>First paragraph.</p>
<p>Second paragraph.</p>
<img src='https://example.com/image.png'>
</body>
</html>";
File.WriteAllText(inputHtmlPath, htmlContent);

// Load the document
var document = new Aspose.Html.HTMLDocument(inputHtmlPath);

// 1. Ensure all images have alt attributes
var images = document.GetElementsByTagName("img");
foreach (Aspose.Html.Dom.Element node in images)
{
var img = node as Aspose.Html.HTMLImageElement;
if (img != null)
{
string alt = img.GetAttribute("alt");
if (string.IsNullOrWhiteSpace(alt))
{
string autoAlt = "Auto-generated alt text";
img.SetAttribute("alt", autoAlt);
}
}
}

// 2. Insert a new image before the second paragraph
var paragraphs = document.GetElementsByTagName("p");
if (paragraphs.Length >= 2)
{
var newImg = (Aspose.Html.HTMLImageElement)document.CreateElement("img");
newImg.SetAttribute("src", "https://example.com/inserted.png");
newImg.SetAttribute("alt", "Inserted image");
Aspose.Html.Dom.Element secondParagraph = (Aspose.Html.Dom.Element)paragraphs[1];
secondParagraph.ParentNode.InsertBefore(newImg, secondParagraph.NextSibling);
}

// 3. Add a watermark div (DOM overlay)
var div = document.CreateElement("div");
div.SetAttribute("style", "position:absolute; top:10px; left:10px; font-size:24px; color:red; background:transparent;");
div.TextContent = "Watermark";
document.Body.AppendChild(div);

// Save the modified HTML
string modifiedHtmlPath = Path.Combine(outputDir, "modified.html");
document.Save(modifiedHtmlPath);

// 4. Convert the document to JPEG using a custom stream provider
var imageOptions = new Aspose.Html.Saving.ImageSaveOptions(Aspose.Html.Rendering.Image.ImageFormat.Jpeg);
using (var provider = new MemoryStreamProvider())
{
Aspose.Html.Converters.Converter.ConvertHTML(document, imageOptions, provider);

if (provider.Streams.Count > 0)
{
var memory = provider.Streams[0];
memory.Seek(0, SeekOrigin.Begin);
string jpegPath = Path.Combine(outputDir, "output.jpg");
using (var fs = File.Create(jpegPath))
{
memory.CopyTo(fs);
}
}
}

Console.WriteLine("Processing completed successfully.");
Console.WriteLine($"Modified HTML saved to: {modifiedHtmlPath}");
Console.WriteLine($"JPEG image saved to: {Path.Combine(outputDir, "output.jpg")}");
}
catch (Exception ex)
{
Console.WriteLine("An error occurred:");
Console.WriteLine(ex.Message);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
// Apply a cancellation token to the validation process to allow graceful termination during long batch runs.

using System;
using System.IO;
using System.Threading;
using System.Collections.Generic;
using System.Net;
using Aspose.Html;
using Aspose.Html.Net;
using Aspose.Html.Services;
using Aspose.Html.Saving;
using Aspose.Html.Converters;

class Handler : Aspose.Html.Net.MessageHandler
{
public override void Invoke(Aspose.Html.Net.INetworkOperationContext context)
{
Next(context);
if (context.Response.StatusCode == HttpStatusCode.InternalServerError)
return;
}
}

class AuthHandler : Aspose.Html.Net.MessageHandler
{
private const string AuthHeader = "Authorization";

public override void Invoke(Aspose.Html.Net.INetworkOperationContext context)
{
if (string.IsNullOrEmpty(context.Request.Headers[AuthHeader]))
{
context.Response.StatusCode = HttpStatusCode.Unauthorized;
return;
}
Next(context);
}
}

class LogHandler : Aspose.Html.Net.MessageHandler
{
private readonly List<string> _logs = new List<string>();

public override void Invoke(Aspose.Html.Net.INetworkOperationContext context)
{
Next(context);
_logs.Add("URL: " + context.Request.RequestUri + " | Status: " + context.Response.StatusCode);
}

public IReadOnlyList<string> Logs => _logs;
}

class Program
{
static void Main(string[] args)
{
try
{
string inputFolder = "input";
string outputFolder = "output";

Directory.CreateDirectory(inputFolder);
Directory.CreateDirectory(outputFolder);

string sampleHtmlPath = Path.Combine(inputFolder, "sample.html");
if (!File.Exists(sampleHtmlPath))
{
File.WriteAllText(sampleHtmlPath, "<!DOCTYPE html><html><body><h1>Sample</h1></body></html>");
}

// Configure Aspose.Html with custom network handlers
Aspose.Html.Configuration configuration = new Aspose.Html.Configuration();
INetworkService network = configuration.GetService<INetworkService>();
network.MessageHandlers.Add(new Handler());
network.MessageHandlers.Add(new AuthHandler());
network.MessageHandlers.Add(new LogHandler());

var processedFiles = new HashSet<string>();

// Bounded polling loop (max 5 iterations)
for (int iteration = 0; iteration < 5; iteration++)
{
string[] htmlFiles = Directory.GetFiles(inputFolder, "*.html");
foreach (string htmlPath in htmlFiles)
{
if (processedFiles.Contains(htmlPath))
continue;

using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlPath, configuration))
{
string outputPdfPath = Path.Combine(outputFolder,
Path.GetFileNameWithoutExtension(htmlPath) + ".pdf");

PdfSaveOptions pdfOptions = new PdfSaveOptions();
Aspose.Html.Converters.Converter.ConvertHTML(document, pdfOptions, outputPdfPath);
}

processedFiles.Add(htmlPath);
}

Thread.Sleep(200);
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
}
Loading
Loading