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,69 @@
// Add error handling for missing src attributes and log warnings without interrupting workflow.

using System;
using System.IO;
using Aspose.Html;
using Aspose.Html.Accessibility;
using Aspose.Html.Accessibility.Results;
using Aspose.Html.Dom;
using Aspose.Html.Dom.XPath;

class Program
{
static void Main()
{
try
{
// Sample HTML content with an <img> missing the src attribute
string htmlContent = "<html><body><img alt='no src'><img src='image.png'></body></html>";
string baseUri = "about:blank";

// Load the document using the two‑argument constructor (content, baseUri)
Aspose.Html.HTMLDocument doc = new Aspose.Html.HTMLDocument(htmlContent, baseUri);

// Log file path
string logPath = "validation_warnings.log";
File.WriteAllText(logPath, "Validation warnings:" + Environment.NewLine);

// -----------------------------------------------------------------
// Detect <img> elements without a src attribute using XPath
// -----------------------------------------------------------------
Aspose.Html.Dom.XPath.IXPathResult xpathResult = doc.Evaluate(
"//img[not(@src)]",
doc,
doc.CreateNSResolver(doc),
Aspose.Html.Dom.XPath.XPathResultType.Any,
null);

Aspose.Html.Dom.Node node;
while ((node = xpathResult.IterateNext()) != null)
{
Aspose.Html.HTMLImageElement img = node as Aspose.Html.HTMLImageElement;
if (img != null)
{
string warning = $"Warning: <img> element missing src attribute. OuterHTML: {img.OuterHTML}";
File.AppendAllText(logPath, warning + Environment.NewLine);
}
}

// -----------------------------------------------------------------
// Run the accessibility validator (optional – logs all rule results)
// -----------------------------------------------------------------
Aspose.Html.Accessibility.WebAccessibility webAccessibility = new Aspose.Html.Accessibility.WebAccessibility();
Aspose.Html.Accessibility.AccessibilityValidator validator = webAccessibility.CreateValidator();
Aspose.Html.Accessibility.Results.ValidationResult validationResult = validator.Validate(doc);

foreach (Aspose.Html.Accessibility.Results.RuleValidationResult detail in validationResult.Details)
{
// Log each validation detail using its default string representation
File.AppendAllText(logPath, detail.ToString() + Environment.NewLine);
}

Console.WriteLine("Validation completed. See log at " + Path.GetFullPath(logPath));
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,41 +1,55 @@
// Add retry logic for transient network failures when downloading images or icons.

using System;
using System.IO;
using Aspose.Html.Net;

public sealed class RetryHandler : Aspose.Html.Net.MessageHandler
{
private readonly int _maxRetries;
public RetryHandler(int maxRetries) { _maxRetries = maxRetries; }
public RetryHandler(int maxRetries)
{
_maxRetries = maxRetries;
}

public override void Invoke(Aspose.Html.Net.INetworkOperationContext context)
{
for (int attempt = 0; attempt <= _maxRetries; attempt++)
{
Next(context);
if (context.Response != null && (int)context.Response.StatusCode < 500)
{
break;
}
}
}
}

class Program
public class Program
{
static void Main()
public static void Main()
{
try
{
// Input HTML URL (can be any reachable page with images/icons)
string inputUrl = "https://example.com/sample.html";
// Output image file path
string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "output.png");

// Configure Aspose.HTML with retry handler
Aspose.Html.Configuration configuration = new Aspose.Html.Configuration();
Aspose.Html.Services.INetworkService networkService = configuration.GetService<Aspose.Html.Services.INetworkService>();
networkService.MessageHandlers.Add(new RetryHandler(3));

string html = "<html><body><h1>Sample</h1><img src='https://example.com/image.png' alt='sample'></body></html>";
using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(html, configuration))
// Load the HTML document from the URL using the configured network service
using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(inputUrl, configuration))
{
Aspose.Html.Saving.ImageSaveOptions options = new Aspose.Html.Saving.ImageSaveOptions();
Aspose.Html.Converters.Converter.ConvertHTML(document, options, "output.png");
// Convert the HTML document to an image (PNG)
Aspose.Html.Saving.ImageSaveOptions saveOptions = new Aspose.Html.Saving.ImageSaveOptions();
Aspose.Html.Converters.Converter.ConvertHTML(document, saveOptions, outputPath);
}

Console.WriteLine("Conversion completed successfully.");
Console.WriteLine("Conversion completed successfully. Output saved to: " + outputPath);
}
catch (Exception ex)
{
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

class Program
{
static void Main()
static void Main(string[] args)
{
try
{
Expand All @@ -16,33 +16,36 @@ static void Main()
// Input files
string[] inputs = new string[] { "sample1.html", "sample2.html" };

// Create minimal sample HTML files if they do not exist
if (!File.Exists(inputs[0]))
File.WriteAllText(inputs[0], "<html><body><h1>Sample 1</h1></body></html>");
if (!File.Exists(inputs[1]))
File.WriteAllText(inputs[1], "<html><body><h1>Sample 2</h1></body></html>");

for (int i = 0; i < inputs.Length; i++)
{
string inputPath = inputs[i];

using (var document = new Aspose.Html.HTMLDocument(inputPath, Directory.GetCurrentDirectory()))
// Ensure sample input file exists (minimal content)
if (!File.Exists(inputPath))
{
File.WriteAllText(inputPath, "<html><body><h1>Sample</h1></body></html>");
}

using (var document = new Aspose.Html.HTMLDocument(inputPath))
{
// Configure image options
var options = new Aspose.Html.Saving.ImageSaveOptions(Aspose.Html.Rendering.Image.ImageFormat.Jpeg);
options.HorizontalResolution = 300;
options.VerticalResolution = 300;

// Determine domain name for prefix
// Determine domain prefix
string domain;
Uri uri = new Uri(Path.GetFullPath(inputPath), UriKind.Absolute);
if (uri.IsAbsoluteUri && !string.IsNullOrEmpty(uri.Host))
if (Uri.TryCreate(inputPath, UriKind.Absolute, out Uri uri) && uri.IsAbsoluteUri && !string.IsNullOrEmpty(uri.Host))
{
domain = uri.Host;
}
else
{
domain = "local";
}

string outputFileName = $"{domain}_{Path.GetFileNameWithoutExtension(inputPath)}.jpg";
string outputPath = Path.Combine(outputDir, outputFileName);
string fileName = $"{domain}_{Path.GetFileNameWithoutExtension(inputPath)}.jpeg";
string outputPath = Path.Combine(outputDir, fileName);

// Convert
Aspose.Html.Converters.Converter.ConvertHTML(document, options, outputPath);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
// Archive all extracted images and icons into a ZIP file for easy distribution.

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

class Program
{
static void Main()
{
try
{
// Define paths
string sourceZipPath = Path.Combine(Path.GetTempPath(), "source.zip");
string extractDir = Path.Combine(Path.GetTempPath(), "extracted_assets");
string outputZipPath = Path.Combine(Path.GetTempPath(), "ImagesAndIcons.zip");

// Ensure clean directories
if (Directory.Exists(extractDir))
Directory.Delete(extractDir, true);
Directory.CreateDirectory(extractDir);

// Create a sample source zip with dummy image/icon files if it does not exist
if (!File.Exists(sourceZipPath))
{
using (FileStream srcStream = new FileStream(sourceZipPath, FileMode.Create))
using (ZipArchive srcArchive = new ZipArchive(srcStream, ZipArchiveMode.Create))
{
// Dummy PNG
ZipArchiveEntry pngEntry = srcArchive.CreateEntry("images/sample.png");
using (Stream entryStream = pngEntry.Open())
using (StreamWriter writer = new StreamWriter(entryStream))
{
writer.Write("dummy png content");
}

// Dummy JPG
ZipArchiveEntry jpgEntry = srcArchive.CreateEntry("icons/icon.jpg");
using (Stream entryStream = jpgEntry.Open())
using (StreamWriter writer = new StreamWriter(entryStream))
{
writer.Write("dummy jpg content");
}

// Non-image file (should be ignored)
ZipArchiveEntry txtEntry = srcArchive.CreateEntry("docs/readme.txt");
using (Stream entryStream = txtEntry.Open())
using (StreamWriter writer = new StreamWriter(entryStream))
{
writer.Write("just a text file");
}
}
}

// Extract only image and icon files from the source zip
using (FileStream zipStream = File.OpenRead(sourceZipPath))
using (ZipArchive archive = new ZipArchive(zipStream, ZipArchiveMode.Read))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
if (entry.FullName.EndsWith(".png", StringComparison.OrdinalIgnoreCase) ||
entry.FullName.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) ||
entry.FullName.EndsWith(".jpeg", StringComparison.OrdinalIgnoreCase) ||
entry.FullName.EndsWith(".gif", StringComparison.OrdinalIgnoreCase) ||
entry.FullName.EndsWith(".ico", StringComparison.OrdinalIgnoreCase) ||
entry.FullName.EndsWith(".svg", StringComparison.OrdinalIgnoreCase))
{
string entryPath = Path.Combine(extractDir, entry.FullName);
Directory.CreateDirectory(Path.GetDirectoryName(entryPath));
entry.ExtractToFile(entryPath, true);
}
}
}

// Optional: Load an HTML file from the extracted assets and render to PDF using Aspose.HTML
// (Demonstrates usage of Aspose.HTML without affecting the zip operation)
string[] htmlFiles = Directory.GetFiles(extractDir, "*.html", SearchOption.AllDirectories);
if (htmlFiles.Length > 0)
{
Aspose.Html.Configuration configuration = new Aspose.Html.Configuration();
using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlFiles[0], configuration))
{
string pdfPath = Path.ChangeExtension(htmlFiles[0], ".pdf");
using (Aspose.Html.Rendering.Pdf.PdfDevice device = new Aspose.Html.Rendering.Pdf.PdfDevice(pdfPath))
{
document.RenderTo(device);
}
}
}

// Create a new zip containing only the extracted images and icons
if (File.Exists(outputZipPath))
File.Delete(outputZipPath);
using (FileStream outStream = new FileStream(outputZipPath, FileMode.Create))
using (ZipArchive outArchive = new ZipArchive(outStream, ZipArchiveMode.Create))
{
foreach (string filePath in Directory.GetFiles(extractDir, "*.*", SearchOption.AllDirectories))
{
if (filePath.EndsWith(".png", StringComparison.OrdinalIgnoreCase) ||
filePath.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) ||
filePath.EndsWith(".jpeg", StringComparison.OrdinalIgnoreCase) ||
filePath.EndsWith(".gif", StringComparison.OrdinalIgnoreCase) ||
filePath.EndsWith(".ico", StringComparison.OrdinalIgnoreCase) ||
filePath.EndsWith(".svg", StringComparison.OrdinalIgnoreCase))
{
string entryName = Path.GetRelativePath(extractDir, filePath);
outArchive.CreateEntryFromFile(filePath, entryName);
}
}
}

Console.WriteLine("Extraction and archiving completed successfully.");
Console.WriteLine($"Extracted assets directory: {extractDir}");
Console.WriteLine($"Output ZIP file: {outputZipPath}");
}
catch (Exception ex)
{
Console.Error.WriteLine($"Error: {ex.Message}");
}
}
}
Loading
Loading