Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save aspose-com-gists/055037aa0f016a0447bbcb858efee0a2 to your computer and use it in GitHub Desktop.
Save aspose-com-gists/055037aa0f016a0447bbcb858efee0a2 to your computer and use it in GitHub Desktop.
Create, load, edit and save HTML code using C#, create different environment configurations, set up a sandbox

Work with HTML Documents in C# using Aspose.HTML

This repository contains C# code examples referenced in the Aspose.HTML for .NET documentation. These gists demonstrate practical ways to load, read, create, modify, and save HTML documents programmatically using C# and the powerful Aspose.HTML for .NET API.

What’s Inside

The gists in this collection cover:

  • Loading HTML documents from files, strings, streams, or web URLs.
  • Loading EPUB and MHTML documents.
  • Creating and manipulating HTML elements dynamically.
  • Working with DOM, navigation, and content modification.
  • Navigation and manipulation the DOM tree using W3C-compliant traversal interfaces to inspect and retrieve content from HTML documents.
  • Setting custom user style sheets, font folders, message handlers, sandboxing, and other environment parameters to tailor document rendering and behavior.
  • Saving HTML documents in different formats like HTML, MHTML, or Markdown.
  • Saving documents along with all linked resources like CSS, fonts, and images using customizable saving options.

Each example is self-contained and ready to use.

Related Documentation

These samples support the tutorials in the Working with HTML Documents chapter of the official documentation.

Other Related Resources

How to Use

  1. Install the latest Aspose.HTML for .NET via NuGet.
  2. You can download a free trial of Aspose.HTML for .NET and use a temporary license for unrestricted access.
  3. Explore the gists in this repository and copy the relevant code to your project.
  4. Configure paths, settings, and inputs to suit your environment.

Requirements

  • .NET Platforms: .NET 5.0, .NET Framework 4.6.1+, or .NET Core 2.0+
  • Supported OS: Windows, Linux, macOS
  • Aspose.HTML for .NET
Aspose.HTML for .NET – Working with HTML Documents
// How to disable scripts for HTML to PDF conversion using C#
// Learn more: https://docs.aspose.com/html/net/sandboxing/
// Create an instance of the Configuration class
using (Configuration configuration = new Configuration())
{
// Mark "scripts" as an untrusted resource
configuration.Security |= Sandbox.Scripts;
// Initialize an HTML document with specified configuration
using (HTMLDocument document = new HTMLDocument(Path.Combine(DataDir, "document-with-scripts.html"), configuration))
{
// Convert HTML to PDF
Converter.ConvertHTML(document, new PdfSaveOptions(), Path.Combine(OutputDir, "document-sandbox.pdf"));
}
}
// Create HTML from scratch using C#
// Learn more: https://docs.aspose.com/html/net/creating-a-document/
// Prepare an output path for a document saving
string documentPath = Path.Combine(OutputDir, "create-new-document.html");
// Initialize an empty HTML Document
using (HTMLDocument document = new HTMLDocument())
{
HTMLElement body = document.Body;
// Create a heading element <h1> and set its text
HTMLHeadingElement h1 = (HTMLHeadingElement)document.CreateElement("h1");
Text texth1 = document.CreateTextNode("Create HTML file");
// Create a paragraph element set its text
HTMLParagraphElement p = (HTMLParagraphElement)document.CreateElement("p");
Text text = document.CreateTextNode("Learn how to create HTML file");
// Attach the text to the h1 and paragraph
h1.AppendChild(texth1);
p.AppendChild(text);
// Attach h1 and paragraph to the document body
body.AppendChild(h1);
body.AppendChild(p);
// Save the document to a disk
document.Save(documentPath);
}
// Create an empty HTML document using C#
// Learn more: https://docs.aspose.com/html/net/creating-a-document/
// Prepare an output path for a document saving
string documentPath = Path.Combine(OutputDir, "create-empty-document.html");
// Initialize an empty HTML Document
using (HTMLDocument document = new HTMLDocument())
{
// Work with the document
// Save the document to a file
document.Save(documentPath);
}
// Create HTML from a string using C#
// Learn more: https://docs.aspose.com/html/net/creating-a-document/
// Prepare HTML code
string html_code = "<p>Hello, World!</p>";
// Initialize a document from the string variable
using (HTMLDocument document = new HTMLDocument(html_code, "."))
{
// Save the document to a disk
document.Save(Path.Combine(OutputDir, "create-from-string.html"));
}
// Create and add new HTML elements using C#
// Learn more: https://docs.aspose.com/html/net/edit-html-document/
// Create an instance of an HTML document
using (HTMLDocument document = new HTMLDocument())
{
// Create a <style> element and assign the green color for all elements with class-name equals 'gr'.
Element style = document.CreateElement("style");
style.TextContent = ".gr { color: green }";
// Find the document <head> element and append the <style> element to it
Element head = document.GetElementsByTagName("head").First();
head.AppendChild(style);
// Create a paragraph element with class-name 'gr'.
HTMLParagraphElement p = (HTMLParagraphElement)document.CreateElement("p");
p.ClassName = "gr";
// Create a text node
Text text = document.CreateTextNode("Hello World!!");
// Append the text node to the paragraph
p.AppendChild(text);
// Append the paragraph to the document <body> element
document.Body.AppendChild(p);
// Save the HTML document to a file
document.Save(Path.Combine(OutputDir, "using-dom.html"));
// Create an instance of the PDF output device and render the document into this device
using (PdfDevice device = new PdfDevice(Path.Combine(OutputDir, "using-dom.pdf")))
{
// Render HTML to PDF
document.RenderTo(device);
}
}
// Create an HTML document using C#
// Learn more: https://docs.aspose.com/html/net/creating-a-document/
// Prepare an output path for a document saving
string documentPath = Path.Combine(OutputDir, "create-new-document.html");
// Initialize an empty HTML Document
using (HTMLDocument document = new HTMLDocument())
{
// Create a text node and add it to the document
Text text = document.CreateTextNode("Hello, World!");
document.Body.AppendChild(text);
// Save the document to a disk
document.Save(documentPath);
}
// Disable loading images in HTML with sandbox configuration using C#
// Learn more: https://docs.aspose.com/html/net/sandboxing/
// Prepare HTML code and save it to a file
string code = "<span style=\"background-image:url('https://docs.aspose.com/html/images/work/lioness.jpg')\">Hello, World!!</span> " +
"<script>document.write('Have a nice day!');</script>";
File.WriteAllText(Path.Combine(OutputDir, "sandboxing.html"), code);
// Create an instance of Configuration
using (Configuration configuration = new Configuration())
{
// Mark 'Images' as an untrusted resource
configuration.Security |= Sandbox.Images;
// Initialize an HTML document with specified configuration
using (HTMLDocument document = new HTMLDocument(Path.Combine(OutputDir, "sandboxing.html"), configuration))
{
// Convert HTML to PDF
Converter.ConvertHTML(document, new PdfSaveOptions(), Path.Combine(OutputDir, "sandboxing-out.pdf"));
}
}
// Edit HTML document using DOM Tree
// Learn more: https://docs.aspose.com/html/net/edit-html-document/
// Create an instance of an HTML document
using (HTMLDocument document = new HTMLDocument())
{
HTMLElement body = document.Body;
// Create a paragraph element
HTMLParagraphElement p = (HTMLParagraphElement)document.CreateElement("p");
// Set a custom attribute
p.SetAttribute("id", "my-paragraph");
// Create a text node
Text text = document.CreateTextNode("my first paragraph");
// Attach the text to the paragraph
p.AppendChild(text);
// Attach the paragraph to the document body
body.AppendChild(p);
// Save the HTML document to a file
document.Save(Path.Combine(OutputDir, "edit-document-tree.html"));
}
// Edit HTML with external CSS using C#
// Learn more: https://docs.aspose.com/html/net/edit-html-document/
// Prepare content of a CSS file
string styleContent = ".flower1 { width:120px; height:40px; border-radius:20px; background:#4387be; margin-top:50px; } \r\n" +
".flower2 { margin-left:0px; margin-top:-40px; background:#4387be; border-radius:20px; width:120px; height:40px; transform:rotate(60deg); } \r\n" +
".flower3 { transform:rotate(-60deg); margin-left:0px; margin-top:-40px; width:120px; height:40px; border-radius:20px; background:#4387be; }\r\n" +
".frame { margin-top:-50px; margin-left:310px; width:160px; height:50px; font-size:2em; font-family:Verdana; color:grey; }\r\n";
// Prepare a linked CSS file
File.WriteAllText("flower.css", styleContent);
// Create an instance of an HTML document with specified content
string htmlContent = "<link rel=\"stylesheet\" href=\"flower.css\" type=\"text/css\" /> \r\n" +
"<div style=\"margin-top: 80px; margin-left:250px; transform: scale(1.3);\" >\r\n" +
"<div class=\"flower1\" ></div>\r\n" +
"<div class=\"flower2\" ></div>\r\n" +
"<div class=\"flower3\" ></div></div>\r\n" +
"<div style = \"margin-top: -90px; margin-left:120px; transform:scale(1);\" >\r\n" +
"<div class=\"flower1\" style=\"background: #93cdea;\"></div>\r\n" +
"<div class=\"flower2\" style=\"background: #93cdea;\"></div>\r\n" +
"<div class=\"flower3\" style=\"background: #93cdea;\"></div></div>\r\n" +
"<div style =\"margin-top: -90px; margin-left:-80px; transform: scale(0.7);\" >\r\n" +
"<div class=\"flower1\" style=\"background: #d5effc;\"></div>\r\n" +
"<div class=\"flower2\" style=\"background: #d5effc;\"></div>\r\n" +
"<div class=\"flower3\" style=\"background: #d5effc;\"></div></div>\r\n" +
"<p class=\"frame\">External</p>\r\n" +
"<p class=\"frame\" style=\"letter-spacing:10px; font-size:2.5em \"> CSS </p>\r\n";
using (HTMLDocument document = new HTMLDocument(htmlContent, "."))
{
// Save the HTML document to a file
document.Save(Path.Combine(OutputDir, "edit-external-css.html"));
}
// How to set inline CSS styles in an HTML element using C#
// Learn more: https://docs.aspose.com/html/net/edit-html-document/
// Create an instance of an HTML document with specified content
string content = "<p>InlineCSS </p>";
using (HTMLDocument document = new HTMLDocument(content, "."))
{
// Find the paragraph element to set a style
HTMLElement paragraph = (HTMLElement)document.GetElementsByTagName("p").First();
// Set the style attribute
paragraph.SetAttribute("style", "font-size:250%; font-family:verdana; color:#cd66aa");
// Save the HTML document to a file
document.Save(Path.Combine(OutputDir, "edit-inline-css.html"));
// Create an instance of PDF output device and render the document into this device
using (PdfDevice device = new PdfDevice(Path.Combine(OutputDir, "edit-inline-css.pdf")))
{
// Render HTML to PDF
document.RenderTo(device);
}
}
// Edit HTML with internal CSS using C#
// Learn more: https://docs.aspose.com/html/net/edit-html-document/
// Create an instance of an HTML document with specified content
string content = "<div><p>Internal CSS</p><p>An internal CSS is used to define a style for a single HTML page</p></div>";
using (HTMLDocument document = new HTMLDocument(content, "."))
{
Element style = document.CreateElement("style");
style.TextContent = ".frame1 { margin-top:50px; margin-left:50px; padding:20px; width:360px; height:90px; background-color:#a52a2a; font-family:verdana; color:#FFF5EE;} \r\n" +
".frame2 { margin-top:-90px; margin-left:160px; text-align:center; padding:20px; width:360px; height:100px; background-color:#ADD8E6;}";
// Find the document header element and append the style element to the header
Element head = document.GetElementsByTagName("head").First();
head.AppendChild(style);
// Find the first paragraph element to inspect the styles
HTMLElement paragraph = (HTMLElement)document.GetElementsByTagName("p").First();
paragraph.ClassName = "frame1";
// Find the last paragraph element to inspect the styles
HTMLElement lastParagraph = (HTMLElement)document.GetElementsByTagName("p").Last();
lastParagraph.ClassName = "frame2";
// Set a color to the first paragraph
paragraph.Style.FontSize = "250%";
paragraph.Style.TextAlign = "center";
// Set a font-size to the last paragraph
lastParagraph.Style.Color = "#434343";
lastParagraph.Style.FontSize= "150%";
lastParagraph.Style.FontFamily = "verdana";
// Save the HTML document to a file
document.Save(Path.Combine(OutputDir, "edit-internal-css.html"));
// Create the instance of the PDF output device and render the document into this device
using (PdfDevice device = new PdfDevice(Path.Combine(OutputDir, "edit-internal-css.pdf")))
{
// Render HTML to PDF
document.RenderTo(device);
}
}
// Limit JavaScript execution time for HTML rendering using C#
// Learn more: https://docs.aspose.com/html/net/environment-configuration/
// Prepare an HTML code and save it to a file
string code = "<h1>Runtime Service</h1>\r\n" +
"<script> while(true) {} </script>\r\n" +
"<p>The Runtime Service optimizes your system by helping it start apps and programs faster.</p>\r\n";
File.WriteAllText(Path.Combine(OutputDir, "runtime-service.html"), code);
// Create an instance of Configuration
using (Configuration configuration = new Configuration())
{
// Limit JS execution time to 5 seconds
IRuntimeService runtimeService = configuration.GetService<IRuntimeService>();
runtimeService.JavaScriptTimeout = TimeSpan.FromSeconds(5);
// Initialize an HTML document with specified configuration
using (HTMLDocument document = new HTMLDocument(Path.Combine(OutputDir, "runtime-service.html"), configuration))
{
// Convert HTML to PNG
Converter.ConvertHTML(document, new ImageSaveOptions(), Path.Combine(OutputDir, "runtime-service_out.png"));
}
}
// Load an HTML documment from a file using C#
// Learn more: https://docs.aspose.com/html/net/creating-a-document/
// Prepare a file path
string documentPath = Path.Combine(DataDir, "sprite.html");
// Initialize an HTML document from the file
using (HTMLDocument document = new HTMLDocument(documentPath))
{
// Work with the document
// Save the document to a disk
document.Save(Path.Combine(OutputDir, "sprite_out.html"));
}
// Load HTML from a file using C#
// Learn more: https://docs.aspose.com/html/net/creating-a-document/
string htmlFile = Path.Combine(OutputDir, "load-from-file.html");
// Prepare a load-from-file.html document
File.WriteAllText(htmlFile, "Hello, World!");
// Load from the load-from-file.html
using (HTMLDocument document = new HTMLDocument(htmlFile))
{
// Write the document content to the output stream
Console.WriteLine(document.DocumentElement.OuterHTML);
}
// Load HTML from a stream using C#
// Learn more: https://docs.aspose.com/html/net/creating-a-document/
// Create a memory stream object
using (MemoryStream mem = new MemoryStream())
using (StreamWriter sw = new StreamWriter(mem))
{
// Write the HTML code into memory object
sw.Write("<p>Hello, World! I love HTML!</p>");
// It is important to set the position to the beginning, since HTMLDocument starts the reading exactly from the current position within the stream
sw.Flush();
mem.Seek(0, SeekOrigin.Begin);
// Initialize a document from the string variable
using (HTMLDocument document = new HTMLDocument(mem, "."))
{
// Save the document to disk
document.Save(Path.Combine(OutputDir, "load-from-stream.html"));
}
}
// Load HTML from a URL using C#
// Learn more: https://docs.aspose.com/html/net/creating-a-document/
// Load a document from 'https://docs.aspose.com/html/files/document.html' web page
using (HTMLDocument document = new HTMLDocument("https://docs.aspose.com/html/files/document.html"))
{
string html = document.DocumentElement.OuterHTML;
// Write the document content to the output stream
Console.WriteLine(html);
}
// Load SVG from a string using C#
// Learn more: https://docs.aspose.com/html/net/creating-a-document/
// Initialize an SVG document from a string object
using (SVGDocument document = new SVGDocument("<svg xmlns='http://www.w3.org/2000/svg'><circle cx='50' cy='50' r='40'/></svg>", "."))
{
// Write the document content to the output stream
Console.WriteLine(document.DocumentElement.OuterHTML);
}
// Сustom network message handler to log HTTP errors during HTML processing
// Learn more: https://docs.aspose.com/html/net/environment-configuration/
private class LogMessageHandler : MessageHandler
{
private List<string> errors = new List<string>();
public List<string> ErrorMessages
{
get { return errors; }
}
public override void Invoke(INetworkOperationContext context)
{
// Check whether response is OK
if (context.Response.StatusCode != HttpStatusCode.OK)
{
// Set error information
errors.Add(string.Format("File '{0}' Not Found", context.Request.RequestUri));
}
// Invoke the next message handler in the chain
Next(context);
}
}
// In-memory resource handler that captures and stores HTML resources as streams
// Learn more: https://docs.aspose.com/html/net/save-html-document/
internal class MemoryResourceHandler : ResourceHandler
{
public List<Tuple<Stream, Resource>> Streams;
public MemoryResourceHandler()
{
Streams = new List<Tuple<Stream, Resource>>();
}
public override void HandleResource(Resource resource, ResourceHandlingContext context)
{
MemoryStream outputStream = new MemoryStream();
Streams.Add(Tuple.Create<Stream, Resource>(outputStream, resource));
resource
.WithOutputUrl(new Url(Path.GetFileName(resource.OriginalUrl.Pathname), "memory:///"))
.Save(outputStream, context);
}
public void PrintInfo()
{
foreach (Tuple<Stream, Resource> stream in Streams)
Console.WriteLine($"uri:{stream.Item2.OutputUrl}, length:{stream.Item1.Length}");
}
}
// Log network errors during HTML processing using custom message handler in C#
// Learn more: https://docs.aspose.com/html/net/environment-configuration/
// Prepare HTML code and save it to a file
string code = "<img src=\"https://docs.aspose.com/svg/net/drawing-basics/filters-and-gradients/park.jpg\" >\r\n" +
"<img src=\"https://docs.aspose.com/html/net/missing1.jpg\" >\r\n" +
"<img src=\"https://docs.aspose.com/html/net/missing2.jpg\" >\r\n";
File.WriteAllText(Path.Combine(OutputDir, "network-service.html"), code);
// Create an instance of Configuration
using (Configuration configuration = new Configuration())
{
// Add the LogMessageHandler to the chain of existing message handlers
INetworkService networkService = configuration.GetService<INetworkService>();
LogMessageHandler logHandler = new LogMessageHandler();
networkService.MessageHandlers.Add(logHandler);
// Initialize an HTML document with specified configuration
using (HTMLDocument document = new HTMLDocument(Path.Combine(OutputDir, "network-service.html"), configuration))
{
//Convert HTML to PNG
Converter.ConvertHTML(document, new ImageSaveOptions(), Path.Combine(OutputDir, "network-service_out.png"));
// Print the List of ErrorMessages
foreach (string errorMessage in logHandler.ErrorMessages)
{
Console.WriteLine(errorMessage);
}
}
}
// Enable sandboxing to restrict script execution when loading HTML
// Learn more: https://docs.aspose.com/html/net/environment-configuration/
// Prepare HTML code and save it to a file
string code = "<span>Hello, World!!</span> " +
"<script>document.write('Have a nice day!');</script>";
File.WriteAllText(Path.Combine(OutputDir, "sandboxing.html"), code);
// Create an instance of Configuration
using (Configuration configuration = new Configuration())
{
// Mark 'scripts' as an untrusted resource
configuration.Security |= Sandbox.Scripts;
// Initialize an HTML document with specified configuration
using (HTMLDocument document = new HTMLDocument(Path.Combine(OutputDir, "sandboxing.html"), configuration))
{
// Convert HTML to PDF
Converter.ConvertHTML(document, new PdfSaveOptions(), Path.Combine(OutputDir, "sandboxing_out.pdf"));
}
}
// Save HTML to a file using C#
// Learn more: https://docs.aspose.com/html/net/save-html-document/
// Prepare an output path for a document saving
string documentPath = Path.Combine(OutputDir, "save-to-file.html");
// Initialize an empty HTML document
using (HTMLDocument document = new HTMLDocument())
{
// Create a text element and add it to the document
Text text = document.CreateTextNode("Hello, World!");
document.Body.AppendChild(text);
// Save the HTML document to the file on a disk
document.Save(documentPath);
}
// Save HTML as Markdown using C#
// Learn more: https://docs.aspose.com/html/net/save-html-document/
// Prepare an output path for a document saving
string documentPath = Path.Combine(OutputDir, "save-html-to-markdown.md");
// Prepare HTML code
string html_code = "<H2>Hello, World!</H2>";
// Initialize a document from a string variable
using (HTMLDocument document = new HTMLDocument(html_code, "."))
{
// Save the document as a Markdown file
document.Save(documentPath, HTMLSaveFormat.Markdown);
}
// Save HTML with resources to memory streams using C#
// Learn more: https://docs.aspose.com/html/net/save-html-document/
// Prepare a path to a source HTML file
string inputPath = Path.Combine(DataDir, "with-resources.html");
// Load the HTML document
using (HTMLDocument doc = new HTMLDocument(inputPath))
{
// Create an instance of the MemoryResourceHandler class and save HTML to memory
MemoryResourceHandler resourceHandler = new MemoryResourceHandler();
doc.Save(resourceHandler);
resourceHandler.PrintInfo();
}
// Save HTML as MHTML using C#
// Learn more: https://docs.aspose.com/html/net/save-html-document/
// Prepare an output path for a document saving
string savePath = Path.Combine(OutputDir, "save-to-mhtml.mht");
// Prepare a simple HTML file with a linked document
File.WriteAllText("save-to-mhtml.html", "<p>Hello, World!</p>" +
"<a href='linked-file.html'>linked file</a>");
// Prepare a simple linked HTML file
File.WriteAllText("linked-file.html", "<p>Hello, linked file!</p>");
// Load the "save-to-mhtml.html" into memory
using (HTMLDocument document = new HTMLDocument("save-to-mhtml.html"))
{
// Save the document to MHTML format
document.Save(savePath, HTMLSaveFormat.MHTML);
}
// Save HTML with a linked resources using C#
// Learn more: https://docs.aspose.com/html/net/save-html-document/
// Prepare an output path for an HTML document
string documentPath = Path.Combine(OutputDir, "save-with-linked-file.html");
// Prepare a simple HTML file with a linked document
File.WriteAllText(documentPath, "<p>Hello, World!</p>" +
"<a href='linked.html'>linked file</a>");
// Prepare a simple linked HTML file
File.WriteAllText(Path.Combine(OutputDir, "linked.html"), "<p>Hello, linked file!</p>");
// Load the "save-with-linked-file.html" into memory
using (HTMLDocument document = new HTMLDocument(documentPath))
{
// Create a save options instance
HTMLSaveOptions options = new HTMLSaveOptions();
// The following line with value '0' cuts off all other linked HTML-files while saving this instance
// If you remove this line or change value to the '1', the 'linked.html' file will be saved as well to the output folder
options.ResourceHandlingOptions.MaxHandlingDepth = 1;
// Save the document with the save options
document.Save(Path.Combine(OutputDir, "save-with-linked-file_out.html"), options);
}
// Save HTML with resources to local storage using C#
// Learn more: https://docs.aspose.com/html/net/save-html-document/
// Prepare a path to a source HTML file
string inputPath = Path.Combine(DataDir, "with-resources.html");
// Prepare a full path to an output directory
string customOutDir = Path.Combine(Directory.GetCurrentDirectory(), "./../../../../tests-out/saving/");
// Load the HTML document from a file
using (HTMLDocument doc = new HTMLDocument(inputPath))
{
// Save HTML with resources
doc.Save(new FileSystemResourceHandler(customOutDir));
}
// Save an HTML document with all linked resources into a ZIP archive using C#
// Learn more: https://docs.aspose.com/html/net/save-html-document/
// Prepare a path to a source HTML file
string inputPath = Path.Combine(DataDir, "with-resources.html");
string dir = Directory.GetCurrentDirectory();
// Prepare a full path to an output zip storage
string customArchivePath = Path.Combine(dir, "./../../../../tests-out/saving/archive.zip");
// Load the HTML document
using (HTMLDocument doc = new HTMLDocument(inputPath))
{
// Initialize an instance of the ZipResourceHandler class
using (ZipResourceHandler resourceHandler = new ZipResourceHandler(customArchivePath))
{
// Save HTML with resources to a Zip archive
doc.Save(resourceHandler);
}
}
// Create and save SVG image using C#
// Learn more: https://docs.aspose.com/html/net/save-html-document/
// Prepare an output path for a document saving
string documentPath = Path.Combine(OutputDir, "create-and-save-svg.svg");
// Prepare SVG code
string code = @"
<svg xmlns='http://www.w3.org/2000/svg' height='200' width='300'>
<g fill='none' stroke-width= '10' stroke-dasharray='30 10'>
<path stroke='red' d='M 25 40 l 215 0' />
<path stroke='black' d='M 35 80 l 215 0' />
<path stroke='blue' d='M 45 120 l 215 0' />
</g>
</svg>";
// Initialize an SVG instance from the content string
using (SVGDocument document = new SVGDocument(code, "."))
{
// Save the SVG file to a disk
document.Save(documentPath);
}
// Set character encoding and custom styles for HTML to PDF conversion in C#
// Learn more: https://docs.aspose.com/html/net/environment-configuration/
// Prepare HTML code and save it to a file
string code = "<h1>Character Set</h1>\r\n" +
"<p>The <b>CharSet</b> property sets the primary character-set for a document.</p>\r\n";
File.WriteAllText(Path.Combine(OutputDir, "user-agent-charset.html"), code);
// Create an instance of Configuration
using (Configuration configuration = new Configuration())
{
// Get the IUserAgentService
IUserAgentService userAgentService = configuration.GetService<IUserAgentService>();
// Set the custom style parameters for the <h1> and <p> elements
userAgentService.UserStyleSheet = "h1 { color:salmon; }\r\n" +
"p { background-color:#f0f0f0; color:DarkCyan; font-size:1.2em; }\r\n";
// Set ISO-8859-1 encoding to parse the document
userAgentService.CharSet = "ISO-8859-1";
// Initialize the HTML document with specified configuration
using (HTMLDocument document = new HTMLDocument(Path.Combine(OutputDir, "user-agent-charset.html"), configuration))
{
// Convert HTML to PDF
Converter.ConvertHTML(document, new PdfSaveOptions(), Path.Combine(OutputDir, "user-agent-charset_out.pdf"));
}
}
// Set font folder for HTML to PDF conversion using C#
// Learn more: https://docs.aspose.com/html/net/environment-configuration/
// Prepare HTML code and save it to a file
string code = "<h1>FontsSettings property</h1>\r\n" +
"<p>The FontsSettings property is used for configuration of fonts handling.</p>\r\n";
File.WriteAllText(Path.Combine(OutputDir, "user-agent-fontsetting.html"), code);
// Create an instance of Configuration
using (Configuration configuration = new Configuration())
{
// Get the IUserAgentService
IUserAgentService userAgentService = configuration.GetService<IUserAgentService>();
// Set the custom style parameters for the <h1> and <p> elements
userAgentService.UserStyleSheet = "h1 { color:#a52a2a; }\r\n" +
"p { color:grey; }\r\n";
// Set a custom font folder path
userAgentService.FontsSettings.SetFontsLookupFolder(Path.Combine(DataDir + "fonts"));
// Initialize the HTML document with specified configuration
using (HTMLDocument document = new HTMLDocument(Path.Combine(OutputDir, "user-agent-fontsetting.html"), configuration))
{
// Convert HTML to PDF
Converter.ConvertHTML(document, new PdfSaveOptions(), Path.Combine(OutputDir, "user-agent-fontsetting_out.pdf"));
}
}
// How to use an external CSS file in HTML using Aspose.HTML for .NET
// Learn more: https://docs.aspose.com/html/net/edit-html-document/
// Create an instance of HTML document with specified content
string htmlContent = "<link rel=\"stylesheet\" href=\"https://docs.aspose.com/html/net/edit-html-document/external.css\" type=\"text/css\" />\r\n" +
"<div class=\"rect1\" ></div>\r\n" +
"<div class=\"rect2\" ></div>\r\n" +
"<div class=\"frame\">\r\n" +
"<p style=\"font-size:2.5em; color:#ae4566;\"> External CSS </p>\r\n" +
"<p class=\"rect3\"> An external CSS can be created once and applied to multiple web pages</p></div>\r\n";
using (HTMLDocument document = new HTMLDocument(htmlContent, "."))
{
// Save the HTML document to a file
document.Save(Path.Combine(OutputDir, "external-css.html"));
// Create the instance of the PDF output device and render the document into this device
using (PdfDevice device = new PdfDevice(Path.Combine(OutputDir, "external-css.pdf")))
{
// Render HTML to PDF
document.RenderTo(device);
}
}
// Apply custom CSS via user agent service during HTML processing in C#
// Learn more: https://docs.aspose.com/html/net/environment-configuration/
// Prepare HTML code and save it to a file
string code = "<h1>User Agent Service </h1>\r\n" +
"<p>The User Agent Service allows you to specify a custom user stylesheet, a primary character set for the document, language and fonts settings.</p>\r\n";
File.WriteAllText(Path.Combine(OutputDir, "user-agent-stylesheet.html"), code);
// Create an instance of Configuration
using (Configuration configuration = new Configuration())
{
// Get the IUserAgentService
IUserAgentService userAgentService = configuration.GetService<IUserAgentService>();
// Set the custom style parameters for the <h1> and <p> elements
userAgentService.UserStyleSheet = "h1 { color:#a52a2a;; font-size:2em;}\r\n" +
"p { background-color:GhostWhite; color:SlateGrey; font-size:1.2em; }\r\n";
// Initialize the HTML document with specified configuration
using (HTMLDocument document = new HTMLDocument(Path.Combine(OutputDir, "user-agent-stylesheet.html"), configuration))
{
// Convert HTML to PDF
Converter.ConvertHTML(document, new PdfSaveOptions(), Path.Combine(OutputDir, "user-agent-stylesheet_out.pdf"));
}
}
// Load HTML asynchronously using C#
// Learn more: https://docs.aspose.com/html/net/creating-a-document/
// Initialize an AutoResetEvent
AutoResetEvent resetEvent = new AutoResetEvent(false);
// Create an instance of an HTML document
HTMLDocument document = new HTMLDocument();
// Create a string variable for the OuterHTML property reading
string outerHTML = string.Empty;
// Subscribe to ReadyStateChange event
// This event will be fired during the document loading process
document.OnReadyStateChange += (sender, @event) =>
{
// Check the value of the ReadyState property
// This property is representing the status of the document. For detail information please visit https://www.w3schools.com/jsref/prop_doc_readystate.asp
if (document.ReadyState == "complete")
{
// Fill the outerHTML variable by value of loaded document
outerHTML = document.DocumentElement.OuterHTML;
resetEvent.Set();
}
};
// Navigate asynchronously at the specified Uri
document.Navigate("https://docs.aspose.com/html/files/document.html");
// Here the outerHTML is empty yet
Console.WriteLine($"outerHTML = {outerHTML}");
// Wait 5 seconds for the file to load
// Here the outerHTML is filled
Console.WriteLine("outerHTML = {0}", outerHTML);
// Handle an HTML document load using C#
// Learn more: https://docs.aspose.com/html/net/creating-a-document/
// Initialize an AutoResetEvent
AutoResetEvent resetEvent = new AutoResetEvent(false);
// Initialize an HTML document
HTMLDocument document = new HTMLDocument();
bool isLoading = false;
// Subscribe to the OnLoad event
// This event will be fired once the document is fully loaded
document.OnLoad += (sender, @event) =>
{
isLoading = true;
resetEvent.Set();
};
// Navigate asynchronously at the specified Uri
document.Navigate("https://docs.aspose.com/html/files/document.html");
Console.WriteLine("outerHTML = {0}", document.DocumentElement.OuterHTML);
// Edit HTML body content and get modified document as string
// Learn more: https://docs.aspose.com/html/net/edit-html-document/
// Create an instance of an HTML document
using (HTMLDocument document = new HTMLDocument())
{
// Write the content of the HTML document into the console output
Console.WriteLine(document.DocumentElement.OuterHTML); // output: <html><head></head><body></body></html>
// Set the content of the body element
document.Body.InnerHTML = "<p>HTML is the standard markup language for Web pages.</p>";
// Set an html variable for the document content viewing
string html = document.DocumentElement.OuterHTML;
// Write the content of the HTML document into the console output
Console.WriteLine(html); // output: <html><head></head><body><p>HTML is the standard markup language for Web pages.</p></body></html>
}
// Read and output full HTML content from a loaded document in C#
// Learn more: https://docs.aspose.com/html/net/edit-html-document/
string documentPath = Path.Combine(DataDir, "document.html");
// Create an instance of an HTML document
using (HTMLDocument document = new HTMLDocument(documentPath))
{
// Set an html variable for the document
string html = document.DocumentElement.OuterHTML;
Console.WriteLine(html);
}
// Custom resource handler to save HTML with resources into a ZIP archive
// Learn more: https://docs.aspose.com/html/net/save-html-document/
internal class ZipResourceHandler : ResourceHandler, IDisposable
{
private FileStream zipStream;
private ZipArchive archive;
private int streamsCounter;
private bool initialized;
public ZipResourceHandler(string name)
{
DisposeArchive();
zipStream = new FileStream(name, FileMode.Create);
archive = new ZipArchive(zipStream, ZipArchiveMode.Update);
initialized = false;
}
public override void HandleResource(Resource resource, ResourceHandlingContext context)
{
string zipUri = (streamsCounter++ == 0
? Path.GetFileName(resource.OriginalUrl.Href)
: Path.Combine(Path.GetFileName(Path.GetDirectoryName(resource.OriginalUrl.Href)),
Path.GetFileName(resource.OriginalUrl.Href)));
string samplePrefix = String.Empty;
if (initialized)
samplePrefix = "my_";
else
initialized = true;
using (Stream newStream = archive.CreateEntry(samplePrefix + zipUri).Open())
{
resource.WithOutputUrl(new Url("file:///" + samplePrefix + zipUri)).Save(newStream, context);
}
}
private void DisposeArchive()
{
if (archive != null)
{
archive.Dispose();
archive = null;
}
if (zipStream != null)
{
zipStream.Dispose();
zipStream = null;
}
streamsCounter = 0;
}
public void Dispose()
{
DisposeArchive();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment