Skip to content

Instantly share code, notes, and snippets.

@aspose-com-gists
Last active November 14, 2025 16:52
Show Gist options
  • Select an option

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

Select an option

Save aspose-com-gists/be3a99906eba4675e28ca0c334be8629 to your computer and use it in GitHub Desktop.
Find answers to popular questions about how to work with HTML in C#

How-to Code Examples

This Gist repository contains C# code snippets that correspond to the How-To Articles chapter of the Aspose.HTML for .NET documentation. These small examples are practical, ready-to-use code snippets that demonstrate common tasks and advanced techniques for working with HTML documents using Aspose.HTML for .NET.

Topics Covered

These gists are practical solutions to popular questions, including:

  • How to Change Text Color – Apply CSS or inline styles to modify the appearance of text.
  • How to Change Background Color – Customize background styles using internal CSS or inline attributes.
  • How to Change Border Color – Add borders to elements using CSS or inline attributes.
  • How to Add an Image to HTML – Insert images into existing documents programmatically.
  • How to Use CSS Selectors – Select and manipulate elements using QuerySelector() and QuerySelectorAll().
  • How to Use XPath Queries – Use the Evaluate() method to locate and extract nodes based on XPath expressions.
  • How to Set a Custom Font Folder – Configure the font directory to influence rendering in PDF or image conversion.
  • How to Serialize Form Input Values – Capture and process user input values from form elements.
  • How to Check for Empty HTML Content – Verify whether the document body contains any text.

Getting Started

Each gist is designed to be self-contained and executable. To get the most out of them:

  1. Install Aspose.HTML for .NET via NuGet.
  2. Clone or download the repository.
  3. Configure paths, settings, and inputs to suit your environment.
  4. Run your project to see the example in action.

Documentation

Detailed explanations and full context for each example can be found in the How-To Articles sections of the official documentation.

About Aspose.HTML for .NET

Aspose.HTML for .NET is a powerful .NET library for parsing, modifying, and converting HTML and HTML-related formats (SVG, MHTML, XHTML, Markdown, EPUB). It provides built-in support for CSS, JavaScript, DOM traversal, XPath, document save options, and more.

Contributing

If you have questions or suggestions related to these examples, please use the Aspose.HTML Support Forum to get help or share feedback.

Other Related Resources

Aspose.HTML for .NET – How-to Articles
// How to automatically add alt text to images in an HTML file using C#
// Learn more: https://docs.aspose.com/html/net/how-to-articles/
string inputPath = Path.Combine(DataDir, "test-checker.html");
string outputPath = Path.Combine(OutputDir, "test-checker-updated.html");
// Load the HTML document
HTMLDocument document = new HTMLDocument(inputPath);
// Get all <img> elements in the document
HTMLCollection images = document.GetElementsByTagName("img");
// Iterate through all image elements
foreach (Element node in images)
{
// Ensure the node is an HTMLImageElement
HTMLImageElement img = node as HTMLImageElement;
if (img != null)
{
// Read the existing alt attribute
string alt = img.GetAttribute("alt");
// Check if the alt text is missing or empty
if (string.IsNullOrWhiteSpace(alt))
{
// Generate simple descriptive alt text using the image filename
string autoAlt = "Image: " + Path.GetFileName(img.Src);
// Add the generated alt text to the image element
img.SetAttribute("alt", autoAlt);
}
}
}
// Save the updated HTML document
document.Save(outputPath);
// Apply background image to heading <h1> with C# and CSS
// Learn more: https://docs.aspose.com/html/net/how-to-articles/how-to-add-image/
// Load the existing HTML document
using (HTMLDocument document = new HTMLDocument(Path.Combine(DataDir, "document-with-h1.html")))
{
// Create a new <style> element
HTMLStyleElement styleElement = (HTMLStyleElement)document.CreateElement("style");
// Define CSS to apply a background image to all <p> elements
string css = "h1 { background-image: url('background.png'); background-repeat: no-repeat; padding: 60px;}";
styleElement.AppendChild(document.CreateTextNode(css));
// Get the <head> element or create one if missing
HTMLElement head = document.QuerySelector("head") as HTMLElement;
if (head == null)
{
head = document.CreateElement("head") as HTMLElement;
document.DocumentElement.InsertBefore(head, document.Body);
}
// Append the <style> element to the <head>
head.AppendChild(styleElement);
// Save the updated HTML document
document.Save(Path.Combine(OutputDir, "add-background-image-to-h1.html"));
}
// Add a background image to HTML using C#
// Learn more: https://docs.aspose.com/html/net/how-to-articles/how-to-add-image/
// Load an existing HTML document
using (HTMLDocument document = new HTMLDocument(Path.Combine(DataDir, "document.html")))
{
// Create a new <style> element
HTMLStyleElement styleElement = (HTMLStyleElement)document.CreateElement("style");
// Define CSS for background image
string css = "body { background-image: url('background.png'); }";
styleElement.AppendChild(document.CreateTextNode(css));
// Get the <head> element or create one if missing
HTMLElement head = document.QuerySelector("head") as HTMLElement;
if (head == null)
{
head = document.CreateElement("head") as HTMLElement;
document.DocumentElement.InsertBefore(head, document.Body);
}
// Append the <style> element to the <head>
head.AppendChild(styleElement);
// Save the updated HTML document
document.Save(Path.Combine(OutputDir, "add-background-image-to-entire-page.html"));
}
// Add background image with CSS in C#
// Learn more: https://docs.aspose.com/html/net/how-to-articles/how-to-add-image/
// Load an existing HTML document
using (HTMLDocument document = new HTMLDocument(Path.Combine(DataDir, "document.html")))
{
// Get the <body> element
HTMLElement body = document.QuerySelector("body") as HTMLElement;
if (body != null)
{
// Set a background image using inline CSS
body.SetAttribute("style", "background-image: url('flower.png');");
}
// Save the updated HTML document
document.Save(Path.Combine(OutputDir, "add-background-image.html"));
}
// Add image to existing HTML using C#
// Learn more: https://docs.aspose.com/html/net/how-to-articles/how-to-add-image/
// Load an existing HTML document
using (HTMLDocument document = new HTMLDocument(Path.Combine(DataDir, "file.html")))
{
// Get all <p> (paragraph) elements
HTMLCollection paragraphs = document.GetElementsByTagName("p");
// Check if there are at least two paragraphs
if (paragraphs.Length >= 2)
{
// Create a new <img> element
var img = document.CreateElement("img");
img.SetAttribute("src", "https://docs.aspose.com/html/images/aspose-html-for-net.png"); // Set image source (URL or local path)
img.SetAttribute("alt", "Aspose.HTML for .NET Product Logo");
img.SetAttribute("width", "128");
img.SetAttribute("height", "128");
// Get the second paragraph
Element secondParagraph = paragraphs[1];
// Insert the image after the second paragraph
secondParagraph.ParentNode.InsertBefore(img, secondParagraph.NextSibling);
}
// Save the updated HTML document
document.Save(Path.Combine(OutputDir, "add-image-after-paragraph.html"), new HTMLSaveOptions());
}
// Add image to HTML using C#
// Learn more: https://docs.aspose.com/html/net/how-to-articles/how-to-add-image/
// Create a new HTML document
using (HTMLDocument document = new HTMLDocument())
{
// Get a reference to the <body> element
HTMLElement body = (HTMLElement)document.GetElementsByTagName("body").First();
// Create an <img> element
var img = document.CreateElement("img");
img.SetAttribute("src", "https://docs.aspose.com/html/images/aspose-html-for-net.png"); // Specify a link URL or local path
img.SetAttribute("alt", "Aspose.HTML for .NET Product Logo");
img.SetAttribute("width", "128"); // Set parameters optionally
img.SetAttribute("height", "128");
// Add the <img> element to the <body>
body.AppendChild(img);
// Save file to a local file system
document.Save(Path.Combine(OutputDir, "add-image.html"), new HTMLSaveOptions());
}
// Change background color with inline CSS in C#
// Learn more: https://docs.aspose.com/html/net/how-to-articles/how-to-change-background-color/
// Prepare output path for document saving
string savePath = Path.Combine(OutputDir, "change-background-color-inline-css.html");
// Prepare path to source HTML file
string documentPath = Path.Combine(DataDir, "file.html");
// Create an instance of an HTML document
HTMLDocument document = new HTMLDocument(documentPath);
// Find the body element to set a style attribute
HTMLElement body = (HTMLElement)document.GetElementsByTagName("body").First();
// Set the style attribute with background-color property
body.Style.BackgroundColor = "#e5f3fd";
// Save the HTML document to a file
document.Save(Path.Combine(savePath));
// Change background color for HTML using internal CSS - C#
// Learn more: https://docs.aspose.com/html/net/how-to-articles/how-to-change-background-color/
// Prepare output path for document saving
string savePath = Path.Combine(OutputDir, "change-background-color-internal-css.html");
// Prepare path to source HTML file
string documentPath = Path.Combine(DataDir, "file.html");
// Create an instance of an HTML document
HTMLDocument document = new HTMLDocument(documentPath);
// Find the body element
HTMLElement body = (HTMLElement)document.GetElementsByTagName("body").First();
// Remove the background-color property from the style attribute
body.Style.RemoveProperty("background-color");
// Create a style element and assign the background-color value for body element
Element style = document.CreateElement("style");
style.TextContent = "body { background-color: rgb(229, 243, 253) }";
// Find the document head element and append style element to the head
Element head = document.GetElementsByTagName("head").First();
head.AppendChild(style);
// Save the HTML document
document.Save(Path.Combine(savePath));
// Convert centimeters to pixels using C#
// Learn more: https://docs.aspose.com/html/net/how-to-articles/
var cm = Unit.FromCentimeters(100);
var px = cm.GetValue(UnitType.Px);
Console.WriteLine(px.ToString("F2"));
// Render HTML to PDF with default RenderingOptions
// Learn more: https://docs.aspose.com/html/net/resize-document/
// Prepare path to a source HTML file
string documentPath = Path.Combine(DataDir, "rendering.html");
// Prepare path for converted file saving
string savePath = Path.Combine(OutputDir, "a4.png");
// Create an instance of the HTMLDocument class
using HTMLDocument document = new HTMLDocument(documentPath);
// Initialize an ImageRenderingOptions object with default options
ImageRenderingOptions opt = new ImageRenderingOptions();
// Create an output rendering device and convert HTML
using ImageDevice device = new ImageDevice(opt, savePath);
document.RenderTo(device);
// Convert inches to pixels using C#
// Learn more: https://docs.aspose.com/html/net/how-to-articles/
var inch = Unit.FromInches(100);
var px = inch.GetValue(UnitType.Px);
Console.WriteLine(px.ToString("F2"));
// Convert pixels to centimeters using C#
// Learn more: https://docs.aspose.com/html/net/how-to-articles/
// Define the number of pixels to convert
var px = Unit.FromPixels(1000);
// Convert pixels to centimeters
var cm = px.GetValue(UnitType.Cm);
// Output the result
Console.WriteLine(cm.ToString("F2"));
// Convert pixels to inches using C#
// Learn more: https://docs.aspose.com/html/net/how-to-articles/
// Define the number of pixels to convert
var px = Unit.FromPixels(800);
// Convert pixels to inches
var inch = px.GetValue(UnitType.In);
// Print the converted value with two decimal places
Console.WriteLine(inch.ToString("F2"));
// Apply background color to elements by class using C#
// Learn more: https://docs.aspose.com/html/net/how-to-articles/how-to-use-css-selector/
// Prepare output path for HTML document saving
string savePath = Path.Combine(OutputDir, "css-selector-color.html");
// Prepare path to source HTML file
string documentPath = Path.Combine(DataDir, "spring.html");
// Create an instance of an HTML document
HTMLDocument document = new HTMLDocument(documentPath);
// Here we create a CSS Selector that extracts all elements whose 'class' attribute equals 'square2'
NodeList elements = document.QuerySelectorAll(".square2");
// Iterate over the resulted list of elements
foreach (HTMLElement element in elements)
{
// Set the style attribute with new background-color property
element.Style.BackgroundColor = "#b0d7fb";
}
// Save the HTML document to a file
document.Save(Path.Combine(savePath));
// Fit HTML to content size when rendering to image in C#
// Learn more: https://docs.aspose.com/html/net/resize-document/
// Prepare path to a source HTML file
string documentPath = Path.Combine(DataDir, "rendering.html");
// Prepare path for converted file saving
string savePath = Path.Combine(OutputDir, "FitPage.png");
// Create an instance of the HTMLDocument class
using HTMLDocument document = new HTMLDocument(documentPath);
// Initialize an ImageRenderingOptions object with custom options. Use FitToContentWidth and FitToContentHeight flags
ImageRenderingOptions opt = new ImageRenderingOptions()
{
PageSetup =
{
PageLayoutOptions = PageLayoutOptions.FitToContentWidth | PageLayoutOptions.FitToContentHeight
},
HorizontalResolution=96,
VerticalResolution=96
};
// Create an output rendering device and convert HTML
using ImageDevice device = new ImageDevice(opt, savePath);
document.RenderTo(device);
// Render HTML to image with width fitting in C#
// Learn more: https://docs.aspose.com/html/net/resize-document/
// Prepare path to a source HTML file
string documentPath = Path.Combine(DataDir, "rendering.html");
// Prepare path for converted file saving
string savePath = Path.Combine(OutputDir, "FitWidth.jpg");
// Create an instance of HTMLDocument class
using HTMLDocument document = new HTMLDocument(documentPath);
// Initialize an ImageRenderingOptions object with custom options. Use the FitToWidestContentWidth flag
ImageRenderingOptions opt = new ImageRenderingOptions(ImageFormat.Jpeg)
{
PageSetup =
{
PageLayoutOptions = PageLayoutOptions.FitToWidestContentWidth
}
};
// Create an output rendering device and convert HTML
using ImageDevice device = new ImageDevice(opt, savePath);
document.RenderTo(device);
// Change background color for HTML paragraph using C#
// Learn more: https://docs.aspose.com/html/net/how-to-articles/how-to-change-background-color/
// Prepare output path for document saving
string savePath = Path.Combine(OutputDir, "change-background-color-p-inline-css.html");
// Prepare path to source HTML file
string documentPath = Path.Combine(DataDir, "file.html");
// Create an instance of an HTML document
HTMLDocument document = new HTMLDocument(documentPath);
// Find the paragraph element to set a style attribute
HTMLElement paragraph = (HTMLElement)document.GetElementsByTagName("p").First();
// Set the style attribute with background-color property
paragraph.Style.BackgroundColor = "#e5f3fd";
// Save the HTML document to a file
document.Save(Path.Combine(savePath));
// Сhange border color for <h1> element using C#
// Learn more: https://docs.aspose.com/html/net/how-to-articles/how-to-change-border-color/
// Prepare an output path for a document saving
string savePath = Path.Combine(OutputDir, "change-border-color.html");
// Prepare path to source HTML file
string documentPath = Path.Combine(DataDir, "file.html");
// Create an instance of an HTML document
HTMLDocument document = new HTMLDocument(documentPath);
// Find the h1 element to set a style attribute
HTMLElement header = (HTMLElement)document.GetElementsByTagName("h1").First();
// Set the style attribute properties
header.Style.Color = "#8B0000";
header.Style.BorderStyle = "solid";
header.Style.BorderColor = "rgb(220,30,100)";
// Save the HTML document to a file
document.Save(Path.Combine(savePath));
// Set different colors for all four borders of HTML element using C#
// Learn more: https://docs.aspose.com/html/net/how-to-articles/how-to-change-border-color/
// Prepare an output path for a document saving
string savePath = Path.Combine(OutputDir, "change-four-border-color.html");
// Prepare path to source HTML file
string documentPath = Path.Combine(DataDir, "change-border-color.html");
// Create an instance of an HTML document
HTMLDocument document = new HTMLDocument(documentPath);
// Find the h1 element to set a style attribute
HTMLElement header = (HTMLElement)document.GetElementsByTagName("h1").First();
// Set the style attribute properties
header.Style.BorderStyle = "solid";
header.Style.BorderColor = "red blue green gray";
// Save the HTML document to a file
document.Save(Path.Combine(savePath));
// Add internal CSS to style HTML in C#
// Learn more: https://docs.aspose.com/html/net/how-to-articles/how-to-change-border-color/
// Prepare an output path for a document saving
string savePath = Path.Combine(OutputDir, "change-border-color-internal-css.html");
// Prepare path to source HTML file
string documentPath = Path.Combine(DataDir, "file.html");
// Create an instance of an HTML document
HTMLDocument document = new HTMLDocument(documentPath);
// Create a style element and assign the color border-style and border-color values for h1 element
Element style = document.CreateElement("style");
style.TextContent = "h1 {color:DarkRed; border-style:solid; border-color:rgb(220,30,100) }";
// Find the document head element and append style element to the head
Element head = document.GetElementsByTagName("head").First();
head.AppendChild(style);
// Save the HTML document to a file
document.Save(Path.Combine(savePath));
// Change HTML paragraph color using C#
// Learn more: https://docs.aspose.com/html/net/how-to-articles/how-to-change-text-color/
// Prepare output path for HTML document saving
string savePath = Path.Combine(OutputDir, "change-paragraph-color-inline-css.html");
// Prepare path to source HTML file
string documentPath = Path.Combine(DataDir, "file.html");
// Create an instance of an HTML document
HTMLDocument document = new HTMLDocument(documentPath);
// Find the first paragraph element to set a style attribute
HTMLElement paragraph = (HTMLElement)document.GetElementsByTagName("p").First();
// Set the style attribute with color property
paragraph.Style.Color = "#8B0000";
// Save the HTML document to a file
document.Save(Path.Combine(savePath));
// Change HTML text color using C#
// Learn more: https://docs.aspose.com/html/net/how-to-articles/how-to-change-text-color/
// Prepare output path for HTML document saving
string savePath = Path.Combine(OutputDir, "change-paragraph-color-internal-css.html");
// Prepare path to source HTML file
string documentPath = Path.Combine(DataDir, "file.html");
// Create an instance of an HTML document
HTMLDocument document = new HTMLDocument(documentPath);
// Create a style element and assign the text color value for all paragraph elements
Element style = document.CreateElement("style");
style.TextContent = "p { color:#8B0000 }";
// Find the document head element and append style element to the head
Element head = document.GetElementsByTagName("head").First();
head.AppendChild(style);
// Save the HTML document to a file
document.Save(Path.Combine(savePath));
// Change table border color using C#
// Learn more: https://docs.aspose.com/html/net/how-to-articles/how-to-change-border-color/
// Prepare an output path for a document saving
string savePath = Path.Combine(OutputDir, "change-table-border-color-inline-css.html");
// Prepare path to source HTML file
string documentPath = Path.Combine(DataDir, "table.html");
// Create an instance of an HTML document
HTMLDocument document = new HTMLDocument(documentPath);
// Create a CSS Selector that selects the first table element
Element element = document.QuerySelector("table");
// Set style attribute with properties for the selected element
element.SetAttribute("style", "border: 2px #0000ff solid");
// Save the HTML document to a file
document.Save(Path.Combine(savePath));
// Change HTML table border color using C#
// Learn more: https://docs.aspose.com/html/net/how-to-articles/how-to-change-border-color/
// Prepare an output path for a document saving
string savePath = Path.Combine(OutputDir, "change-table-border-color-internal-css.html");
// Prepare path to source HTML file
string documentPath = Path.Combine(DataDir, "table.html");
// Create an instance of an HTML document
HTMLDocument document = new HTMLDocument(documentPath);
// Create a style element and assign the color border-style and border-color values for table element
Element style = document.CreateElement("style");
style.TextContent = "table { border-style:solid; border-color:rgb(0, 0, 255) }";
// Find the document head element and append style element to the head
Element head = document.GetElementsByTagName("head").First();
head.AppendChild(style);
// Save the HTML document to a file
document.Save(Path.Combine(savePath));
// Check if HTML body is empty using C#
// Learn more: https://docs.aspose.com/html/net/how-to-articles/how-to-check-if-html-text-content-is-empty/
// Prepare a path to a source HTML file
string inputPath = Path.Combine(DataDir, "file.html");
// Load the HTML document
using (HTMLDocument document = new HTMLDocument(inputPath))
{
// Get the body element
HTMLElement body = document.Body;
// Check if the body element contains any child nodes
if (!string.IsNullOrWhiteSpace(body.TextContent))
Console.WriteLine("Non-empty HTML elements found");
else
Console.WriteLine("No child nodes found in the body element.");
}
// Render HTML to image with small custom page size
// Learn more: https://docs.aspose.com/html/net/resize-document/
// Prepare path to a source HTML file
string documentPath = Path.Combine(DataDir, "rendering.html");
// Prepare path for converted file saving
string savePath = Path.Combine(OutputDir, "FitSmallPage.jpg");
// Initialize HTMLDocument
using HTMLDocument document = new HTMLDocument(documentPath);
// Initialize an ImageRenderingOptions object with custom options. Use FitToWidestContentWidth and FitToContentHeight flags
ImageRenderingOptions opt = new ImageRenderingOptions(ImageFormat.Jpeg)
{
PageSetup =
{
PageLayoutOptions = PageLayoutOptions.FitToWidestContentWidth | PageLayoutOptions.FitToContentHeight,
AnyPage = new Page(new Size(20,20))
}
};
// Create an output rendering device and convert HTML
using ImageDevice device = new ImageDevice(opt, savePath);
document.RenderTo(device);
// Fit HTML to content size when rendering to PDF in C#
// Learn more: https://docs.aspose.com/html/net/resize-document/
// Prepare path to a source HTML file
string documentPath = Path.Combine(DataDir, "rendering.html");
// Prepare path for converted file saving
string savePath = Path.Combine(OutputDir, "FitPage.pdf");
// Initialize HTMLDocument
using HTMLDocument document = new HTMLDocument(documentPath);
// Initialize an PdfRenderingOptions object with custom options. Use FitToContentWidth and FitToContentHeight flags
PdfRenderingOptions opt = new PdfRenderingOptions()
{
PageSetup =
{
PageLayoutOptions = PageLayoutOptions.FitToContentWidth | PageLayoutOptions.FitToContentHeight
}
};
// Create an output rendering device and convert HTML
using PdfDevice device = new PdfDevice(opt, savePath);
document.RenderTo(device);
// How to save a website as a pdf using C#
// Learn more: https://docs.aspose.com/html/net/how-to-articles/
// Set the target webpage URL
string url = "https://docs.aspose.com/html/";
// Define the output path (OutputDir is assumed to exist)
string outputPath = Path.Combine(OutputDir, "website.pdf");
// Load the HTML document from the specified URL
HTMLDocument document = new HTMLDocument(url);
// Configure PDF rendering options
PdfRenderingOptions options = new PdfRenderingOptions();
options.PageSetup.AnyPage = new Page(new Size(1920, 1080));
// Create a PDF rendering device with the defined options and output file
PdfDevice device = new PdfDevice(options, outputPath);
// Initialize the HTML renderer
HtmlRenderer renderer = new HtmlRenderer();
// Render the document to the specified device
renderer.Render(device, document);
// Dispose of resources
renderer.Dispose();
device.Dispose();
document.Dispose();
// Scale HTML content to fixed page size
// Learn more: https://docs.aspose.com/html/net/resize-document/
// Prepare path to a source HTML file
string documentPath = Path.Combine(DataDir, "rendering.html");
// Prepare path for converted file saving
string savePath = Path.Combine(OutputDir, "ScaleSmallPage.png");
// Initialize an HTMLDocument object
using HTMLDocument document = new HTMLDocument(documentPath);
// Initialize an ImageRenderingOptions object and use ScaleToPageWidth and ScaleToPageHeight flags
ImageRenderingOptions opt = new ImageRenderingOptions()
{
PageSetup =
{
PageLayoutOptions = PageLayoutOptions.ScaleToPageWidth | PageLayoutOptions.ScaleToPageHeight,
AnyPage = new Page(new Size(200,200))
}
};
// Create an output rendering device and convert HTML
using ImageDevice device = new ImageDevice(opt, savePath);
document.RenderTo(device);
// Set input value and serialize HTML form element using C#
// Learn more: https://docs.aspose.com/html/net/how-to-serialize-input-value/
string html = @"
<html>
<body>
<div>The new input element value: <input type = ""text"" value=""No"" /></div>
</body>
</html>";
// Create an HTML document from string of code containing an HTMLInputElement
using HTMLDocument doc = new HTMLDocument(html, string.Empty);
// Get all elements with the <input> tag
HTMLCollection inputElements = doc.GetElementsByTagName("input");
// Take the first and only element, in this case, from the resulting collection
HTMLInputElement input = (HTMLInputElement)inputElements[0];
// Set the desired value for this HTML form element
input.Value = "Text";
// Prepare a path to save HTML
string savePath = Path.Combine(OutputDir, "result.html");
// Save the HTML document with SerializeInputValue set to true
doc.Save(savePath, new HTMLSaveOptions { SerializeInputValue = true });
// Set custom font folder for HTML to PNG conversion in C#
// Learn more: https://docs.aspose.com/html/net/how-to-set-font-folder/
// Prepare a path to a source HTML file
string documentPath = Path.Combine(DataDir, "file.html");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "file-output.png");
// Create an instance of the Configuration class
using Configuration configuration = new Configuration();
// Get the IUserAgentService
IUserAgentService userAgentService = configuration.GetService<IUserAgentService>();
// Use the SetFontsLookupFolder() method to set a directory which will act as a new fontsFolder
// Pass "true" as the recursive parameter to use all nested directories
userAgentService.FontsSettings.SetFontsLookupFolder(Path.Combine(DataDir + "font"), true);
// Initialize the HTML document with specified configuration
using (HTMLDocument document = new HTMLDocument(documentPath, configuration))
{
// Convert HTML to Image
Converter.ConvertHTML(document, new ImageSaveOptions(), savePath);
}
// Use custom font folder in HTML to PDF conversion
// Learn more: https://docs.aspose.com/html/net/how-to-set-font-folder/
// Prepare a path to a source HTML file
string documentPath = Path.Combine(DataDir, "file.html");
// Create an instance of Configuration
using Configuration configuration = new Configuration();
// Get the IUserAgentService
IUserAgentService service = configuration.GetService<IUserAgentService>();
// Set a custom font folder path
service.FontsSettings.SetFontsLookupFolder(Path.Combine(DataDir + "fonts"));
// Initialize the HTML document with specified configuration
using (HTMLDocument document = new HTMLDocument(documentPath, configuration))
{
// Convert HTML to PDF
Converter.ConvertHTML(document, new PdfSaveOptions(), Path.Combine(OutputDir, "file-fontsetting.pdf"));
}
// Query and extract XML data using XPath expressions
// Learn more: https://docs.aspose.com/html/net/how-to-articles/how-to-use-xpath-to-select-xml-nodes/
// Create an instance of a document
using (HTMLDocument doc = new HTMLDocument(Path.Combine(DataDir, "cars.xml")))
{
// Select dealers that match XPath expression
IXPathResult dealers = doc.Evaluate("//Dealer[descendant::Car[descendant::Model > 2005 and descendant::Price < 25000]]", doc, doc.CreateNSResolver(doc), XPathResultType.Any, null);
Node dealer;
// Iterate over the selected dealers
while ((dealer = dealers.IterateNext()) != null)
{
// Get and print Dealer name and Telephone
IXPathResult dealerInfo = doc.Evaluate("concat('Dealer name: ', Name/text(), ' Telephone: ', Telephone/text())", dealer, doc.CreateNSResolver(doc), XPathResultType.String, null);
Console.WriteLine(dealerInfo.StringValue);
// Select and print CarID that match XPath expression
IXPathResult carIds = doc.Evaluate(".//Car[descendant::Model > 2005 and descendant::Price < 25000]/@CarID", dealer, doc.CreateNSResolver(doc), XPathResultType.Any, null);
Node carId;
while ((carId = carIds.IterateNext()) != null)
{
Console.WriteLine("Car id: " + carId.TextContent);
}
}
}
// Use XPath to get only links to photos from HTML
// Learn more: https://docs.aspose.com/html/net/how-to-articles/how-to-use-xpath/
// Create an instance of an HTML document
using (HTMLDocument doc = new HTMLDocument(Path.Combine(DataDir, "xpath-image.htm")))
{
// Evaluate the XPath expression
IXPathResult result = doc.Evaluate("//main/div[position() mod 2 = 1]//img[@class = 'photo']", doc, doc.CreateNSResolver(doc), XPathResultType.Any, null);
// Iterate over the resulted nodes and print them to the console
Node node;
while ((node = result.IterateNext()) != null)
{
HTMLImageElement img = (HTMLImageElement)node;
Console.WriteLine(img.Src);
}
}
// Use XPath to select nodes from XML
// Learn more: https://docs.aspose.com/html/net/how-to-articles/how-to-use-xpath-to-select-xml-nodes/
// Create an instance of a document
using (HTMLDocument doc = new HTMLDocument(Path.Combine(DataDir, "cars.xml")))
{
// Select dealers that match XPath expression
IXPathResult dealers = doc.Evaluate("//Dealer[descendant::Car[descendant::Model > 2005 and descendant::Price < 25000]]", doc, doc.CreateNSResolver(doc), XPathResultType.Any, null);
Node dealer;
// Iterate over the selected dealers
while ((dealer = dealers.IterateNext()) != null)
{
Console.WriteLine(dealer.TextContent);
}
}
// Extract HTML content using CSS selector
// Learn more: https://docs.aspose.com/html/net/how-to-articles/how-to-use-css-selector/
// Prepare path to source HTML file
string documentPath = Path.Combine(DataDir, "queryselector.html");
// Create an instance of an HTML document
HTMLDocument document = new HTMLDocument(documentPath);
// Here we create a CSS Selector that extracts the first paragraph element
Element element = document.QuerySelector("p");
// Print content of the first paragraph
Console.WriteLine(element.InnerHTML);
// output: The QuerySelector() method returns the first element in the document that matches the specified selector.
// Set style attribute with properties for the selected element
element.SetAttribute("style", "color:rgb(50,150,200); background-color:#e1f0fe;");
// Save the HTML document to a file
document.Save(Path.Combine(OutputDir, "queryselector-p.html"));
// Select and style HTML element with C# CSS selector
// Learn more: https://docs.aspose.com/html/net/how-to-articles/how-to-use-css-selector/
// Prepare output path for HTML document saving
string savePath = Path.Combine(OutputDir, "css-celector-style.html");
// Prepare path to source HTML file
string documentPath = Path.Combine(DataDir, "nature.html");
// Create an instance of an HTML document
HTMLDocument document = new HTMLDocument(documentPath);
// Create a CSS Selector that selects <div> element that is the last child of its parent
Element element = document.QuerySelector("div:last-child");
// Set the style attribute with properties for the selected element
element.SetAttribute("style", "color:rgb(50,150,200); background-color:#e1f0fe; text-align:center");
// Save the HTML document to a file
document.Save(Path.Combine(savePath));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment