Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save aspose-com-gists/ccfe5f5c2758640b0d2d998bfb7a6421 to your computer and use it in GitHub Desktop.
Save aspose-com-gists/ccfe5f5c2758640b0d2d998bfb7a6421 to your computer and use it in GitHub Desktop.
Use advanced features, such as CSS extensions, output streams, HTML5 Canvas support, HTML forms, etc.

Advanced Programming Techniques in Aspose.HTML for .NET

This gist repository contains advanced C# code samples for Aspose.HTML for .NET. These examples support the scenarios covered in the Advanced Programming section of the documentation and are intended for developers working with more complex HTML processing tasks.

Key Topics

This repository provides advanced usage examples of the Aspose.HTML for .NET API. You will explore:

  • Custom Stream Processing. Implement custom stream providers to control how output is generated and stored in memory or files.
  • Memory Stream Output. Render documents directly to memory streams for use in non-file-based workflows.
  • Advanced DOM manipulation with Mutation Observer. You will learn how to register and observe changes in the HTML Document tree using MutationObserver.
  • Aspose CSS Extension. Use Aspose-specific CSS properties to customize the layout of your printed document, such as adding headers, footers, and page numbers.
  • Editing HTML5 Canvas Content. Work with a document that contains an HTML5 Canvas element and render visual HTML output to formats like PDF.
  • Using the HTML Form Editor. Programmatically manipulate HTML forms in the document, input controls, and submission.

Examples Included

Example Description
Example-SetPageMarginMarksUsingCssExtensions.cs Use CSS extensions to customize margin boxes in printed output.
Example-CanvasRenderingContext2D.cs Create and render drawings using JavaScript canvas API.
Example-ConvertHtml5CanvasToPdf.cs Modify canvas content and render it to a PDF.
Example-FillAndSubmitHtmlForm.cs Automatically fill and submit form data.
Example-MemoryStreamProvider.cs Save output documents in memory without writing to disk.
Example-MutationObserver.cs Observe changes to the HTML DOM.
Example-UsingCustomStreamProviderToConvertHtmlToJpeg.cs Use a custom stream provider for image output.

Usage

  1. Add Aspose.HTML for .NET to your project.
  2. You can download a free trial of Aspose.HTML for .NET and use a temporary license for unrestricted access.
  3. Browse the available gists and copy the code samples you need.
  4. Configure paths, settings, and inputs to suit your environment.

Related Resources

Prerequisites

  • .NET Platforms: .NET 5.0, .NET Framework 4.6.1+, or .NET Core 2.0+
  • Supported OS: Windows, Linux, macOS
  • Aspose.HTML for .NET library
Aspose.HTML for .NET – Advanced Programming
// How to render HTML5 Canvas 2D to PDF using C#
// Learn more: https://docs.aspose.com/html/net/edit-html5-canvas/
// Create an empty HTML document
using HTMLDocument document = new HTMLDocument();
// Create a <canvas> element
HTMLCanvasElement canvas = (HTMLCanvasElement)document.CreateElement("canvas");
// with a specified size
canvas.Width = 500;
canvas.Height = 150;
// and append it to the document body
document.Body.AppendChild(canvas);
// Get the canvas rendering context to draw
ICanvasRenderingContext2D context = (Html.Dom.Canvas.ICanvasRenderingContext2D)canvas.GetContext("2d");
// Prepare a gradient brush
ICanvasGradient gradient = context.CreateLinearGradient(0, 0, canvas.Width, 0);
gradient.AddColorStop(0, "magenta");
gradient.AddColorStop(0.4, "blue");
gradient.AddColorStop(0.9, "red");
// Assign the brush to the content
context.FillStyle = gradient;
context.StrokeStyle = gradient;
// Write the text
context.FillText("Hello, World!", 10, 90, 500);
// Fill the rectangle
context.FillRect(0, 95, 500, 100);
// Prepare an output path
string outputPath = Path.Combine(OutputDir, "canvas.pdf");
// Create the PDF output device
using (PdfDevice device = new PdfDevice(outputPath))
{
// Render HTML5 Canvas to PDF
document.RenderTo(device);
}
// How to edit HTML5 Canvas and convert it to PDF using C#
// Learn more: https://docs.aspose.com/html/net/edit-html5-canvas/
// Prepare an output path
string outputPath = Path.Combine(OutputDir, "output.pdf");
// Prepare a document with HTML5 Canvas inside and save it to the file "document.html"
string code = @"
<canvas id=myCanvas width='200' height='100' style='border:1px solid #d3d3d3;'></canvas>
<script>
var c = document.getElementById('myCanvas');
var context = c.getContext('2d');
context.font = '30px Arial';
context.fillStyle = 'red';
context.fillText('Hello, World', 40, 50);
</script>";
System.IO.File.WriteAllText("document.html", code);
// Initialize an HTML document from the html file
using (HTMLDocument document = new HTMLDocument("document.html"))
{
// Convert HTML to PDF
Converter.ConvertHTML(document, new PdfSaveOptions(), outputPath);
}
// How to to programmatically fill and submit an HTML form in C#
// Learn more: https://docs.aspose.com/html/net/html-form-editor/
// Initialize an instance of HTML document
using (HTMLDocument document = new HTMLDocument(Path.Combine(DataDir, "form.html")))
{
// Create an instance of Form Editor
using (FormEditor editor = Aspose.Html.Forms.FormEditor.Create(document, 0))
{
// You can fill the data up using direct access to the input elements, like this:
editor["custname"].Value = "John Doe";
document.Save("out.html");
// or this:
TextAreaElement comments = editor.GetElement<Aspose.Html.Forms.TextAreaElement>("comments");
comments.Value = "MORE CHEESE PLEASE!";
// or even by performing a bulk operation, like this one:
editor.Fill(new Dictionary<string, string>()
{
{"custemail", "john.doe@gmail.com"},
{"custtel", "+1202-555-0290"}
});
// Create an instance of form submitter
using (FormSubmitter submitter = new Aspose.Html.Forms.FormSubmitter(editor))
{
// Submit the form data to the remote server
// If you need you can specify user-credentials and timeout for the request, etc.
SubmissionResult result = submitter.Submit();
// Check the status of the result object
if (result.IsSuccess)
{
// Check whether the result is in json format
if (result.ResponseMessage.Headers.ContentType.MediaType == "application/json")
{
// Dump result data to the console
Console.WriteLine(result.Content.ReadAsString());
}
else
{
// Load the result data as an HTML document
using (Document resultDocument = result.LoadDocument())
{
// Inspect HTML document here.
}
}
}
}
}
}
// How to capture output in memory using a custom stream provider
// Learn more: https://docs.aspose.com/html/net/output-streams/
class MemoryStreamProvider : ICreateStreamProvider
{
// List of MemoryStream objects created during the document rendering
public List<MemoryStream> Streams { get; } = new List<MemoryStream>();
public Stream GetStream(string name, string extension)
{
// This method is called when only one output stream is required, for instance for XPS, PDF or TIFF formats
MemoryStream result = new MemoryStream();
Streams.Add(result);
return result;
}
public Stream GetStream(string name, string extension, int page)
{
// This method is called when the creation of multiple output streams are required. For instance, during the rendering HTML to list of image files (JPG, PNG, etc.)
MemoryStream result = new MemoryStream();
Streams.Add(result);
return result;
}
public void ReleaseStream(Stream stream)
{
// Here you can release the stream filled with data and, for instance, flush it to the hard-drive
}
public void Dispose()
{
// Releasing resources
foreach (MemoryStream stream in Streams)
stream.Dispose();
}
}
// Use Mutation Observer to watch for new nodes added to a document with C#
// Learn more: https://docs.aspose.com/html/net/mutationobserver/
// Create an empty HTML document
using (HTMLDocument document = new HTMLDocument())
{
// Create a mutation observer instance
Html.Dom.Mutations.MutationObserver observer = new Html.Dom.Mutations.MutationObserver((mutations, mutationObserver) =>
{
foreach (MutationRecord record in mutations)
{
foreach (Node node in record.AddedNodes)
{
Console.WriteLine("The '" + node + "' node was added to the document.");
}
}
});
// Configuration of the observer
MutationObserverInit config = new Html.Dom.Mutations.MutationObserverInit
{
ChildList = true,
Subtree = true,
CharacterData = true
};
// Pass in the target node to observe with the specified configuration
observer.Observe(document.Body, config);
// Now, we are going to modify DOM tree to check
// Create a paragraph element and append it to the document body
Element p = document.CreateElement("p");
document.Body.AppendChild(p);
// Create a text and append it to the paragraph
Text text = document.CreateTextNode("Hello, World");
p.AppendChild(text);
Console.WriteLine("Waiting for mutation. Press any key to continue...");
Output.ToString();
}
// How to add custom margin marks using CSS extensions
// Learn more: https://docs.aspose.com/html/net/css-extensions/
// Initialize a configuration object and set up page-margins for a document
using (Configuration configuration = new Configuration())
{
// Get the User Agent service
IUserAgentService userAgent = configuration.GetService<IUserAgentService>();
// Set the style of custom margins and create marks on it
userAgent.UserStyleSheet = @"@page
{
/* Page margins should be not empty in order to write content inside the margin-boxes */
margin-top: 1cm;
margin-left: 2cm;
margin-right: 2cm;
margin-bottom: 2cm;
/* Page counter located at the bottom of the page */
@bottom-right
{
-aspose-content: ""Page "" currentPageNumber() "" of "" totalPagesNumber();
color: green;
}
/* Page title located at the top-center box */
@top-center
{
-aspose-content: ""Hello, World Document Title!!!"";
vertical-align: bottom;
color: blue;
}
}";
// Initialize an HTML document
using HTMLDocument document = new HTMLDocument("<div>Hello, World!!!</div>", ".", configuration);
// Initialize an output device
using (PdfDevice device = new PdfDevice(Path.Combine(OutputDir, "output.pdf")))
{
// Send the document to the output device
document.RenderTo(device);
}
}
// Convert HTML to JPEG in C# using output memory streams for writing data
// Learn more: https://docs.aspose.com/html/net/output-streams/
// Create an instance of MemoryStreamProvider
using (MemoryStreamProvider streamProvider = new MemoryStreamProvider())
{
// Prepare HTML code
string code = @"<style>
div { page-break-after: always; }
</style>
<div style='border: 1px solid red; width: 300px'>First Page</div>
<div style='border: 1px solid red; width: 300px'>Second Page</div>
<div style='border: 1px solid red; width: 300px'>Third Page</div>
";
// Initialize an HTML document from the HTML code
using HTMLDocument document = new HTMLDocument(code, ".");
{
// Convert HTML to Image by using the MemoryStreamProvider
Converter.ConvertHTML(document, new ImageSaveOptions(ImageFormat.Jpeg), streamProvider);
// Get access to the memory stream that contains the result data
int page = 1;
foreach (MemoryStream memory in streamProvider.Streams)
{
memory.Seek(0, SeekOrigin.Begin);
// Flush the result data to the output file
using (FileStream fs = File.Create(Path.Combine(OutputDir, "page_" + page + ".jpg")))
{
memory.CopyTo(fs);
}
page++;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment