### Install Aspose.HTML via NuGet Package Manager Console Source: https://github.com/aspose-html/aspose.html-for-.net/blob/master/docs/installation.md Installs the Aspose.HTML package using the Package Manager Console in Visual Studio. This command fetches the latest version and all necessary dependencies. ```csharp Install-Package Aspose.HTML ``` -------------------------------- ### Install Aspose.HTML via .NET CLI Source: https://github.com/aspose-html/aspose.html-for-.net/blob/master/docs/installation.md Adds the Aspose.HTML package to your project using the .NET Command Line Interface. This is a convenient way to manage packages across different development environments. ```bash dotnet add package Aspose.HTML ``` -------------------------------- ### Install Aspose.HTML for .NET NuGet Package Source: https://github.com/aspose-html/aspose.html-for-.net/blob/master/README.md Installs the Aspose.HTML for .NET NuGet package using the Package Manager Console in Visual Studio. This is the primary way to add the library to your .NET project. ```csharp Install-Package Aspose.Html ``` -------------------------------- ### Draw Text on Canvas using Aspose.HTML for .NET Source: https://github.com/aspose-html/aspose.html-for-.net/blob/master/Examples/data/canvas.html This snippet demonstrates how to get a canvas element, obtain its 2D rendering context, set the font and fill style, and then draw "Hello, World!" text onto the canvas. It requires the Aspose.HTML for .NET library. ```javascript var c = document.getElementById("myCanvas"); var context = c.getContext("2d"); context.font = "30px Arial"; context.fillStyle = "red"; context.fillText("Hello, World!",15,60); ``` -------------------------------- ### Custom Stream Provider for HTML Conversion in C# Source: https://context7.com/aspose-html/aspose.html-for-.net/llms.txt Illustrates how to implement a custom stream provider (ICreateStreamProvider) for handling output during HTML conversion. This example shows a MemoryStreamProvider for in-memory operations and its usage with PdfSaveOptions and ImageSaveOptions. It allows flexible output management, such as writing to memory or cloud storage. ```csharp using Aspose.Html; using Aspose.Html.Converters; using Aspose.Html.IO; using Aspose.Html.Saving; using System.Collections.Generic; using System.IO; using System.Linq; // Custom memory stream provider implementation public class MemoryStreamProvider : ICreateStreamProvider { public List Streams { get; } = new List(); public Stream GetStream(string name, string extension) { MemoryStream stream = new MemoryStream(); Streams.Add(stream); return stream; } public Stream GetStream(string name, string extension, int page) { MemoryStream stream = new MemoryStream(); Streams.Add(stream); return stream; } public void ReleaseStream(Stream stream) { } public void Dispose() { foreach (MemoryStream stream in Streams) stream.Dispose(); } } // Usage example using (MemoryStreamProvider provider = new MemoryStreamProvider()) { using (HTMLDocument document = new HTMLDocument("

Stream Output!

", ".")) { // Convert HTML to PDF using the stream provider Converter.ConvertHTML(document, new PdfSaveOptions(), provider); // Access the result from memory MemoryStream pdfStream = provider.Streams.First(); pdfStream.Seek(0, SeekOrigin.Begin); // Write to file or send to cloud storage using (FileStream fs = File.Create("stream-output.pdf")) { pdfStream.CopyTo(fs); } Console.WriteLine($"PDF size: {pdfStream.Length} bytes"); } } // Convert HTML to multiple PNG pages using stream provider using (MemoryStreamProvider provider = new MemoryStreamProvider()) { using (HTMLDocument document = new HTMLDocument("multi-page.html")) { Converter.ConvertHTML(document, new ImageSaveOptions(ImageFormat.Png), provider); for (int i = 0; i < provider.Streams.Count; i++) { MemoryStream pageStream = provider.Streams[i]; pageStream.Seek(0, SeekOrigin.Begin); using (FileStream fs = File.Create($"page-{i + 1}.png")) { pageStream.CopyTo(fs); } } } } ``` -------------------------------- ### Load HTML from URL and Convert to PDF in C# Source: https://github.com/aspose-html/aspose.html-for-.net/blob/master/docs/basic-usage.md Demonstrates how to load HTML content directly from a web page URL and convert it into a PDF document using Aspose.HTML for .NET. This is useful for archiving web pages or generating reports from online content. ```csharp using Aspose.Html; using Aspose.Html.Converters; using Aspose.Html.Saving; // Load HTML document from a URL using (HTMLDocument document = new HTMLDocument("https://docs.aspose.com/html/net/")) { // Convert to PDF Converter.ConvertHTML(document, new PdfSaveOptions(), "webpage.pdf"); } ``` -------------------------------- ### Convert MHTML to PDF in C# Source: https://github.com/aspose-html/aspose.html-for-.net/blob/master/docs/basic-usage.md Shows how to convert an existing MHTML file into a PDF document using Aspose.HTML for .NET. This is applicable for archiving emails, web page snapshots, or complex documents that include images and CSS. ```csharp using Aspose.Html; using Aspose.Html.Converters; using Aspose.Html.Saving; // Open an existing MHTML file for reading using FileStream stream = File.OpenRead("document.mht"); // Convert MHTML to PDF Converter.ConvertMHTML(stream, new PdfSaveOptions(), "convert-mhtml-to.pdf"); ``` -------------------------------- ### Add Table to HTML Document in C# Source: https://github.com/aspose-html/aspose.html-for-.net/blob/master/docs/basic-usage.md Illustrates how to create dynamic HTML content programmatically by adding a table element to an HTML document using the DOM API in Aspose.HTML for .NET. The resulting HTML file is then saved. ```csharp using Aspose.Html; using System.IO; // Create new HTML document using (HTMLDocument document = new HTMLDocument()) { HTMLElement body = document.Body; // Create a table element HTMLTableElement table = (HTMLTableElement)document.CreateElement("table"); table.Border = "2"; table.Style.Border = "2px #ff0000 dotted"; document.Body.AppendChild(table); HTMLTableRowElement row = (HTMLTableRowElement)document.CreateElement("tr"); table.AppendChild(row); HTMLTableCellElement cell = (HTMLTableCellElement)document.CreateElement("td"); cell.InnerHTML = "Hello Table!"; row.AppendChild(cell); // Prepare a path for resulting file saving string savePath = Path.Combine(OutputDir, "add-simple-table.html"); document.Save(savePath); } ``` -------------------------------- ### Apply CSS Styles to HTML Elements using Aspose.HTML for .NET Source: https://github.com/aspose-html/aspose.html-for-.net/blob/master/Examples/data/color-contrast.html This snippet shows how to apply CSS styles to HTML elements, including font properties, text alignment, padding, border-radius, and width. It defines styles for a general 'div' element and specific classes '.bad' and '.good' for contrast. ```css div { font-family: sans-serif; text-align: center; font-weight: bold; text-align: center; padding: 10px; border-radius: 15px; width: 300px; margin: auto; } .bad { background-color: #045DE2; font-size: 16px; } .good { background-color: #f0f6ff; } ``` -------------------------------- ### Create, Load, and Save HTML Documents in C# Source: https://context7.com/aspose-html/aspose.html-for-.net/llms.txt Demonstrates how to create HTML documents from scratch, load them from strings, files, URLs, or streams, and save them. This covers the fundamental document handling capabilities of the Aspose.HTML library. ```csharp using Aspose.Html; using System.IO; // Create an empty HTML document using (HTMLDocument doc = new HTMLDocument()) { doc.Save("empty-document.html"); } // Create HTML document from a string string htmlCode = "

Hello, World!

Welcome to Aspose.HTML

"; using (HTMLDocument doc = new HTMLDocument(htmlCode, ".")) { doc.Save("from-string.html"); } // Load HTML document from a file using (HTMLDocument doc = new HTMLDocument("input.html")) { Console.WriteLine(doc.DocumentElement.OuterHTML); } // Load HTML document from a URL using (HTMLDocument doc = new HTMLDocument("https://example.com")) { Console.WriteLine(doc.Title); } // Load HTML document from a stream using (MemoryStream stream = new MemoryStream()) using (StreamWriter sw = new StreamWriter(stream)) { sw.Write("

Hello from stream!

"); sw.Flush(); stream.Seek(0, SeekOrigin.Begin); using (HTMLDocument doc = new HTMLDocument(stream, ".")) { doc.Save("from-stream.html"); } } ``` -------------------------------- ### Render HTML to PDF with Custom Devices in C# Source: https://context7.com/aspose-html/aspose.html-for-.net/llms.txt Demonstrates how to render an HTML document to a PDF file using the PdfDevice. This includes creating styled HTML content and rendering it directly or from an existing HTML file. It utilizes the Aspose.Html library for document manipulation and rendering. ```csharp using Aspose.Html; using Aspose.Html.Dom; using Aspose.Html.Rendering.Pdf; using System.Linq; // Create HTML document with styled content using (HTMLDocument document = new HTMLDocument()) { // Add CSS styles Element style = document.CreateElement("style"); style.TextContent = ".highlight { color: green; font-size: 24px; }"; Element head = document.GetElementsByTagName("head").First(); head.AppendChild(style); // Add content HTMLParagraphElement p = (HTMLParagraphElement)document.CreateElement("p"); p.ClassName = "highlight"; p.AppendChild(document.CreateTextNode("Rendered with PdfDevice!")); document.Body.AppendChild(p); // Save HTML document.Save("styled-document.html"); // Render directly to PDF using PdfDevice using (PdfDevice device = new PdfDevice("rendered-output.pdf")) { document.RenderTo(device); } } // Render from existing HTML file using (HTMLDocument document = new HTMLDocument("input.html")) { // Create PDF device with custom output path using (PdfDevice device = new PdfDevice(new PdfRenderingOptions(), "custom-render.pdf")) { document.RenderTo(device); } } ``` -------------------------------- ### Populate HTML Templates with Data using Aspose.HTML for .NET Source: https://context7.com/aspose-html/aspose.html-for-.net/llms.txt This snippet shows how to use Aspose.HTML for .NET to populate HTML templates with data from JSON or XML sources. It covers creating templates, providing data, and converting them into output HTML files. Dependencies include Aspose.Html and System.IO. ```csharp using Aspose.Html; using Aspose.Html.Converters; using Aspose.Html.Loading; using System.IO; // Create template and JSON data string template = @"
PersonAddress
{{FirstName}} {{LastName}} {{Address.Street}} {{Address.Number}}, {{Address.City}}
"; File.WriteAllText("template.html", template); string jsonData = @"{ "FirstName": "John", "LastName": "Doe", "Address": { "City": "Dallas", "Street": "Austin rd.", "Number": "200" } }"; File.WriteAllText("data.json", jsonData); // Convert template with JSON data Converter.ConvertTemplate( "template.html", new TemplateData("data.json"), new TemplateLoadOptions(), "output.html"); // Convert template with XML data string xmlData = "JaneSmith"; using (HTMLDocument doc = Converter.ConvertTemplate( "

Hello, {{FirstName}} {{LastName}}!

", string.Empty, new TemplateData(new TemplateContentOptions(xmlData, TemplateContent.XML)), new TemplateLoadOptions())) { doc.Save("xml-template-output.html"); } // Template with attribute control (checkbox example) string checkboxTemplate = ""; string checkedData = "checked"; using (HTMLDocument doc = Converter.ConvertTemplate( checkboxTemplate, string.Empty, new TemplateData(new TemplateContentOptions(checkedData, TemplateContent.XML)), new TemplateLoadOptions())) { HTMLInputElement input = (HTMLInputElement)doc.GetElementsByTagName("input")[0]; Console.WriteLine($"Checkbox is checked: {input.Checked}"); // True doc.Save("checked-checkbox.html"); } ``` -------------------------------- ### Convert HTML to PDF using Aspose.HTML for .NET Source: https://context7.com/aspose-html/aspose.html-for-.net/llms.txt This snippet demonstrates how to convert HTML content to PDF format using Aspose.HTML for .NET. It covers simple one-line conversions, conversions with custom page settings, metadata, encryption, and stream output. Dependencies include the Aspose.HTML library. ```csharp using Aspose.Html; using Aspose.Html.Converters; using Aspose.Html.Drawing; using Aspose.Html.Rendering.Pdf.Encryption; using Aspose.Html.Saving; using System.IO; // Simple one-line conversion Converter.ConvertHTML("

Hello PDF!

", ".", new PdfSaveOptions(), "simple.pdf"); // Convert from file with custom options using (HTMLDocument document = new HTMLDocument("input.html")) { PdfSaveOptions options = new PdfSaveOptions { HorizontalResolution = 200, VerticalResolution = 200, BackgroundColor = System.Drawing.Color.White, JpegQuality = 100, DocumentInfo = { Title = "My Document", Author = "Aspose", Subject = "HTML to PDF", Keywords = "conversion, PDF, HTML" } }; // Custom page size and margins options.PageSetup.AnyPage = new Page( new Aspose.Html.Drawing.Size(Length.FromInches(8.5f), Length.FromInches(11f)), new Margin(30, 20, 30, 20) ); Converter.ConvertHTML(document, options, "custom-output.pdf"); } // Convert from URL using (HTMLDocument document = new HTMLDocument("https://docs.aspose.com/html/net/")) { Converter.ConvertHTML(document, new PdfSaveOptions(), "webpage.pdf"); } // Convert with password protection using (HTMLDocument document = new HTMLDocument("confidential.html")) { PdfSaveOptions options = new PdfSaveOptions { Encryption = new PdfEncryptionInfo( ownerPassword: "owner123", userPassword: "user123", permissions: PdfPermissions.PrintDocument | PdfPermissions.ExtractContent, encryptionAlgorithm: PdfEncryptionAlgorithm.RC4_128) }; Converter.ConvertHTML(document, options, "protected.pdf"); } ``` -------------------------------- ### Convert HTML to Images (PNG, JPG, BMP, TIFF, GIF) using Aspose.HTML for .NET Source: https://context7.com/aspose-html/aspose.html-for-.net/llms.txt This section shows how to render HTML documents into various image formats like PNG, JPG, BMP, TIFF, and GIF using Aspose.HTML for .NET. It includes options for setting resolution, background color, and antialiasing. The Aspose.HTML library is required. ```csharp using Aspose.Html; using Aspose.Html.Converters; using Aspose.Html.Rendering.Image; using Aspose.Html.Saving; using System.IO; // Simple one-line conversion to PNG Converter.ConvertHTML("

Hello Image!

", ".", new ImageSaveOptions(), "output.png"); // Convert HTML file to PNG with custom options using (HTMLDocument document = new HTMLDocument("input.html")) { ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Png) { HorizontalResolution = 300, VerticalResolution = 300, BackgroundColor = System.Drawing.Color.White, UseAntialiasing = true }; Converter.ConvertHTML(document, options, "high-quality.png"); } // Convert to JPEG using (HTMLDocument document = new HTMLDocument("input.html")) { ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Jpeg) { HorizontalResolution = 150, VerticalResolution = 150 }; Converter.ConvertHTML(document, options, "output.jpg"); } // Convert to BMP Converter.ConvertHTML("input.html", new ImageSaveOptions(ImageFormat.Bmp), "output.bmp"); // Convert to TIFF (multi-page support) Converter.ConvertHTML("input.html", new ImageSaveOptions(ImageFormat.Tiff), "output.tiff"); // Convert to GIF Converter.ConvertHTML("input.html", new ImageSaveOptions(ImageFormat.Gif), "output.gif"); ``` -------------------------------- ### Convert HTML to BMP using Aspose.HTML for .NET Source: https://github.com/aspose-html/aspose.html-for-.net/blob/master/Examples/data/bmp.html Demonstrates how to convert an HTML document to a BMP image format using the Aspose.HTML for .NET library. This process involves loading an HTML file and then rendering it to the desired image format. ```csharp using Aspose.Html; using Aspose.Html.Converters; using Aspose.Html.Saving; public class ConvertHtmlToBmp { public static void Main(string[] args) { // Load HTML document from a file using (var document = new HtmlDocument(new HtmlLoadOptions("input.html"))) { // Create an instance of ImageSaveOptions for BMP format var options = new ImageSaveOptions(ImageFormat.Bmp); // Convert HTML to BMP Converter.ConvertHTML(document.Content, options, "output.bmp"); } System.Console.WriteLine("HTML converted to BMP successfully."); } } ``` -------------------------------- ### Convert MHTML to PDF, Images, and DOCX using Aspose.HTML for .NET Source: https://context7.com/aspose-html/aspose.html-for-.net/llms.txt Convert MHTML web archive files to PDF, image formats (like PNG), and DOCX using Aspose.HTML for .NET. Preserves all embedded resources and allows for options like background color and JPEG quality. Requires Aspose.HTML library. ```csharp using Aspose.Html.Converters; using Aspose.Html.Saving; using System.IO; // Convert MHTML to PDF using (FileStream stream = File.OpenRead("document.mht")) { Converter.ConvertMHTML(stream, new PdfSaveOptions(), "document.pdf"); } // Convert MHTML to PDF with options using (FileStream stream = File.OpenRead("archive.mhtml")) { PdfSaveOptions options = new PdfSaveOptions { BackgroundColor = System.Drawing.Color.White, JpegQuality = 90 }; Converter.ConvertMHTML(stream, options, "archive.pdf"); } // Convert MHTML to PNG using (FileStream stream = File.OpenRead("webpage.mht")) { Converter.ConvertMHTML(stream, new ImageSaveOptions(ImageFormat.Png), "webpage.png"); } // Convert MHTML to DOCX using (FileStream stream = File.OpenRead("document.mhtml")) { Converter.ConvertMHTML(stream, new DocSaveOptions(), "document.docx"); } ``` -------------------------------- ### Navigate HTML with XPath, CSS Selectors, and DOM Traversal in C# Source: https://context7.com/aspose-html/aspose.html-for-.net/llms.txt This snippet demonstrates how to query and extract data from HTML documents using XPath expressions, CSS selectors, and DOM traversal in C#. It utilizes the Aspose.HTML library and shows how to find elements, iterate through results, and use a custom filter for specific node types like images. ```csharp using Aspose.Html; using Aspose.Html.Dom; using Aspose.Html.Dom.Traversal; using Aspose.Html.Dom.Traversal.Filters; using Aspose.Html.Dom.XPath; using System; string htmlCode = @"
Hello,

World!

Image 1 Image 2
"; using (HTMLDocument document = new HTMLDocument(htmlCode, ".")) { // XPath query - select all spans inside elements with class 'happy' IXPathResult result = document.Evaluate( "//*[@class='happy']//span", document, null, XPathResultType.Any, null); Console.WriteLine("XPath Results:"); for (Node node; (node = result.IterateNext()) != null;) { Console.WriteLine($" {node.TextContent}"); } // CSS Selector - same query using QuerySelectorAll Console.WriteLine("\nCSS Selector Results:"); var elements = document.QuerySelectorAll(".happy span"); foreach (HTMLElement element in elements) { Console.WriteLine($" {element.InnerHTML}"); } // DOM Navigation Console.WriteLine("\nDOM Navigation:"); Node firstChild = document.Body.FirstChild; Console.WriteLine($"First child text: {firstChild.TextContent?.Trim()}"); // TreeWalker with custom filter for images using (ITreeWalker walker = document.CreateTreeWalker(document, NodeFilter.SHOW_ALL, new ImageFilter())) { Console.WriteLine("\nImages found:"); while (walker.NextNode() != null) { HTMLImageElement img = (HTMLImageElement)walker.CurrentNode; Console.WriteLine($" src: {img.Src}, alt: {img.Alt}"); } } } // Custom node filter for images class ImageFilter : NodeFilter { public override short AcceptNode(Node n) { return string.Equals("img", n.LocalName, StringComparison.OrdinalIgnoreCase) ? FILTER_ACCEPT : FILTER_SKIP; } } ``` -------------------------------- ### Convert Markdown to HTML using Aspose.HTML for .NET Source: https://context7.com/aspose-html/aspose.html-for-.net/llms.txt Convert Markdown files or strings to HTML documents using Aspose.HTML for .NET. Allows for custom styling and DOM manipulation after conversion. Requires Aspose.HTML library. ```csharp using Aspose.Html; using Aspose.Html.Converters; using System.IO; // Simple Markdown to HTML conversion string markdownContent = "### Hello, World!\n[Visit Aspose](https://www.aspose.com/)"; File.WriteAllText("document.md", markdownContent); Converter.ConvertMarkdown("document.md", "document.html"); // Convert Markdown file to HTML Converter.ConvertMarkdown("readme.md", "readme.html"); // Convert Markdown string and add custom CSS string markdown = "# Title\n\nThis is **bold** and *italic* text.\n\n- Item 1\n- Item 2"; using (MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(markdown))) { HTMLDocument document = Converter.ConvertMarkdown(stream, ""); // Add custom styles HTMLHeadElement head = document.QuerySelector("head") as HTMLHeadElement; if (head == null) { head = document.CreateElement("head") as HTMLHeadElement; document.DocumentElement.InsertBefore(head, document.Body); } HTMLStyleElement style = document.CreateElement("style") as HTMLStyleElement; style.TextContent = @" body { font-family: Arial, sans-serif; max-width: 800px; margin: auto; padding: 20px; } h1 { color: #333; } code { background-color: #f4f4f4; padding: 2px 6px; } "; head.AppendChild(style); document.Save("styled-markdown.html"); } ``` -------------------------------- ### Monitor DOM Changes with MutationObserver in Aspose.HTML for .NET Source: https://context7.com/aspose-html/aspose.html-for-.net/llms.txt This C# snippet demonstrates how to use the MutationObserver API in Aspose.HTML for .NET to detect and respond to DOM modifications in real-time. It shows how to configure the observer for various changes like node additions/removals and attribute changes, and how to handle these events. Dependencies include Aspose.Html and System. ```csharp using Aspose.Html; using Aspose.Html.Dom; using Aspose.Html.Dom.Mutations; using System; using (HTMLDocument document = new HTMLDocument()) { // Create a mutation observer with callback MutationObserver observer = new MutationObserver((mutations, obs) => { foreach (MutationRecord record in mutations) { // Handle added nodes foreach (Node node in record.AddedNodes) { Console.WriteLine($"Added: {node.NodeName} - {node.TextContent}"); } // Handle removed nodes foreach (Node node in record.RemovedNodes) { Console.WriteLine($"Removed: {node.NodeName}"); } // Handle attribute changes if (record.Type == "attributes") { Console.WriteLine($"Attribute '{record.AttributeName}' changed on {record.Target.NodeName}"); } } }); // Configure observer options MutationObserverInit config = new MutationObserverInit { ChildList = true, // Watch for child additions/removals Subtree = true, // Watch all descendants CharacterData = true, // Watch text content changes Attributes = true // Watch attribute changes }; // Start observing the body element observer.Observe(document.Body, config); // Make DOM changes that will trigger the observer Element p = document.CreateElement("p"); document.Body.AppendChild(p); // Triggers: Added P Text text = document.CreateTextNode("Hello, World"); p.AppendChild(text); // Triggers: Added #text p.SetAttribute("class", "greeting"); // Triggers: Attribute 'class' changed // Disconnect observer when done observer.Disconnect(); } ``` -------------------------------- ### Convert EPUB to PDF and Images using Aspose.HTML for .NET Source: https://context7.com/aspose-html/aspose.html-for-.net/llms.txt Convert EPUB e-book files to PDF and image formats using Aspose.HTML for .NET. Supports customizable page settings and output options for both PDF and image conversions. Requires Aspose.HTML library. ```csharp using Aspose.Html.Converters; using Aspose.Html.Drawing; using Aspose.Html.Saving; using System.IO; // Simple EPUB to PDF conversion using (FileStream stream = File.OpenRead("ebook.epub")) { Converter.ConvertEPUB(stream, new PdfSaveOptions(), "ebook.pdf"); } // Convert EPUB to PDF with custom page size using (FileStream stream = File.OpenRead("ebook.epub")) { PdfSaveOptions options = new PdfSaveOptions() { PageSetup = { AnyPage = new Page() { Size = new Aspose.Html.Drawing.Size(Length.FromPixels(1000), Length.FromPixels(1000)) } }, BackgroundColor = System.Drawing.Color.White }; Converter.ConvertEPUB(stream, options, "custom-ebook.pdf"); } // Convert EPUB from file path Converter.ConvertEPUB("input.epub", new PdfSaveOptions(), "output.pdf"); // Convert EPUB to PNG images using (FileStream stream = File.OpenRead("ebook.epub")) { Converter.ConvertEPUB(stream, new ImageSaveOptions(ImageFormat.Png), "ebook-page.png"); } // Convert EPUB to JPEG using (FileStream stream = File.OpenRead("ebook.epub")) { Converter.ConvertEPUB(stream, new ImageSaveOptions(ImageFormat.Jpeg), "ebook-page.jpg"); } ``` -------------------------------- ### Manipulate and Edit HTML DOM in C# Source: https://context7.com/aspose-html/aspose.html-for-.net/llms.txt Illustrates how to navigate, create, modify, and remove HTML elements using the DOM API. This includes working with attributes, styles, text content, and internal CSS. ```csharp using Aspose.Html; using Aspose.Html.Dom; using System.Linq; using (HTMLDocument document = new HTMLDocument()) { HTMLElement body = document.Body; // Create and configure a paragraph element HTMLParagraphElement p = (HTMLParagraphElement)document.CreateElement("p"); p.SetAttribute("id", "my-paragraph"); p.SetAttribute("class", "content"); // Create and append text node Text text = document.CreateTextNode("Hello, Aspose.HTML!"); p.AppendChild(text); body.AppendChild(p); // Create a styled heading HTMLHeadingElement h1 = (HTMLHeadingElement)document.CreateElement("h1"); h1.TextContent = "Document Title"; body.InsertBefore(h1, p); // Add internal CSS styles Element style = document.CreateElement("style"); style.TextContent = ".content { color: blue; font-size: 16px; }"; Element head = document.GetElementsByTagName("head").First(); head.AppendChild(style); // Modify inline styles p.Style.FontFamily = "Arial, sans-serif"; p.Style.MarginTop = "20px"; // Set innerHTML body.InnerHTML += "

Footer content

"; document.Save("edited-document.html"); Console.WriteLine(document.DocumentElement.OuterHTML); } ``` -------------------------------- ### Convert SVG to Images and PDF using Aspose.HTML for .NET Source: https://context7.com/aspose-html/aspose.html-for-.net/llms.txt This code demonstrates converting Scalable Vector Graphics (SVG) to various formats including PNG, PDF, and JPEG using Aspose.HTML for .NET. It supports inline SVG code, SVG files, and offers customization for resolution, background color, and antialiasing. The Aspose.HTML library is a prerequisite. ```csharp using Aspose.Html.Converters; using Aspose.Html.Dom.Svg; using Aspose.Html.Saving; using System.IO; // Convert inline SVG code to PNG string svgCode = "" + "" + ""; Converter.ConvertSVG(svgCode, ".", new ImageSaveOptions(), "circle.png"); // Convert SVG file to PNG with custom settings using (SVGDocument document = new SVGDocument("graphic.svg")) { ImageSaveOptions options = new ImageSaveOptions() { HorizontalResolution = 200, VerticalResolution = 200, BackgroundColor = System.Drawing.Color.AliceBlue, UseAntialiasing = true }; Converter.ConvertSVG(document, options, "graphic.png"); } // Convert SVG to PDF Converter.ConvertSVG("shapes.svg", new PdfSaveOptions(), "shapes.pdf"); // Convert SVG to JPEG Converter.ConvertSVG("icon.svg", new ImageSaveOptions(ImageFormat.Jpeg), "icon.jpg"); // Load SVG from string and output using (SVGDocument document = new SVGDocument("", ".")) { Console.WriteLine(document.DocumentElement.OuterHTML); } ``` -------------------------------- ### Convert HTML to PDF using C# Source: https://github.com/aspose-html/aspose.html-for-.net/blob/master/README.md Converts an HTML string to a PDF document using a single line of C# code. This demonstrates the simplest method for transforming HTML content into a high-quality PDF with Aspose.HTML for .NET. ```csharp using Aspose.Html.Converters; using Aspose.Html.Saving; // Convert HTML to PDF using C# Converter.ConvertHTML(@"

Convert HTML to PDF!

", ".", new PdfSaveOptions(), "convert-with-single-line.pdf"); ``` -------------------------------- ### QuerySelector() Method Source: https://github.com/aspose-html/aspose.html-for-.net/blob/master/Examples/data/queryselector.html The QuerySelector() method returns the first element in the document that matches the specified CSS selector. ```APIDOC ## QuerySelector() Method ### Description Returns the first element in the document that matches the specified selector. ### Method Not applicable (this is a method description, not an endpoint). ### Endpoint Not applicable. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example Not applicable. ### Response #### Success Response (200) An `Element` object representing the first matching element, or `null` if no match is found. #### Response Example ```json { "example": "An Element object or null" } ``` ``` -------------------------------- ### Update Aspose.HTML for .NET NuGet Package Source: https://github.com/aspose-html/aspose.html-for-.net/blob/master/README.md Updates the existing Aspose.HTML for .NET NuGet package to the latest version via the Package Manager Console in Visual Studio. Ensures you have the most recent features and bug fixes. ```csharp Update-Package Aspose.Html ``` -------------------------------- ### Edit HTML Document using DOM Tree in C# Source: https://github.com/aspose-html/aspose.html-for-.net/blob/master/README.md This C# snippet demonstrates how to programmatically create and manipulate HTML elements using the DOM (Document Object Model) with Aspose.HTML for .NET. It shows the creation of a paragraph element, setting its ID attribute, adding text content, and appending it to the document's body before saving the result. ```csharp using Aspose.Html; using Aspose.Html.Dom.Elements; using Aspose.Html.Dom.Text; using System.IO; // ... (assuming OutputDir is defined elsewhere) // Create an instance of an HTML document using (HTMLDocument document = new HTMLDocument()) { // Get the body element HTMLElement body = document.Body; // Create a paragraph element HTMLParagraphElement p = (HTMLParagraphElement)document.CreateElement("p"); // Set a custom attribute for the paragraph p.SetAttribute("id", "my-paragraph"); // Create a text node with content Text text = document.CreateTextNode("my first paragraph"); // Attach the text node to the paragraph p.AppendChild(text); // Attach the paragraph element to the document body body.AppendChild(p); // Define the output path and save the HTML document string outPath = Path.Combine(OutputDir, "edit-document-tree.html"); document.Save(outPath); } ``` -------------------------------- ### Extract Data from HTML Tables to JSON in C# Source: https://context7.com/aspose-html/aspose.html-for-.net/llms.txt This C# code snippet demonstrates how to scrape and extract structured data, specifically links, from HTML tables using the Aspose.HTML library. It loads an HTML document, iterates through tables, extracts link information, and then serializes the extracted data into a JSON file. ```csharp using Aspose.Html; using Aspose.Html.Collections; using Aspose.Html.Dom; using System; using System.Collections.Generic; using System.IO; using System.Text.Json; // Load HTML document from URL using (HTMLDocument document = new HTMLDocument("https://example.com/data-table.html")) { // Get all table elements HTMLCollection tables = document.GetElementsByTagName("table"); List> extractedData = new List>(); for (int t = 0; t < tables.Length; t++) { HTMLElement table = tables[t] as HTMLElement; if (table == null) continue; // Extract all links from the table HTMLCollection links = table.GetElementsByTagName("a"); for (int i = 0; i < links.Length; i++) { Element link = links[i]; string href = link.GetAttribute("href"); string text = link.TextContent?.Trim() ?? string.Empty; if (!string.IsNullOrEmpty(href)) { extractedData.Add(new Dictionary { { "text", text }, { "href", href } }); } } // Extract table rows and cells HTMLCollection rows = table.GetElementsByTagName("tr"); for (int r = 0; r < rows.Length; r++) { HTMLElement row = rows[r] as HTMLElement; HTMLCollection cells = row.GetElementsByTagName("td"); for (int c = 0; c < cells.Length; c++) { Console.WriteLine($"Row {r}, Cell {c}: {cells[c].TextContent?.Trim()}"); } } } // Serialize to JSON JsonSerializerOptions options = new JsonSerializerOptions { WriteIndented = true }; string json = JsonSerializer.Serialize(extractedData, options); File.WriteAllText("extracted-links.json", json); Console.WriteLine($"Extracted {extractedData.Count} links"); } ``` -------------------------------- ### Convert SVG to PNG using C# Source: https://github.com/aspose-html/aspose.html-for-.net/blob/master/README.md Converts inline SVG code into a PNG image programmatically. This is useful for generating charts, icons, and dynamic graphics within .NET applications. ```csharp using Aspose.Html.Converters; using Aspose.Html.Saving; // Prepare SVG code string code = ""; // Prepare a path to save the converted file string savePath = Path.Combine(OutputDir, "circle.png"); // Create an instance of the ImageSaveOptions class ImageSaveOptions options = new ImageSaveOptions(); // Convert SVG to PNG Converter.ConvertSVG(code, ".", options, savePath); ``` -------------------------------- ### Define CSS for Drawing Shapes Source: https://github.com/aspose-html/aspose.html-for-.net/blob/master/Examples/data/drawing.html This CSS code defines styles for various elements to create visual shapes like squares and circles. It uses properties like margin, height, width, background-color, and border-radius to achieve the desired appearance. These styles can be applied to HTML elements to render them on a page. ```css .square1 { margin-left: 50px; margin-top: -170px; height: 80px; width: 80px; background-color: #c4456d; border-radius: 50%; //border:12px solid #c4456d; } .square2 { margin-left: 90px; margin-top: 0px; height: 60px; width: 60px; background-color:#fd6696; border-radius: 50% ; } .square3 { margin-left: 155px; margin-top: -20px; height:40px; width: 40px; background-color:#ffb1ca; border-radius: 50%; } .circle { margin-left: 440px; margin-top: -115px; height:30px; width: 30px; background-color: #6dc6bf; border-radius: 50% ; } .frame{ margin-top:100px; margin-left: 150px; font-size:4em; font-family:Verdana; color:#538caa; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.