Skip to content

Instantly share code, notes, and snippets.

@aspose-com-gists
Last active June 20, 2025 14:08
Show Gist options
  • Save aspose-com-gists/f3606888162b6b9cad4e80c485ee4ec3 to your computer and use it in GitHub Desktop.
Save aspose-com-gists/f3606888162b6b9cad4e80c485ee4ec3 to your computer and use it in GitHub Desktop.
This Gist contains examples for Aspose.HTML for C#.
Aspose.HTML for C#
// 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"));
}
// 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"));
}
// 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"));
}
// Create an instance of the Configuration class
using Configuration configuration = new Configuration();
// Add the CredentialHandler to the chain of existing message handlers
INetworkService service = configuration.GetService<INetworkService>();
MessageHandlerCollection handlers = service.MessageHandlers;
handlers.Insert(0, new CredentialHandler());
// Initialize an HTML document with specified configuration
using HTMLDocument document = new HTMLDocument("https://httpbin.org/basic-auth/username/securelystoredpassword", configuration);
// 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());
}
// 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());
}
// 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 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);
}
}
// 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));
// 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));
// Prepare a path to a source HTML file
string documentPath = Path.Combine(DataDir, "alt-tag.html");
// Initialize webAccessibility container
WebAccessibility webAccessibility = new WebAccessibility();
// Get from the rules list Principle "1. Perceivable" by code "1" and get guideline "1.1 Text Alternatives"
Guideline guideline = webAccessibility.Rules.GetPrinciple("1").GetGuideline("1.1");
// Create an accessibility validator - pass the found guideline as parameters and specify the full validation settings
AccessibilityValidator validator = webAccessibility.CreateValidator(guideline, ValidationBuilder.All);
// Initialize an HTMLDocument object
using (HTMLDocument document = new HTMLDocument(documentPath))
{
ValidationResult validationResult = validator.Validate(document);
if (!validationResult.Success)
{
// Get all the result details
foreach (RuleValidationResult ruleResult in validationResult.Details)
{
// If the result of the rule is unsuccessful
if (!ruleResult.Success)
{
// Get an errors list
foreach (ITechniqueResult result in ruleResult.Errors)
{
// Check the type of the erroneous element, in this case, we have an error in the HTML Element
if (result.Error.Target.TargetType == TargetTypes.HTMLElement)
{
HTMLElement rule = (HTMLElement)result.Error.Target.Item;
Console.WriteLine("Error in rule {0} : {1}", result.Rule.Code, result.Error.ErrorMessage);
Console.WriteLine("HTML Element: {0}", rule.OuterHTML);
}
}
}
}
}
}
// Prepare a path to a source HTML file
string documentPath = Path.Combine(DataDir, "check-color.html");
// Initialize a webAccessibility container
WebAccessibility webAccessibility = new WebAccessibility();
// Get Principle "1.Perceivable" by code "1" and get guideline "1.4"
Guideline guideline = webAccessibility.Rules.GetPrinciple("1").GetGuideline("1.4");
// Get criterion by code, for example 1.4.3
Criterion criterion143 = guideline.GetCriterion("1.4.3");
// Get criterion by code, for example 1.4.6
Criterion criterion146 = guideline.GetCriterion("1.4.6");
// Create an accessibility validator, pass the found guideline as parameters and specify the full validation settings
AccessibilityValidator validator = webAccessibility.CreateValidator(new IRule[] { criterion143, criterion146 }, ValidationBuilder.All);
using (HTMLDocument document = new HTMLDocument(documentPath))
{
ValidationResult validationResult = validator.Validate(document);
if (!validationResult.Success)
{
Console.WriteLine(validationResult.SaveToString());
}
}
// Prepare a path to a source HTML file
string documentPath = Path.Combine(DataDir, "check-color.html");
// Initialize a webAccessibility container
WebAccessibility webAccessibility = new WebAccessibility();
// Get Principle "1.Perceivable" by code "1" and get guideline "1.4"
Guideline guideline = webAccessibility.Rules.GetPrinciple("1").GetGuideline("1.4");
// Get criterion by code, for example 1.4.3
Criterion criterion = guideline.GetCriterion("1.4.3");
// Create an accessibility validator, pass the found guideline as parameters and specify the full validation settings
AccessibilityValidator validator = webAccessibility.CreateValidator(criterion, ValidationBuilder.All);
using (HTMLDocument document = new HTMLDocument(documentPath))
{
ValidationResult validationResult = validator.Validate(document);
if (!validationResult.Success)
{
// Get all result details
foreach (RuleValidationResult ruleResult in validationResult.Details)
{
// If the result of the rule is unsuccessful
if (!ruleResult.Success)
{
// Get errors list
foreach (ITechniqueResult result in ruleResult.Errors)
{
// Check the type of the erroneous element, in this case we have an error in the html element rule
if (result.Error.Target.TargetType == TargetTypes.HTMLElement)
{
// Element of file with error
HTMLElement rule = (HTMLElement)result.Error.Target.Item;
Console.WriteLine("Error in rule {0} : {1}", result.Rule.Code, result.Error.ErrorMessage);
Console.WriteLine("CSS Rule: {0}", rule.OuterHTML);
}
}
}
}
}
}
string htmlPath = Path.Combine(DataDir, "input.html");
// Initialize a webAccessibility container
WebAccessibility webAccessibility = new WebAccessibility();
// List of necessary rules for checking (rule code according to the specification)
string[] rulesCode = new string[] { "H2", "H37", "H67", "H86" };
// Get the required IList<Rule> rules from the rules reference
IList<IRule> rules = webAccessibility.Rules.GetRules(rulesCode);
// Create an accessibility validator, pass the found rules as parameters, and specify the full validation settings
AccessibilityValidator validator = webAccessibility.CreateValidator(rules, ValidationBuilder.All);
// Initialize an object of the HTMLDocument
using (HTMLDocument document = new HTMLDocument(htmlPath))
{
// Check the document
ValidationResult validationResult = validator.Validate(document);
// Return the result in string format
// SaveToString - return only errors and warnings
Console.WriteLine(validationResult.SaveToString());
}
// Open an existing EPUB file for reading
using FileStream stream = File.OpenRead(DataDir + "input.epub");
// Invoke the ConvertEPUB() method to convert EPUB to DOCX
Converter.ConvertEPUB(stream, new DocSaveOptions(), Path.Combine(OutputDir, "convert-by-two-lines.docx"));
// Open an existing EPUB file for reading
using FileStream stream = File.OpenRead(DataDir + "input.epub");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "input-output.bmp");
// Create an instance of the ImageSaveOptions class
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Bmp);
// Call the ConvertEPUB() method to convert EPUB to BMP
Converter.ConvertEPUB(stream, options, savePath);
// Open an existing EPUB file for reading
using FileStream stream = File.OpenRead(DataDir + "input.epub");
// Prepare a path for converted file saving
string savePath = Path.Combine(OutputDir, "input-options.bmp");
// Initialize ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Bmp)
{
UseAntialiasing = true,
HorizontalResolution = 400,
VerticalResolution = 400,
BackgroundColor = System.Drawing.Color.AliceBlue
};
// Call the ConvertEPUB() method to convert EPUB to BMP
Converter.ConvertEPUB(stream, options, savePath);
// Open an existing EPUB file for reading
using FileStream stream = File.OpenRead(DataDir + "input.epub");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "input-output.docx");
// Create an instance of the DocSaveOptions class
DocSaveOptions options = new DocSaveOptions();
// Call the ConvertEPUB() method to convert EPUB to DOCX
Converter.ConvertEPUB(stream, options, savePath);
// Open an existing EPUB file for reading
using FileStream stream = File.OpenRead(DataDir + "input.epub");
// Create an instance of EPUB Renderer
using EpubRenderer renderer = new EpubRenderer();
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "convert-epub-options.docx");
// Create the instance of Rendering Options and set a custom page-size
DocRenderingOptions options = new DocRenderingOptions();
options.PageSetup.AnyPage = new Page(new Size(800, 400));
// Create an instance of the DocDevice class
using DocDevice device = new DocDevice(options, savePath);
// Render EPUB to DOCX
renderer.Render(device, stream);
// Open an existing EPUB file for reading
using FileStream stream = File.OpenRead(DataDir + "input.epub");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "input-output.gif");
// Create an instance of the ImageSaveOptions class
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Gif);
// Call the ConvertEPUB() method to convert EPUB to GIF
Converter.ConvertEPUB(stream, options, savePath);
// Open an existing EPUB file for reading
using FileStream stream = File.OpenRead(DataDir + "input.epub");
// Prepare a path for converted file saving
string savePath = Path.Combine(OutputDir, "input-options.gif");
// Initialize ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Gif)
{
UseAntialiasing = true,
HorizontalResolution = 400,
VerticalResolution = 400,
BackgroundColor = System.Drawing.Color.AliceBlue
};
options.PageSetup.AnyPage = new Page(new Aspose.Html.Drawing.Size(800, 500), new Margin(30, 20, 10, 10));
// Call the ConvertEPUB() method to convert EPUB to GIF
Converter.ConvertEPUB(stream, options, savePath);
// Open an existing EPUB file for reading
using FileStream stream = File.OpenRead(DataDir + "input.epub");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "input-output.jpg");
// Create an instance of the ImageSaveOptions class
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Jpeg);
// Call the ConvertEPUB() method to convert EPUB to JPG
Converter.ConvertEPUB(stream, options, savePath);
// Open an existing EPUB file for reading
using FileStream stream = File.OpenRead(DataDir + "input.epub");
// Invoke the ConvertEPUB() method to convert EPUB to JPG
Converter.ConvertEPUB(stream, new ImageSaveOptions(ImageFormat.Jpeg), Path.Combine(OutputDir, "convert-by-two-lines.jpg"));
// Open an existing EPUB file for reading
using FileStream stream = File.OpenRead(DataDir + "input.epub");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "input-options.jpg");
// Initialize ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Jpeg)
{
UseAntialiasing = true,
HorizontalResolution = 400,
VerticalResolution = 400,
BackgroundColor = System.Drawing.Color.AliceBlue
};
options.PageSetup.AnyPage = new Page(new Aspose.Html.Drawing.Size(800, 500), new Margin(30, 20, 10, 10));
// Call the ConvertEPUB() method to convert EPUB to JPG
Converter.ConvertEPUB(stream, options, savePath);
// Open an existing EPUB file for reading
using FileStream stream = File.OpenRead(DataDir + "input.epub");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "input-output.pdf");
// Create an instance of the PdfSaveOptions class
PdfSaveOptions options = new PdfSaveOptions();
// Call the ConvertEPUB() method to convert EPUB to PDF
Converter.ConvertEPUB(stream, options, savePath);
// Open an existing EPUB file for reading
using FileStream stream = File.OpenRead(DataDir + "input.epub");
// Invoke the ConvertEPUB() method to convert EPUB to PDF
Converter.ConvertEPUB(stream, new PdfSaveOptions(), Path.Combine(OutputDir, "convert-by-two-lines.pdf"));
// Open an existing EPUB file for reading
using FileStream stream = File.OpenRead(DataDir + "input.epub");
// Create an instance of EPUB Renderer
using EpubRenderer renderer = new EpubRenderer();
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "convert-epub.pdf");
// Create the instance of Rendering Options and set a custom page-size
PdfRenderingOptions options = new PdfRenderingOptions();
options.PageSetup.AnyPage = new Page(new Size(800, 400));
// Create an instance of the PdfDevice class
using PdfDevice device = new PdfDevice(options, savePath);
// Convert EPUB to PDF
renderer.Render(device, stream);
// Open an existing EPUB file for reading
using FileStream stream = File.OpenRead(DataDir + "input.epub");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "input-output.png");
// Create an instance of the ImageSaveOptions class
ImageSaveOptions options = new ImageSaveOptions();
// Call the ConvertEPUB() method to convert EPUB to PNG
Converter.ConvertEPUB(stream, options, savePath);
// Open an existing EPUB file for reading
using FileStream stream = File.OpenRead(DataDir + "input.epub");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "input-options.png");
// Initialize ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions()
{
UseAntialiasing = true,
HorizontalResolution = 400,
VerticalResolution = 400,
BackgroundColor = System.Drawing.Color.AliceBlue
};
// Call the ConvertEPUB() method to convert EPUB to PNG
Converter.ConvertEPUB(stream, options, savePath);
// Open an existing EPUB file for reading
using FileStream stream = File.OpenRead(DataDir + "input.epub");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "input-output.tiff");
// Create an instance of the ImageSaveOptions class
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Tiff);
// Call the ConvertEPUB() method to convert EPUB to TIFF
Converter.ConvertEPUB(stream, options, savePath);
// Open an existing EPUB file for reading
using FileStream stream = File.OpenRead(DataDir + "input.epub");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "input-options.tiff");
// Create an instance of the ImageSaveOptions class
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Tiff)
{
Compression = Compression.None,
UseAntialiasing = true,
HorizontalResolution = 400,
VerticalResolution = 400,
BackgroundColor = System.Drawing.Color.AliceBlue
};
options.PageSetup.AnyPage = new Page(new Aspose.Html.Drawing.Size(800, 500), new Margin(30, 20, 10, 10));
// Call the ConvertEPUB() method to convert EPUB to TIFF
Converter.ConvertEPUB(stream, options, savePath);
// Open an existing EPUB file for reading
using FileStream stream = File.OpenRead(DataDir + "input.epub");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "input-output.xps");
// Create an instance of XpsSaveOptions
XpsSaveOptions options = new XpsSaveOptions();
// Call the ConvertEPUB() method to convert EPUB to XPS
Converter.ConvertEPUB(stream, options, savePath);
// Open an existing EPUB file for reading
using FileStream stream = File.OpenRead(DataDir + "input.epub");
// Invoke the ConvertEPUB() method to convert EPUB to XPS
Converter.ConvertEPUB(stream, new XpsSaveOptions(), Path.Combine(OutputDir, "convert-by-two-lines.xps"));
// Invoke the ConvertEPUB() method to convert EPUB to PNG
Converter.ConvertEPUB(File.OpenRead(DataDir + "input.epub"), new ImageSaveOptions(), Path.Combine(OutputDir, "convert-with-single-line.png"));
// Initialize an HTML document from a URL
using HTMLDocument document = new HTMLDocument("https://docs.aspose.com/html/files/document.html");
// Initialize PdfSaveOptions
PdfSaveOptions options = new PdfSaveOptions();
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "document.pdf");
// Convert HTML to PDF
Converter.ConvertHTML(document, options, savePath);
// Prepare a path to JSON data source file
string jsonPath = Path.Combine(OutputDir, "data-source.json");
// Prepare a JSON data source and save it to the file
string data = @"{
""FirstName"": ""John"",
""LastName"": ""Doe"",
""Address"": {
""City"": ""Dallas"",
""Street"": ""Austin rd."",
""Number"": ""200""
}
}";
File.WriteAllText(jsonPath, data);
// Prepare a path to an HTML Template file
string sourcePath = Path.Combine(OutputDir, "template.html");
// Prepare an HTML Template and save it to the file
string template = @"
<table border=1>
<tr>
<th>Person</th>
<th>Address</th>
</tr>
<tr>
<td>{{FirstName}} {{LastName}}</td>
<td>{{Address.Street}} {{Address.Number}}, {{Address.City}}</td>
</tr>
</table>
";
File.WriteAllText(sourcePath, template);
// Prepare a path to the output file (data-filled template file)
string outputPath = Path.Combine(OutputDir, "template-output.html");
// Invoke Converter.ConvertTemplate() method in order to populate "template.html" with the data source from "data-source.json" file
Converter.ConvertTemplate(sourcePath, new TemplateData(jsonPath), new TemplateLoadOptions(), outputPath);
// Prepare a path to a source HTML file
string documentPath = Path.Combine(DataDir, "bmp.html");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "bmp-output.bmp");
// Initialize an HTML document from the file
using HTMLDocument document = new HTMLDocument(documentPath);
// Create an instance of the ImageSaveOptions class
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Bmp);
// Convert HTML to BMP
Converter.ConvertHTML(document, options, savePath);
// Prepare a path to a source HTML file
string documentPath = Path.Combine(DataDir, "bmp.html");
// Prepare a path for converted file saving
string savePath = Path.Combine(OutputDir, "bmp-output-options.bmp");
// Initialize an HTML Document from the html file
using HTMLDocument document = new HTMLDocument(documentPath);
// Initialize ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Bmp)
{
UseAntialiasing = false,
HorizontalResolution = 350,
VerticalResolution = 350,
BackgroundColor = System.Drawing.Color.Beige
};
// Convert HTML to BMP
Converter.ConvertHTML(document, options, savePath);
// Prepare a path to a source HTML file
string documentPath = Path.Combine(DataDir, "canvas.html");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "canvas-output.docx");
// Initialize an HTML document from the file
using HTMLDocument document = new HTMLDocument(documentPath);
// Initialize DocSaveOptions
DocSaveOptions options = new DocSaveOptions();
// Convert HTML to DOCX
Converter.ConvertHTML(document, options, savePath);
// Prepare a path to a source HTML file
string documentPath = Path.Combine(DataDir, "spring.html");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "spring-output.gif");
// Initialize an HTML document from the file
using HTMLDocument document = new HTMLDocument(documentPath);
// Create an instance of the ImageSaveOptions class
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Gif);
// Convert HTML to GIF
Converter.ConvertHTML(document, options, savePath);
string documentPath = Path.Combine(OutputDir, "convert-to-gif.html");
string savePath = Path.Combine(OutputDir, "convert-to-gif-options.gif");
// Prepare HTML code and save it to a file
string code = "<h1> HTML to GIF Converter </h1>\r\n" +
"<p> GIF is a popular image format that supports animated images and frequently used in web publishing. HTML to GIF conversion allows you to save an HTML document as a GIF image. </p>\r\n";
File.WriteAllText(documentPath, code);
// Initialize an HTML Document from the html file
using HTMLDocument document = new HTMLDocument(documentPath);
// Initialize ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Gif)
{
UseAntialiasing = false,
HorizontalResolution = 100,
VerticalResolution = 100,
BackgroundColor = System.Drawing.Color.MistyRose
};
options.PageSetup.AnyPage = new Page(new Aspose.Html.Drawing.Size(500, 200), new Margin(30, 20, 10, 10));
// Convert HTML to GIF
Converter.ConvertHTML(document, options, savePath);
// Prepare a path to a source HTML file
string documentPath = Path.Combine(DataDir, "spring.html");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "spring-output.jpg");
// Initialize an HTML document from the file
using HTMLDocument document = new HTMLDocument(documentPath);
// Create an instance of the ImageSaveOptions class
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Jpeg);
// Convert HTML to JPG
Converter.ConvertHTML(document, options, savePath);
// Invoke the ConvertHTML() method to convert the HTML code to JPG image
Converter.ConvertHTML(@"<h1>Convert HTML to JPG!</h1>", ".", new ImageSaveOptions(ImageFormat.Jpeg), Path.Combine(OutputDir, "convert-with-single-line.jpg"));
// Prepare a path to a source HTML file
string documentPath = Path.Combine(DataDir, "color.html");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "color-output-options.jpg");
// Initialize an HTML document from the file
using HTMLDocument document = new HTMLDocument(documentPath);
// Initialize ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Jpeg)
{
UseAntialiasing = true,
HorizontalResolution = 200,
VerticalResolution = 200,
BackgroundColor = System.Drawing.Color.AliceBlue
};
options.PageSetup.AnyPage = new Page(new Aspose.Html.Drawing.Size(500, 500), new Margin(30, 20, 10, 10));
// Convert HTML to JPG
Converter.ConvertHTML(document, options, savePath);
// Prepare HTML code and save it to a file
string code = "<h1>Header 1</h1>" +
"<h2>Header 2</h2>" +
"<p>Convert HTML to Markdown</p>";
File.WriteAllText("convert.html", code);
// Call ConvertHTML() method to convert HTML to Markdown
Converter.ConvertHTML("convert.html", new MarkdownSaveOptions(), Path.Combine(OutputDir, "convert.md"));
// Prepare a path for converted file saving
string savePath = Path.Combine(OutputDir, "output-git.md");
// Prepare HTML code and save it to the file
string code = "<h1>Header 1</h1>" +
"<h2>Header 2</h2>" +
"<p>Hello, World!!</p>";
File.WriteAllText(Path.Combine(OutputDir, "document.html"), code);
// Call ConvertHTML() method to convert HTML to Markdown
Converter.ConvertHTML(Path.Combine(OutputDir, "document.html"), MarkdownSaveOptions.Git, savePath);
// Prepare a path to a source HTML file
string documentPath = Path.Combine(DataDir, "drawing.html");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "drawing-output.mht");
// Initialize an HTML document from the file
using HTMLDocument document = new HTMLDocument(documentPath);
// Initialize MHTMLSaveOptions
MHTMLSaveOptions options = new MHTMLSaveOptions();
// Convert HTML to MHTML
Converter.ConvertHTML(document, options, savePath);
// Invoke the ConvertHTML() method to convert HTML to MHTML
Converter.ConvertHTML(@"<h1>Hellow, Word!</h1>", ".", new MHTMLSaveOptions(), Path.Combine(OutputDir, "convert-with-single-line.mht"));
// Prepare a path to a source HTML file
string documentPath = Path.Combine(DataDir, "spring.html");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "spring-output.pdf");
// Initialize an HTML document from the file
using HTMLDocument document = new HTMLDocument(documentPath);
// Initialize PdfSaveOptions
PdfSaveOptions options = new PdfSaveOptions();
// Convert HTML to PDF
Converter.ConvertHTML(document, options, savePath);
// Prepare a path to an HTML source file
string sourcePath = Path.Combine(DataDir, "SampleHtmlForm.html");
// Initialize an HTML document from the file
using HTMLDocument document = new HTMLDocument(sourcePath);
// Prepare PDF save options
PdfSaveOptions options = new PdfSaveOptions
{
// Flatten all form fields
FormFieldBehaviour = FormFieldBehaviour.Flattened
};
// Prepare a path to the result file
string resultPath = Path.Combine(OutputDir, "form-flattened.pdf");
// Convert HTML to PDF
Converter.ConvertHTML(document, options, resultPath);
// Initialize an HTML document from a URL
using HTMLDocument document = new HTMLDocument("https://docs.aspose.com/html/files/document.html");
// Initialize PdfSaveOptions
PdfSaveOptions options = new PdfSaveOptions();
// Configure PDF encryption settings
options.Encryption = new PdfEncryptionInfo(
ownerPassword: "owner123",
userPassword: "user123",
permissions: PdfPermissions.PrintDocument | PdfPermissions.ExtractContent,
encryptionAlgorithm: PdfEncryptionAlgorithm.RC4_128
);
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "document-with-password.pdf");
// Convert HTML to PDF
Converter.ConvertHTML(document, options, savePath);
// Invoke the ConvertHTML() method to convert HTML to PDF
Converter.ConvertHTML(@"<h1>Convert HTML to PDF!</h1>", ".", new PdfSaveOptions(), Path.Combine(OutputDir, "convert-with-single-line.pdf"));
// Prepare a path to a source HTML file
string documentPath = Path.Combine(DataDir, "file.html");
// Initialize an HTML document from the file
using HTMLDocument document = new HTMLDocument(documentPath);
// Create an instance of HTML Renderer
using HtmlRenderer renderer = new HtmlRenderer();
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "convert-html-options.pdf");
// Create the instance of Rendering Options and set a custom page-size
PdfRenderingOptions options = new PdfRenderingOptions();
options.PageSetup.AnyPage = new Page(new Size(600, 200));
options.Encryption = new PdfEncryptionInfo(
"user_pwd",
"owner_pwd",
PdfPermissions.PrintDocument,
PdfEncryptionAlgorithm.RC4_128);
// Create an instance of PDF device
using PdfDevice device = new PdfDevice(options, savePath);
// Render HTML to PDF
renderer.Render(device, document);
// Load an HTML document from file or string
using (HTMLDocument document = new HTMLDocument("<h1>Hello, PDF!</h1>", "."))
{
// Initialize PDF rendering options
PdfSaveOptions options = new PdfSaveOptions();
// Set PDF document information (metadata)
options.DocumentInfo.Title = "Sample PDF Title";
options.DocumentInfo.Author = "Aspose.HTML for .NET";
options.DocumentInfo.Subject = "HTML to PDF Example";
options.DocumentInfo.Keywords = "Aspose, HTML, PDF, conversion";
// Set output file path
string outputPath = Path.Combine(OutputDir, "document.pdf");
// Convert HTML to PDF
Converter.ConvertHTML(document, options, outputPath);
}
Console.WriteLine("PDF created successfully.");
// Prepare a path to a source HTML file
string documentPath = Path.Combine(DataDir, "nature.html");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "nature-output.png");
// Initialize an HTML document from the file
using HTMLDocument document = new HTMLDocument(documentPath);
// Create an instance of the ImageSaveOptions class
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Png);
// Convert HTML to PNG
Converter.ConvertHTML(document, options, savePath);
// Invoke the ConvertHTML() method to convert HTML to PNG
Converter.ConvertHTML(@"<h1>Convert HTML to PNG!</h1>", ".", new ImageSaveOptions(), Path.Combine(OutputDir, "convert-with-single-line.png"));
// Prepare a path to a source HTML file
string documentPath = Path.Combine(DataDir, "nature.html");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "nature-output-options.png");
// Initialize an HTML document from the file
using HTMLDocument document = new HTMLDocument(documentPath);
// Initialize ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions()
{
UseAntialiasing = false,
HorizontalResolution = 100,
VerticalResolution = 100,
BackgroundColor = System.Drawing.Color.Beige
};
// Convert HTML to PNG
Converter.ConvertHTML(document, options, savePath);
// Prepare a path to a source HTML file
string documentPath = Path.Combine(DataDir, "nature.html");
// Prepare a path for converted file saving
string savePath = Path.Combine(OutputDir, "nature-output.tiff");
// Initialize an HTML document from the file
using HTMLDocument document = new HTMLDocument(documentPath);
// Create an instance of the ImageSaveOptions class
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Tiff);
// Convert HTML to TIFF
Converter.ConvertHTML(document, options, savePath);
string documentPath = Path.Combine(DataDir, "nature.html");
string savePath = Path.Combine(OutputDir, "nature-output-options.tiff");
// Initialize an HTML Document from the html file
using HTMLDocument document = new HTMLDocument(documentPath);
// Initialize ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Tiff)
{
Compression = Compression.None,
BackgroundColor = System.Drawing.Color.Bisque,
HorizontalResolution = 150,
VerticalResolution = 150,
UseAntialiasing = true,
};
// Convert HTML to TIFF
Converter.ConvertHTML(document, options, savePath);
// Prepare a path to a source HTML file
string documentPath = Path.Combine(DataDir, "canvas.html");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "canvas-output.xps");
// Initialize an HTML document from the file
using HTMLDocument document = new HTMLDocument(documentPath);
// Initialize XpsSaveOptions
XpsSaveOptions options = new XpsSaveOptions();
// Convert HTML to XPS
Converter.ConvertHTML(document, options, savePath);
// Invoke the ConvertHTML() method to convert the HTML code to XPS
Converter.ConvertHTML(@"<h1>Convert HTML to XPS!</h1>", ".", new XpsSaveOptions(), Path.Combine(OutputDir, "convert-with-single-line.xps"));
// Invoke the ConvertHTML() method to convert HTML to DOCX
Converter.ConvertHTML(@"<h1>Convert HTML to DOCX!</h1>", ".", new DocSaveOptions(), Path.Combine(OutputDir, "convert-with-single-line.docx"));
// 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);
// AI response in Markdown format with the text, code example and link
string markdownContent = "# How to Convert a Markdown File to HTML\n" +
"Markdown is a lightweight markup language used for formatting text. If you need to convert a Markdown file to an HTML document, you can use **Aspose.HTML for .NET**.\n\n" +
"## Steps to Convert\n" +
"1. Load the Markdown file.\n" +
"2. Convert it to an HTML document.\n" +
"3. Save the output file.\n\n" +
"## Example Code\n" +
"```csharp\n" +
"// Convert a Markdown file to HTML\n" +
"Converter.ConvertMarkdown(\"input.md\", \"output.html\");\n" +
"```\n\n" +
"For more details, refer to the [official documentation](https://docs.aspose.com/html/net/convert-markdown-to-html/).\n";
// Create a memory stream from the Markdown string
using (MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(markdownContent)))
{
// Convert Markdown to HTML
HTMLDocument document = Converter.ConvertMarkdown(stream, "");
// Ensure the document has a <head> element
HTMLHeadElement head = document.QuerySelector("head") as HTMLHeadElement;
if (head == null)
{
head = document.CreateElement("head") as HTMLHeadElement;
document.DocumentElement.InsertBefore(head, document.Body);
}
// Create a <style> element with CSS styles
string cssStyles = "body { font-family: Open Sans, sans-serif; max-width: 800px; margin: auto; padding: 20px; background-color: #f9f9f9; }\n" +
"h1, h2 { color: #333; }\n" +
"p, li { font-size: 14px; }\n" +
"code, pre { font-family: Consolas, monospace; color: #f8f8f2; background-color: #272822; padding: 10px; border-radius: 5px; display: block; }\n";
HTMLStyleElement styleElement = document.CreateElement("style") as HTMLStyleElement;
styleElement.TextContent = cssStyles;
// Append the <style> element to the <head>
head.AppendChild(styleElement);
// Save the resulting HTML file
string outputPath = Path.Combine(OutputDir, "chartAnswer.html");
document.Save(outputPath);
// Print the HTML content to the console
Console.WriteLine(document.DocumentElement.OuterHTML);
Console.WriteLine("Conversion completed. HTML saved at " + outputPath);
}
// Prepare a path to a source Markdown file
string sourcePath = Path.Combine(DataDir, "nature.md");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "nature-output.html");
// Convert Markdown to HTML
Converter.ConvertMarkdown(sourcePath, savePath);
// Prepare a path to a source Markdown file
string sourcePath = Path.Combine(DataDir, "document.md");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "output.bmp");
// Convert Markdown to HTML
using HTMLDocument document = Converter.ConvertMarkdown(sourcePath);
// Convert HTML document to BMP image file format
Converter.ConvertHTML(document, new ImageSaveOptions(ImageFormat.Bmp), savePath);
// Prepare a path to a source Markdown file
string sourcePath = Path.Combine(OutputDir, "document.md");
// Prepare a simple Markdown example
string code = "### Hello, World!" +
"\r\n" +
"Convert Markdown to DOCX!";
// Create a Markdown file
File.WriteAllText(sourcePath, code);
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "document-output.docx");
// Convert Markdown to HTML document
using HTMLDocument document = Converter.ConvertMarkdown(sourcePath);
// Convert HTML document to DOCX file format
Converter.ConvertHTML(document, new DocSaveOptions(), savePath);
// Prepare a path to a source Markdown file
string sourcePath = Path.Combine(DataDir, "nature.md");
// Prepare a path for converted DOCX file saving
string savePath = Path.Combine(OutputDir, "nature-output.docx");
// Convert Markdown to HTML
using HTMLDocument document = Converter.ConvertMarkdown(sourcePath);
// Initialize DocSaveOptions. Set up the page-size 500x1000 pixels and margins
DocSaveOptions options = new DocSaveOptions();
options.PageSetup.AnyPage = new Page(new Aspose.Html.Drawing.Size(500, 1000), new Margin(20, 20, 10, 10));
// Convert the HTML document to DOCX file format
Converter.ConvertHTML(document, options, savePath);
// Prepare a path to a source Markdown file
string sourcePath = Path.Combine(DataDir, "document.md");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "output.gif");
// Convert Markdown to HTML
using HTMLDocument document = Converter.ConvertMarkdown(sourcePath);
// Convert HTML document to GIF image file format
Converter.ConvertHTML(document, new ImageSaveOptions(ImageFormat.Gif), savePath);
// Prepare a path to a source Markdown file
string sourcePath = Path.Combine(OutputDir, "document.md");
// Prepare a simple Markdown example
string code = "### Hello, World!" +
"\r\n" +
"[visit applications](https://products.aspose.app/html/family)";
// Create a Markdown file
File.WriteAllText(sourcePath, code);
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "document-output.html");
// Convert Markdown to HTML document
Converter.ConvertMarkdown(sourcePath, savePath);
// Prepare a path to a source Markdown file
string sourcePath = Path.Combine(OutputDir, "document.md");
// Prepare a simple Markdown example
string code = "### Hello, World!" +
"\r\n" +
"[visit applications](https://products.aspose.app/html/family)";
// Create a Markdown file
File.WriteAllText(sourcePath, code);
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "document-output.jpg");
// Convert Markdown to HTML
using HTMLDocument document = Converter.ConvertMarkdown(sourcePath);
// Convert HTML document to JPG image file format
Converter.ConvertHTML(document, new ImageSaveOptions(ImageFormat.Jpeg), savePath);
// Prepare a path to a source Markdown file
string sourcePath = Path.Combine(DataDir, "nature.md");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "nature-options.jpg");
// Convert Markdown to HTML
using HTMLDocument document = Converter.ConvertMarkdown(sourcePath);
// Initialize ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Jpeg)
{
UseAntialiasing = true,
HorizontalResolution = 200,
VerticalResolution = 200,
BackgroundColor = System.Drawing.Color.AliceBlue
};
options.PageSetup.AnyPage = new Page(new Aspose.Html.Drawing.Size(600, 950), new Margin(30, 20, 10, 10));
// Convert HTML to JPG
Converter.ConvertHTML(document, options, savePath);
// Prepare a path to a source Markdown file
string sourcePath = Path.Combine(OutputDir, "document.md");
// Prepare a simple Markdown example
string code = "### Hello, World!" +
"\r\n" +
"[visit applications](https://products.aspose.app/html/applications)";
// Create a Markdown file
File.WriteAllText(sourcePath, code);
// Convert Markdown to HTML
using HTMLDocument document = Converter.ConvertMarkdown(sourcePath);
// Prepare a path for converted PDF file saving
string savePath = Path.Combine(OutputDir, "document-output.pdf");
// Convert the HTML document to PDF file format
Converter.ConvertHTML(document, new PdfSaveOptions(), savePath);
// Prepare a path to a source Markdown file
string sourcePath = Path.Combine(DataDir, "nature.md");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "nature-output.pdf");
// Convert Markdown to HTML
using HTMLDocument document = Converter.ConvertMarkdown(sourcePath);
// Initialize PdfSaveOptions. Set up the resolutions, JpegQuality and change the background color to AliceBlue
PdfSaveOptions options = new PdfSaveOptions()
{
HorizontalResolution = 200,
VerticalResolution = 200,
BackgroundColor = System.Drawing.Color.AliceBlue,
JpegQuality = 100
};
// Convert the HTML document to PDF file format
Converter.ConvertHTML(document, options, savePath);
// Prepare a path to a source Markdown file
string sourcePath = Path.Combine(DataDir, "document.md");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "output.png");
// Convert Markdown to HTML
using HTMLDocument document = Converter.ConvertMarkdown(sourcePath);
// Convert HTML document to PNG image file format
Converter.ConvertHTML(document, new ImageSaveOptions(), savePath);
// Prepare a path to a source Markdown file
string sourcePath = Path.Combine(DataDir, "document.md");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "output.tiff");
// Convert Markdown to HTML
using HTMLDocument document = Converter.ConvertMarkdown(sourcePath);
// Convert HTML document to TIFF image file format
Converter.ConvertHTML(document, new ImageSaveOptions(ImageFormat.Tiff), savePath);
// Prepare a path to a source Markdown file
string sourcePath = Path.Combine(OutputDir, "document.md");
// Prepare a simple Markdown example
string code = "### Hello, World!" +
"\r\n" +
"[visit applications](https://products.aspose.app/html/applications)";
// Create a Markdown file
File.WriteAllText(sourcePath, code);
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "document-output.xps");
// Convert Markdown to HTML
using HTMLDocument document = Converter.ConvertMarkdown(sourcePath);
// Convert the HTML document to XPS file format
Converter.ConvertHTML(document, new XpsSaveOptions(), savePath);
// Prepare a path to a source Markdown file
string sourcePath = Path.Combine(DataDir, "nature.md");
// Prepare a path for converted PDF file saving
string savePath = Path.Combine(OutputDir, "nature-output.xps");
// Convert Markdown to HTML
using HTMLDocument document = Converter.ConvertMarkdown(sourcePath);
// Initialize XpsSaveOptions. Set up the resilutions, page-size, margins and change the background color to AntiqueWhite
XpsSaveOptions options = new XpsSaveOptions()
{
HorizontalResolution = 200,
VerticalResolution = 200,
BackgroundColor = System.Drawing.Color.AntiqueWhite
};
options.PageSetup.AnyPage = new Page(new Aspose.Html.Drawing.Size(Length.FromInches(5.0f), Length.FromInches(10.0f)), new Margin(30, 20, 10, 10));
// Convert HTML to XPS file format
Converter.ConvertHTML(document, options, savePath);
// Open an existing MHTML file for reading
using FileStream stream = File.OpenRead(DataDir + "sample.mht");
// Create an instance of ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Bmp);
// Call the ConvertMHTML() method to convert MHTML to BMP
Converter.ConvertMHTML(stream, options, Path.Combine(OutputDir, "sample-output.bmp"));
// Open an existing MHTML file for reading
using FileStream stream = File.OpenRead(DataDir + "sample.mht");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "sample-output.docx");
// Create an instance of DocSaveOptions
DocSaveOptions options = new DocSaveOptions();
// Call the ConvertMHTML() method to convert MHTML to DOCX
Converter.ConvertMHTML(stream, options, savePath);
// Open an existing MHTML file for reading
using FileStream stream = File.OpenRead(DataDir + "sample.mht");
// Invoke the ConvertMHTML() method to convert MHTML to DOCX
Converter.ConvertMHTML(stream, new DocSaveOptions(), Path.Combine(OutputDir, "convert-by-two-lines.docx"));
// Open an existing MHTML file for reading
using FileStream stream = File.OpenRead(DataDir + "sample.mht");
// Create an instance of ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Gif);
// Call the ConvertMHTML() method to convert MHTML to GIF
Converter.ConvertMHTML(stream, options, Path.Combine(OutputDir, "sample-output.gif"));
// Open an existing MHTML file for reading
using FileStream stream = File.OpenRead(DataDir + "sample.mht");
// Create an instance of MHTML Renderer
using MhtmlRenderer renderer = new MhtmlRenderer();
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "convert-mhtml.png");
// Create the instance of Rendering Options and set a custom page-size and background color
ImageRenderingOptions options = new ImageRenderingOptions();
options.PageSetup.AnyPage = new Page(new Size(200, 100));
options.BackgroundColor = System.Drawing.Color.Bisque;
// Create an instance of ImageDevice
using ImageDevice device = new ImageDevice(options, savePath);
// Convert MHTML to PNG
renderer.Render(device, stream);
// Open an existing MHTML file for reading
using FileStream stream = File.OpenRead(DataDir + "sample.mht");
// Create an instance of ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Jpeg);
// Call the ConvertMHTML() method to convert MHTML to JPG
Converter.ConvertMHTML(stream, options, Path.Combine(OutputDir, "sample-output.jpg"));
// Open an existing MHTML file for reading
using FileStream stream = File.OpenRead(DataDir + "sample.mht");
// Invoke the ConvertMHTML() method to convert MHTML to JPG
Converter.ConvertMHTML(stream, new ImageSaveOptions(ImageFormat.Jpeg), Path.Combine(OutputDir, "convert-by-two-lines.jpg"));
// Open an existing MHTML file for reading
using FileStream stream = File.OpenRead(DataDir + "sample.mht");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "sample-output.pdf");
// Create an instance of PdfSaveOptions
PdfSaveOptions options = new PdfSaveOptions();
// Call the ConvertMHTML() method to convert MHTML to PDF
Converter.ConvertMHTML(stream, options, savePath);
// Prepare a path to an MHTML source file
string sourcePath = Path.Combine(DataDir, "SampleHtmlForm.mhtml");
// Initialize PDF save options
PdfSaveOptions options = new PdfSaveOptions
{
// Flatten all form fields
FormFieldBehaviour = FormFieldBehaviour.Interactive
};
// Prepare a path to the result file
string resultPath = Path.Combine(OutputDir, "document-flattened.pdf");
// Convert MHTML to PDF
Converter.ConvertMHTML(sourcePath, options, resultPath);
// Open an existing MHTML file for reading
using FileStream stream = File.OpenRead(DataDir + "sample.mht");
// Invoke the ConvertMHTML() method to convert MHTML to PDF
Converter.ConvertMHTML(stream, new PdfSaveOptions(), Path.Combine(OutputDir, "convert-by-two-lines.pdf"));
// Open an existing MHTML file for reading
using FileStream stream = File.OpenRead(DataDir + "sample.mht");
// Create an instance of MHTML Renderer
using MhtmlRenderer renderer = new MhtmlRenderer();
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "convert-mhtml-options.pdf");
// Create the instance of Rendering Options and set a custom page-size and background color
PdfRenderingOptions options = new PdfRenderingOptions();
options.PageSetup.AnyPage = new Page(new Size(600, 200));
options.BackgroundColor = System.Drawing.Color.Azure;
// Create an instance of PDF device
using PdfDevice device = new PdfDevice(options, savePath);
// Convert MHTML to PDF
renderer.Render(device, stream);
// Open an existing MHTML file for reading
using FileStream stream = File.OpenRead(DataDir + "sample.mht");
// Create an instance of ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Png);
// Call the ConvertMHTML() method to convert MHTML to PNG
Converter.ConvertMHTML(stream, options, Path.Combine(OutputDir, "sample-output.png"));
// Open an existing MHTML file for reading
using FileStream stream = File.OpenRead(DataDir + "sample.mht");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "sample-options.tiff");
// Create an instance of ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Tiff);
// Call the ConvertMHTML() method to convert MHTML to TIFF
Converter.ConvertMHTML(stream, options, savePath);
// Open an existing MHTML file for reading
using FileStream stream = File.OpenRead(DataDir + "sample.mht");
// Prepare a path for converted file saving
string savePath = Path.Combine(OutputDir, "sample-output.xps");
// Create an instance of XpsSaveOptions
XpsSaveOptions options = new XpsSaveOptions();
// Call the ConvertMHTML() method to convert MHTML to XPS
Converter.ConvertMHTML(stream, options, savePath);
// Open an existing MHTML file for reading
using FileStream stream = File.OpenRead(DataDir + "sample.mht");
// Invoke the ConvertMHTML() method to convert the MHTML code to XPS
Converter.ConvertMHTML(stream, new XpsSaveOptions(), Path.Combine(OutputDir, "convert-by-two-lines.xps"));
// Prepare SVG code
string code = "<svg xmlns='http://www.w3.org/2000/svg'>" +
"<circle cx ='100' cy ='100' r ='50' fill='none' stroke='red' stroke-width='10' />" +
"</svg>";
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "circle.bmp");
// Create an instance of the ImageSaveOptions class
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Bmp);
// Convert SVG to BMP
Converter.ConvertSVG(code, ".", options, savePath);
// Invoke the ConvertSVG() method for SVG to BMP conversion
Converter.ConvertSVG(Path.Combine(DataDir, "shapes.svg"), new ImageSaveOptions(ImageFormat.Bmp), Path.Combine(OutputDir, "convert-with-single-line.bmp"));
// Prepare SVG code
string code = "<svg xmlns='http://www.w3.org/2000/svg'>" +
"<circle cx ='100' cy ='100' r ='50' fill='none' stroke='red' stroke-width='10' />" +
"</svg>";
// Prepare a path for converted file saving
string savePath = Path.Combine(OutputDir, "circle.docx");
// Initialize DocSaveOptions
DocSaveOptions options = new DocSaveOptions();
// Convert SVG to DOCX
Converter.ConvertSVG(code, ".", options, savePath);
// Invoke the ConvertSVG() method to convert SVG to DOCX
Converter.ConvertSVG(Path.Combine(DataDir, "shapes.svg"), new DocSaveOptions(), Path.Combine(OutputDir, "convert-with-single-line.docx"));
// Prepare SVG code
string code = "<svg xmlns='http://www.w3.org/2000/svg'>" +
"<circle cx ='100' cy ='100' r ='55' fill='pink' stroke='red' stroke-width='8' />" +
"</svg>";
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "circle.gif");
// Create an instance of the ImageSaveOptions class
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Gif);
// Convert SVG to GIF
Converter.ConvertSVG(code, ".", options, savePath);
// Invoke the ConvertSVG() method for SVG to GIF conversion
Converter.ConvertSVG(Path.Combine(DataDir, "shapes.svg"), new ImageSaveOptions(ImageFormat.Gif), Path.Combine(OutputDir, "convert-with-single-line.gif"));
// Prepare SVG code
string code = "<svg xmlns='http://www.w3.org/2000/svg'>" +
"<circle cx ='100' cy ='100' r ='55' fill='green' stroke='red' stroke-width='10' />" +
"</svg>";
// Prepare a path for converted file saving
string savePath = Path.Combine(OutputDir, "circle.jpg");
// Create an instance of the ImageSaveOptions class
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Jpeg);
// Convert SVG to JPG
Converter.ConvertSVG(code, ".", options, savePath);
// Invoke the ConvertSVG() method for SVG to JPG conversion
Converter.ConvertSVG(Path.Combine(DataDir, "shapes.svg"), new ImageSaveOptions(ImageFormat.Jpeg), Path.Combine(OutputDir, "convert-with-single-line.jpg"));
// Prepare SVG code
string code = "<svg xmlns='http://www.w3.org/2000/svg'>" +
"<circle cx ='100' cy ='100' r ='50' fill='none' stroke='red' stroke-width='5' />" +
"</svg>";
// Prepare a path for converted file saving
string savePath = Path.Combine(OutputDir, "circle.pdf");
// Initialize PdfSaveOptions
PdfSaveOptions options = new PdfSaveOptions();
// Convert SVG to PDF
Converter.ConvertSVG(code, ".", options, savePath);
// Invoke the ConvertSVG() method for SVG to PDF conversion
Converter.ConvertSVG(Path.Combine(DataDir, "shapes.svg"), new PdfSaveOptions(), Path.Combine(OutputDir, "convert-with-single-line.pdf"));
// Prepare SVG code
string code = "<svg xmlns='http://www.w3.org/2000/svg'>" +
"<circle cx ='100' cy ='100' r ='60' fill='none' stroke='red' stroke-width='10' />" +
"</svg>";
// 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);
// Invoke the ConvertSVG() method for SVG to PNG conversion
Converter.ConvertSVG(Path.Combine(DataDir, "shapes.svg"), new ImageSaveOptions(), Path.Combine(OutputDir, "convert-with-single-line.png"));
// Prepare SVG code
string code = "<svg xmlns='http://www.w3.org/2000/svg'>" +
"<circle cx ='100' cy ='100' r ='50' fill='pink' stroke='red' stroke-width='10' />" +
"</svg>";
// Prepare a path for converted file saving
string savePath = Path.Combine(OutputDir, "circle.tiff");
// Create an instance of the ImageSaveOptions class
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Tiff);
// Convert SVG to TIFF
Converter.ConvertSVG(code, ".", options, savePath);
// Invoke the ConvertSVG() method for SVG to TIFF conversion
Converter.ConvertSVG(Path.Combine(DataDir, "shapes.svg"), new ImageSaveOptions(ImageFormat.Tiff), Path.Combine(OutputDir, "convert-with-single-line.tiff"));
// Prepare SVG code
string code = "<svg xmlns='http://www.w3.org/2000/svg'>" +
"<circle cx ='100' cy ='100' r ='60' fill='none' stroke='red' stroke-width='10' />" +
"</svg>";
// Prepare a path for converted file saving
string savePath = Path.Combine(OutputDir, "circle.xps");
// Initialize XpsSaveOptions
XpsSaveOptions options = new XpsSaveOptions();
// Convert SVG to XPS
Converter.ConvertSVG(code, ".", options, savePath);
// Invoke the ConvertSVG() method to convert SVG to XPS
Converter.ConvertSVG(Path.Combine(DataDir, "shapes.svg"), new XpsSaveOptions(), Path.Combine(OutputDir, "convert-with-single-line.xps"));
// Prepare a path to an HTML source file
string sourcePath = Path.Combine(DataDir, "template.html");
// Prepare a path to an xml template data file
string templateDataPath = Path.Combine(DataDir, "templateData.xml");
// Define TemplateData object instance
TemplateData templateData = new TemplateData(templateDataPath);
// Prepare a path to the result file
string resultPath = Path.Combine(OutputDir, "result.html");
// Define default TemplateLoadOptions object
TemplateLoadOptions options = new TemplateLoadOptions();
// Initialize an HTML document as conversion source
HTMLDocument document = new HTMLDocument(sourcePath, new Configuration());
// Convert template to HTML
Converter.ConvertTemplate(document, templateData, options, resultPath);
// Clear resources
document.Dispose();
// Convert template to HTML
Converter.ConvertTemplate(
Path.Combine(DataDir, "template.html"),
new TemplateData(Path.Combine(DataDir, "data-source.json")),
new TemplateLoadOptions(),
Path.Combine(OutputDir, "template-with-single-line.html")
);
// Add this line before you try to use the 'IBM437' encoding
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
// Prepare path to a source zip file
string documentPath = Path.Combine(DataDir, "test.zip");
// Prepare path for converted file saving
string savePath = Path.Combine(OutputDir, "zip-to-jpg.jpg");
// Create an instance of ZipArchiveMessageHandler
using ZipArchiveMessageHandler zip = new ZipArchiveMessageHandler(documentPath);
// Create an instance of the Configuration class
using Configuration configuration = new Configuration();
// Add ZipArchiveMessageHandler to the chain of existing message handlers
configuration
.GetService<INetworkService>()
.MessageHandlers.Add(zip);
// Initialize an HTML document with specified configuration
using HTMLDocument document = new HTMLDocument("zip:///test.html", configuration);
// Create an instance of Rendering Options
ImageRenderingOptions options = new ImageRenderingOptions()
{
Format = ImageFormat.Jpeg
};
// Create an instance of Image Device
using ImageDevice device = new ImageDevice(options, savePath);
// Render ZIP to JPG
document.RenderTo(device);
// Add this line before you try to use the 'IBM437' encoding
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
// Prepare path to a source zip file
string documentPath = Path.Combine(DataDir, "test.zip");
// Prepare path for converted file saving
string savePath = Path.Combine(OutputDir, "zip-to-pdf.pdf");
// Create an instance of ZipArchiveMessageHandler
using ZipArchiveMessageHandler zip = new ZipArchiveMessageHandler(documentPath);
// Create an instance of the Configuration class
using Configuration configuration = new Configuration();
// Add ZipArchiveMessageHandler to the chain of existing message handlers
configuration
.GetService<INetworkService>()
.MessageHandlers.Add(zip);
// Initialize an HTML document with specified configuration
using HTMLDocument document = new HTMLDocument("zip:///test.html", configuration);
// Create the PDF Device
using PdfDevice device = new PdfDevice(savePath);
// Render ZIP to PDF
document.RenderTo(device);
// Create an instance of the Configuration class
using Configuration configuration = new Configuration();
// Add the LogMessageHandler to the chain of existing message handlers
INetworkService service = configuration.GetService<INetworkService>();
MessageHandlerCollection handlers = service.MessageHandlers;
handlers.Insert(0, new LogMessageHandler());
// Prepare path to a source document file
string documentPath = Path.Combine(DataDir, "input.htm");
// Initialize an HTML document with specified configuration
using HTMLDocument document = new HTMLDocument(documentPath, configuration);
// 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"));
}
// 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);
}
// 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);
}
// 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);
}
// This message handler used basic autentifications request
public class CredentialHandler : MessageHandler
{
// Override the Invoke() method
public override void Invoke(INetworkOperationContext context)
{
context.Request.Credentials = new NetworkCredential("username", "securelystoredpassword");
context.Request.PreAuthenticate = true;
Next(context);
}
}
// 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);
}
}
// 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));
// Prepare HTML code
string code = @"
<div class='happy'>
<div>
<span>Hello,</span>
</div>
</div>
<p class='happy'>
<span>World!</span>
</p>
";
// Initialize a document based on the prepared code
using (HTMLDocument document = new HTMLDocument(code, "."))
{
// Here we create a CSS Selector that extracts all elements whose 'class' attribute equals 'happy' and their child <span> elements
NodeList elements = document.QuerySelectorAll(".happy span");
// Iterate over the resulted list of elements
foreach (HTMLElement element in elements)
{
Console.WriteLine(element.InnerHTML);
// output: Hello,
// output: World!
}
}
// Define the CustomSchemaMessageFilter class that is derived from the MessageFilter class
class CustomSchemaMessageFilter : MessageFilter
{
private readonly string schema;
public CustomSchemaMessageFilter(string schema)
{
this.schema = schema;
}
// Override the Match() method
public override bool Match(INetworkOperationContext context)
{
return string.Equals(schema, context.Request.RequestUri.Protocol.TrimEnd(':'));
}
}
// Define the CustomSchemaMessageHandler class that is derived from the MessageHandler class
abstract class CustomSchemaMessageHandler : MessageHandler
{
// Initialize an instance of the CustomSchemaMessageHandler class
protected CustomSchemaMessageHandler(string schema)
{
Filters.Add(new CustomSchemaMessageFilter(schema));
}
}
// 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++;
}
}
}
// Prepare HTML code and save it to a file
string code = "<span style=\"background-image:url('https://httpbin.org/image/jpeg')\">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"));
}
}
// 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"));
}
// 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"));
}
// 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);
}
// 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);
}
}
// 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);
}
}
// Create an instance of MemoryStreamProvider
using MemoryStreamProvider streamProvider = new MemoryStreamProvider();
// Open an existing EPUB file for reading
using FileStream stream = File.OpenRead(DataDir + "input.epub");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "stream-provider.docx");
// Convert EPUB to DOCX by using the MemoryStreamProvider class
Converter.ConvertEPUB(stream, new DocSaveOptions(), streamProvider);
// Get access to the memory stream that contains the result data
MemoryStream memory = streamProvider.Streams.First();
memory.Seek(0, SeekOrigin.Begin);
// Flush the result data to the output file
using (FileStream fs = File.Create(savePath))
{
memory.CopyTo(fs);
}
// Open an existing EPUB file for reading
using FileStream stream = File.OpenRead(DataDir + "input.epub");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "input-options.docx");
// Create an instance of DocSaveOptions. Set A5 as a page-size
DocSaveOptions options = new DocSaveOptions();
options.PageSetup.AnyPage = new Page(new Aspose.Html.Drawing.Size(Length.FromInches(8.3f), Length.FromInches(5.8f)));
// Call the ConvertEPUB() method to convert EPUB to DOCX
Converter.ConvertEPUB(stream, options, savePath);
// Open an existing EPUB file for reading
using FileStream stream = File.OpenRead(DataDir + "input.epub");
// Create an instance of MemoryStreamProvider
using MemoryStreamProvider streamProvider = new MemoryStreamProvider();
// Convert HTML to JPG using the MemoryStreamProvider
Converter.ConvertEPUB(stream, new ImageSaveOptions(ImageFormat.Jpeg), streamProvider);
// Get access to the memory streams that contain the resulted data
for (int i = 0; i < streamProvider.Streams.Count; i++)
{
MemoryStream memory = streamProvider.Streams[i];
memory.Seek(0, System.IO.SeekOrigin.Begin);
// Flush the page to the output file
using (FileStream fs = File.Create(Path.Combine(OutputDir, $"input-page_{i + 1}.jpg")))
{
memory.CopyTo(fs);
}
}
// Create an instance of MemoryStreamProvider
using MemoryStreamProvider streamProvider = new MemoryStreamProvider();
// Open an existing EPUB file for reading
using FileStream stream = File.OpenRead(DataDir + "input.epub");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "stream-provider.pdf");
// Convert EPUB to PDF by using the MemoryStreamProvider class
Converter.ConvertEPUB(stream, new PdfSaveOptions(), streamProvider);
// Get access to the memory stream that contains the result data
MemoryStream memory = streamProvider.Streams.First();
memory.Seek(0, SeekOrigin.Begin);
// Flush the result data to the output file
using (FileStream fs = File.Create(savePath))
{
memory.CopyTo(fs);
}
// Open an existing EPUB file for reading
using FileStream stream = File.OpenRead(DataDir + "input.epub");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "input-options.pdf");
// Create an instance of PdfSaveOptions. Set up the page-size and change the background color to AliceBlue
PdfSaveOptions options = new PdfSaveOptions()
{
PageSetup =
{
AnyPage = new Page()
{
Size = new Aspose.Html.Drawing.Size(Length.FromPixels(1000), Length.FromPixels(1000))
}
},
BackgroundColor = System.Drawing.Color.AliceBlue
};
// Call the ConvertEPUB() method to convert EPUB to PDF
Converter.ConvertEPUB(stream, options, savePath);
// Open an existing EPUB file for reading
using FileStream stream = File.OpenRead(DataDir + "input.epub");
// Create an instance of MemoryStreamProvider
using MemoryStreamProvider streamProvider = new MemoryStreamProvider();
// Convert HTML to PNG using the MemoryStreamProvider
Converter.ConvertEPUB(stream, new ImageSaveOptions(), streamProvider);
// Get access to the memory streams that contain the resulted data
for (int i = 0; i < streamProvider.Streams.Count; i++)
{
MemoryStream memory = streamProvider.Streams[i];
memory.Seek(0, System.IO.SeekOrigin.Begin);
// Flush the page to the output file
using (FileStream fs = File.Create(Path.Combine(OutputDir, $"input-page_{i + 1}.png")))
{
memory.CopyTo(fs);
}
}
// Create an instance of MemoryStreamProvider
using MemoryStreamProvider streamProvider = new MemoryStreamProvider();
// Open an existing EPUB file for reading
using FileStream stream = File.OpenRead(DataDir + "input.epub");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "stream-provider.xps");
// Convert EPUB to XPS by using the MemoryStreamProvider class
Converter.ConvertEPUB(stream, new XpsSaveOptions(), streamProvider);
// Get access to the memory stream that contains the result data
MemoryStream memory = streamProvider.Streams.First();
memory.Seek(0, SeekOrigin.Begin);
// Flush the result data to the output file
using (FileStream fs = File.Create(savePath))
{
memory.CopyTo(fs);
}
// Open an existing EPUB file for reading
using FileStream stream = File.OpenRead(DataDir + "input.epub");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "input-options.xps");
// Create an instance of XpsSaveOptions. Set up the page-size and change the background color to LightGray
XpsSaveOptions options = new XpsSaveOptions()
{
PageSetup =
{
AnyPage = new Page()
{
Size = new Aspose.Html.Drawing.Size(Length.FromPixels(500), Length.FromPixels(500))
}
},
BackgroundColor = System.Drawing.Color.LightGray
};
// Call the ConvertEPUB() method to convert EPUB to XPS
Converter.ConvertEPUB(stream, options, savePath);
// Initialize a webAccessibility container
WebAccessibility webAccessibility = new WebAccessibility();
// Create an accessibillity validator with static instance for all rules from repository that match the builder settings
AccessibilityValidator validator = webAccessibility.CreateValidator(ValidationBuilder.All);
string documentPath = Path.Combine(DataDir, "input.html");
// Initialize an object of the HTMLDocument class
using (HTMLDocument document = new HTMLDocument(documentPath))
{
// Check the document
ValidationResult validationResult = validator.Validate(document);
foreach (RuleValidationResult ruleResult in validationResult.Details)
{
// list only unsuccessful rule
if (!ruleResult.Success)
{
// print the code and description of the rule
Console.WriteLine("{0}:{1} = {2}", ruleResult.Rule.Code, ruleResult.Rule.Description, ruleResult.Success);
// print the results of methods with errors
foreach (ITechniqueResult ruleDetail in ruleResult.Errors)
{
// print the code and description of the method
StringBuilder str = new StringBuilder(string.Format("\n{0}: {1} - {2}",
ruleDetail.Rule.Code, ruleDetail.Success,
ruleDetail.Rule.Description));
// get an error object
IError error = ruleDetail.Error;
// get a target object
Target target = error.Target;
// get error type and message
str.AppendFormat("\n\n\t{0} : {1}", error.ErrorTypeName, error.ErrorMessage);
if (target != null)
{
// Checking the type of the contained object for casting and working with it
if (target.TargetType == TargetTypes.CSSStyleRule)
{
ICSSStyleRule cssRule = (ICSSStyleRule)target.Item;
str.AppendFormat("\n\n\t{0}", cssRule.CSSText);
}
if (ruleDetail.Error.Target.TargetType == TargetTypes.CSSStyleSheet)
str.AppendFormat("\n\n\t{0}", ((ICSSStyleSheet)target.Item).Title);
if (ruleDetail.Error.Target.TargetType == TargetTypes.HTMLElement)
str.AppendFormat("\n\n\t{0}", ((HTMLElement)target.Item).OuterHTML);
}
Console.WriteLine(str.ToString());
}
}
}
}
// Load the HTML document from a local file
HTMLDocument document = new HTMLDocument("https://docs.aspose.com/html/net/edit-html-document/");
// Create a list to store extracted hyperlink data
List <Dictionary<string, string>> linkList = new List<Dictionary<string, string>>();
// Get all <table> elements in the document
HTMLCollection tables = document.GetElementsByTagName("table");
for (int t = 0; t < tables.Length; t++)
{
// Access the table element
Element element = tables[t];
HTMLElement htmlTable = element as HTMLElement;
if (htmlTable == null)
continue;
// Get all <a> elements (hyperlinks) within this table only
HTMLCollection links = htmlTable.GetElementsByTagName("a");
for (int i = 0; i < links.Length; i++)
{
Element link = links[i];
string href = link.GetAttribute("href");
string text = link.TextContent != null ? link.TextContent.Trim() : string.Empty;
// Add hyperlink to the result list if href exists
if (!string.IsNullOrEmpty(href))
{
Dictionary<string, string> item = new Dictionary<string, string>
{
{ "text", text },
{ "href", href }
};
linkList.Add(item);
}
}
}
// Configure JSON serializer to output indented (pretty) format
JsonSerializerOptions options = new JsonSerializerOptions
{
WriteIndented = true
};
// Serialize the link list to JSON
string json = JsonSerializer.Serialize(linkList, options);
// Ensure output directory exists
// Save the JSON to a file
string outputPath = Path.Combine(OutputDir, "links1.json");
File.WriteAllText(outputPath, json);
Console.WriteLine("Hyperlinks successfully extracted and saved to: " + outputPath);
}
// Open a document you want to download external SVGs from
using HTMLDocument document = new HTMLDocument("https://products.aspose.com/html/net/");
// Collect all image elements
HTMLCollection images = document.GetElementsByTagName("img");
// Create a distinct collection of relative image URLs
IEnumerable<string> urls = images.Select(element => element.GetAttribute("src")).Distinct();
// Filter out non SVG images
IEnumerable<string> svgUrls = urls.Where(url => url.EndsWith(".svg"));
// Create absolute SVG image URLs
IEnumerable<Url> absUrls = svgUrls.Select(src => new Url(src, document.BaseURI));
foreach (Url url in absUrls)
{
// Create a downloading request
using RequestMessage request = new RequestMessage(url);
// Download SVG image
using ResponseMessage response = document.Context.Network.Send(request);
// Check whether response is successful
if (response.IsSuccess)
{
// Save SVG image to a local file system
File.WriteAllBytes(Path.Combine(OutputDir, url.Pathname.Split('/').Last()), response.Content.ReadAsByteArray());
}
}
// Open a document you want to download icons from
using HTMLDocument document = new HTMLDocument("https://docs.aspose.com/html/net/message-handlers/");
// Collect all <link> elements
HTMLCollection links = document.GetElementsByTagName("link");
// Leave only "icon" elements
IEnumerable<Element> icons = links.Where(link => link.GetAttribute("rel") == "icon");
// Create a distinct collection of relative icon URLs
IEnumerable<string> urls = icons.Select(icon => icon.GetAttribute("href")).Distinct();
// Create absolute icon URLs
IEnumerable<Url> absUrls = urls.Select(src => new Url(src, document.BaseURI));
foreach (Url url in absUrls)
{
// Create a downloading request
using RequestMessage request = new RequestMessage(url);
// Extract icon
using ResponseMessage response = document.Context.Network.Send(request);
// Check whether a response is successful
if (response.IsSuccess)
{
// Save icon to a local file system
File.WriteAllBytes(Path.Combine(OutputDir, url.Pathname.Split('/').Last()), response.Content.ReadAsByteArray());
}
}
// Open a document you want to download images from
using HTMLDocument document = new HTMLDocument("https://docs.aspose.com/svg/net/drawing-basics/svg-shapes/");
// Collect all <img> elements
HTMLCollection images = document.GetElementsByTagName("img");
// Create a distinct collection of relative image URLs
IEnumerable<string> urls = images.Select(element => element.GetAttribute("src")).Distinct();
// Create absolute image URLs
IEnumerable<Url> absUrls = urls.Select(src => new Url(src, document.BaseURI));
foreach (Url url in absUrls)
{
// Create an image request message
using RequestMessage request = new RequestMessage(url);
// Extract image
using ResponseMessage response = document.Context.Network.Send(request);
// Check whether a response is successful
if (response.IsSuccess)
{
// Save image to a local file system
File.WriteAllBytes(Path.Combine(OutputDir, url.Pathname.Split('/').Last()), response.Content.ReadAsByteArray());
}
}
// Open a document you want to download inline SVG images from
using HTMLDocument document = new HTMLDocument("https://products.aspose.com/html/net/");
// Collect all inline SVG images
HTMLCollection images = document.GetElementsByTagName("svg");
for (int i = 0; i < images.Length; i++)
{
// Save every image to a local file system
File.WriteAllText(Path.Combine(OutputDir, $"{i}.svg"), images[i].OuterHTML);
}
// Create a template with a string of HTML code
string htmlCode = "<input type=\"checkbox\" disabled {{attr}} />";
// Set data for the template in XML format
string dataSource = "<Data><attr>checked</attr></Data>";
// Convert template to HTML
using (HTMLDocument htmlDocument = Converter.ConvertTemplate(htmlCode, string.Empty,
new TemplateData(new TemplateContentOptions(dataSource, TemplateContent.XML)),
new TemplateLoadOptions()))
{
// Request the input checkbox element that we specified in the template
HTMLInputElement input = (HTMLInputElement)htmlDocument.GetElementsByTagName("input").First();
// Check if it has a checkmark
Console.WriteLine("Checked: " + input.Checked);
Console.WriteLine("Attributes.Length: " + input.Attributes.Length);
Console.WriteLine("Attributes[0].Name: " + input.Attributes[0].Name);
Console.WriteLine("Attributes[1].Name: " + input.Attributes[1].Name);
Console.WriteLine("Attributes[2].Name: " + input.Attributes[2].Name);
/*
This example produces the following results:
Checked: True
Attributes.Length: 3
Attributes[0].Name: type
Attributes[1].Name: disabled
Attributes[2].Name: checked
*/
// Save the HTML document to a file
htmlDocument.Save(Path.Combine(OutputDir, "out-checked.html"));
// Prepare a path to the output image file
string outputPath = Path.Combine(OutputDir, "out-checked.png");
// Convert HTML to PNG using RenderTo() method
htmlDocument.RenderTo(new ImageDevice(new ImageRenderingOptions(), outputPath));
}
// 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);
// 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);
// Initialize a webAccessibility container
WebAccessibility webAccessibility = new WebAccessibility();
// Get the principle by code
Principle principle = webAccessibility.Rules.GetPrinciple("1");
// Get guideline
Guideline guideline = principle.GetGuideline("1.1");
// Get criterion by code
Criterion criterion = guideline.GetCriterion("1.1.1");
if (criterion != null)
{
Console.WriteLine("{0}:{1} - {2}", criterion.Code, criterion.Description, criterion.Level); // output: 1.1.1:Non-text Content - A
// Get all Sufficient Techniques and write to console
foreach (IRule technique in criterion.SufficientTechniques)
Console.WriteLine("{0}:{1}", technique.Code, technique.Description);
}
// Initialize a webAccessibility container
WebAccessibility webAccessibility = new WebAccessibility();
// Get the principle by code
Principle principle = webAccessibility.Rules.GetPrinciple("1");
// Get guideline 1.1
Guideline guideline = principle.GetGuideline("1.1");
if (guideline != null)
{
Console.WriteLine("{0}:{1}", guideline.Code, guideline.Description, guideline); // output: 1.1:Text Alternatives
}
// Initialize a webAccessibility container
WebAccessibility webAccessibility = new WebAccessibility();
// Get the principle by code
Principle rule = webAccessibility.Rules.GetPrinciple("1");
// Get code and description of principle
Console.WriteLine("{0}:{1}", rule.Code, rule.Description); // output: 1:Perceivable
// Initialize a webAccessibility container
WebAccessibility webAccessibility = new WebAccessibility();
// List of rule codes can contain both technique codes and principles, guidelines and criteria - all rules that implement the interface IRule
string[] rulesCodes = new string[] { "H2", "H37", "H30", "1.1", "1.2.1" };
// Get a list of IRule objects; if a rule with the specified code is not found, it will not be in the list
IList<IRule> rules = webAccessibility.Rules.GetRules(rulesCodes);
// Get code and description of rule
foreach (IRule rule in rules)
Console.WriteLine("{0}:{1}", rule.Code, rule.Description);
// 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));
// 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));
// 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));
// 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));
// 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));
// 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));
// 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));
// 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));
// 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.");
}
// Initialize an instance of HTML document from 'https://httpbin.org/forms/post' url
using (HTMLDocument document = new Aspose.Html.HTMLDocument(@"https://httpbin.org/forms/post"))
{
// 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", "[email protected]"},
{"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.
}
}
}
}
}
}
// Create an instance of MemoryStreamProvider
using MemoryStreamProvider streamProvider = new MemoryStreamProvider();
// Initialize an HTML document
using HTMLDocument document = new HTMLDocument(@"<h1>Convert HTML to DOCX File Format!</h1>", ".");
// Convert HTML to DOCX using the MemoryStreamProvider
Converter.ConvertHTML(document, new DocSaveOptions(), streamProvider);
// Get access to the memory stream that contains the result data
MemoryStream memory = streamProvider.Streams.First();
memory.Seek(0, SeekOrigin.Begin);
// Flush the result data to the output file
using (FileStream fs = File.Create(Path.Combine(OutputDir, "stream-provider.docx")))
{
memory.CopyTo(fs);
}
// Prepare a path to a source HTML file
string documentPath = Path.Combine(DataDir, "canvas.html");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "canvas-output-options.docx");
// Initialize an HTML document from the file
using HTMLDocument document = new HTMLDocument(documentPath);
// Initialize DocSaveOptions. Set up the page-size 600x400 pixels and margins
DocSaveOptions options = new DocSaveOptions();
options.PageSetup.AnyPage = new Page(new Aspose.Html.Drawing.Size(600, 400), new Margin(10, 10, 10, 10));
// Convert HTML to DOCX
Converter.ConvertHTML(document, options, savePath);
// Create an instance of MemoryStreamProvider
using MemoryStreamProvider streamProvider = new MemoryStreamProvider();
// Initialize an HTML document
using HTMLDocument document = new HTMLDocument(@"<h1>Convert HTML to JPG File Format!</h1>", ".");
// Convert HTML to JPG using the MemoryStreamProvider
Converter.ConvertHTML(document, new ImageSaveOptions(ImageFormat.Jpeg), streamProvider);
// Get access to the memory stream that contains the result data
MemoryStream memory = streamProvider.Streams.First();
memory.Seek(0, SeekOrigin.Begin);
// Flush the result data to the output file
using (FileStream fs = File.Create(Path.Combine(OutputDir, "stream-provider.jpg")))
{
memory.CopyTo(fs);
}
// Prepare HTML code with a link to another file and save it to the file as 'document.html'
string code = "<span>Hello, World!!</span> " +
"<a href='document2.html'>click</a>";
File.WriteAllText("document.html", code);
// Prepare HTML code and save it to the file as 'document2.html'
code = @"<span>Hello, World!!</span>";
File.WriteAllText("document2.html", code);
string savePath = Path.Combine(OutputDir, "output-options.mht");
// Change the value of the resource linking depth to 1 in order to convert document with directly linked resources
MHTMLSaveOptions options = new MHTMLSaveOptions()
{
ResourceHandlingOptions =
{
MaxHandlingDepth = 1
}
};
// Convert HTML to MHTML
Converter.ConvertHTML("document.html", options, savePath);
// Create an instance of MemoryStreamProvider
using MemoryStreamProvider streamProvider = new MemoryStreamProvider();
// Initialize an HTML document
using HTMLDocument document = new HTMLDocument(@"<h1>Convert HTML to PDF File Format!</h1>", ".");
// Convert HTML to PDF using the MemoryStreamProvider
Converter.ConvertHTML(document, new PdfSaveOptions(), streamProvider);
// Get access to the memory stream that contains the result data
MemoryStream memory = streamProvider.Streams.First();
memory.Seek(0, SeekOrigin.Begin);
// Flush the result data to the output file
using (FileStream fs = File.Create(Path.Combine(OutputDir, "stream-provider.pdf")))
{
memory.CopyTo(fs);
}
// Prepare a path to a source HTML file
string documentPath = Path.Combine(DataDir, "drawing.html");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "drawing-options.pdf");
// Initialize an HTML document from the file
using HTMLDocument document = new HTMLDocument(documentPath);
// Initialize PdfSaveOptions. Set up the page-size 600x300 pixels, margins, resolutions and change the background color to AliceBlue
PdfSaveOptions options = new PdfSaveOptions()
{
HorizontalResolution = 200,
VerticalResolution = 200,
BackgroundColor = System.Drawing.Color.AliceBlue,
JpegQuality = 100
};
options.PageSetup.AnyPage = new Page(new Aspose.Html.Drawing.Size(600, 300), new Margin(20, 10, 10, 10));
// Convert HTML to PDF
Converter.ConvertHTML(document, options, savePath);
// Create an instance of MemoryStreamProvider
using MemoryStreamProvider streamProvider = new MemoryStreamProvider();
// Initialize an HTML document
using HTMLDocument document = new HTMLDocument(@"<h1>Convert HTML to PNG File Format!</h1>", ".");
// Convert HTML to JPG using the MemoryStreamProvider
Converter.ConvertHTML(document, new ImageSaveOptions(ImageFormat.Png), streamProvider);
// Get access to the memory stream that contains the result data
MemoryStream memory = streamProvider.Streams.First();
memory.Seek(0, SeekOrigin.Begin);
// Flush the result data to the output file
using (FileStream fs = File.Create(Path.Combine(OutputDir, "stream-provider.png")))
{
memory.CopyTo(fs);
}
// Create an instance of MemoryStreamProvider
using MemoryStreamProvider streamProvider = new MemoryStreamProvider();
// Initialize an HTML document
using HTMLDocument document = new HTMLDocument(@"<h1>Convert HTML to XPS File Format!</h1>", ".");
// Convert HTML to XPS using the MemoryStreamProvider
Converter.ConvertHTML(document, new XpsSaveOptions(), streamProvider);
// Get access to the memory stream that contains the result data
MemoryStream memory = streamProvider.Streams.First();
memory.Seek(0, SeekOrigin.Begin);
// Flush the result data to the output file
using (FileStream fs = File.Create(Path.Combine(OutputDir, "stream-provider.xps")))
{
memory.CopyTo(fs);
}
// Prepare a path for converted file saving
string savePath = Path.Combine(OutputDir, "inline-html.md");
// Prepare HTML code and save it to the file
string code = "text<div markdown='inline'><code>text</code></div>";
File.WriteAllText(Path.Combine(OutputDir, "inline.html"), code);
// Call ConvertHTML() method to convert HTML to Markdown.
Converter.ConvertHTML(Path.Combine(OutputDir, "inline.html"), new MarkdownSaveOptions(), savePath);
// Output file will contain: text\r\n<div markdown="inline"><code>text</code></div>
// Load a document from a file
string documentPath = Path.Combine(DataDir, "html_file.html");
using (HTMLDocument document = new HTMLDocument(documentPath))
{
// Get the html element of the document
Element element = document.DocumentElement;
Console.WriteLine(element.TagName); // HTML
// Get the last element of the html element
element = element.LastElementChild;
Console.WriteLine(element.TagName); // BODY
// Get the first element in the body element
element = element.FirstElementChild;
Console.WriteLine(element.TagName); // H1
Console.WriteLine(element.TextContent); // Header 1
}
// Create an instance of the Configuration class
using Configuration configuration = new Configuration();
// Call the INetworkService which contains the functionality for managing network operations
INetworkService network = configuration.GetService<INetworkService>();
// Add the TimeoutMessageHandler to the top of existing message handler chain
network.MessageHandlers.Insert(0, new NetworkDisabledMessageHandler());
// Prepare path to a source document file
string documentPath = Path.Combine(DataDir, "document.html");
// Create an HTML document with a custom configuration
using HTMLDocument document = new HTMLDocument(documentPath, configuration);
// Initialize a webAccessibility container
WebAccessibility webAccessibility = new WebAccessibility();
// Create an accessibillity validator with static instance for all rules from repository that match the builder settings
AccessibilityValidator validator = webAccessibility.CreateValidator(ValidationBuilder.All);
string documentPath = Path.Combine(DataDir, "input.html");
// Initialize an object of the HTMLDocument class
using (HTMLDocument document = new HTMLDocument(documentPath))
{
// Check the document
ValidationResult validationResult = validator.Validate(document);
// Take a list of rules results
foreach (RuleValidationResult ruleResult in validationResult.Details)
{
// List only unsuccessful rule
if (!ruleResult.Success)
{
// Print the code and description of the rule
Console.WriteLine("{0}:{1}", ruleResult.Rule.Code, ruleResult.Rule.Description);
// Print the results of all methods
foreach (ITechniqueResult ruleDetail in ruleResult.Results)
{
// Print the code and description of the criterions
StringBuilder str = new StringBuilder(string.Format("\n{0}: {1} - {2}",
ruleDetail.Rule.Code, ruleDetail.Success,
ruleDetail.Rule.Description));
Console.WriteLine(str.ToString());
}
}
}
}
// 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"));
}
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);
}
// 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 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);
}
// 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);
}
// This message handler prints a message about start and finish processing request
public class LogMessageHandler : MessageHandler
{
// Override the Invoke() method
public override void Invoke(INetworkOperationContext context)
{
Debug.WriteLine("Start processing request: " + context.Request.RequestUri);
// Invoke the next message handler in the chain
Next(context);
Debug.WriteLine("Finish processing request: " + context.Request.RequestUri);
}
}
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);
}
}
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}");
}
}
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();
}
}
class MemoryStreamProvider : Aspose.Html.IO.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();
}
}
// Prepare HTML code
string code1 = @"<br><span style='color: green'>Hello, World!!</span>";
string code2 = @"<br><span style='color: blue'>Hello, World!!</span>";
string code3 = @"<br><span style='color: red'>Hello, World!!</span>";
// Create three HTML documents to merge later
using HTMLDocument document1 = new HTMLDocument(code1, ".");
using HTMLDocument document2 = new HTMLDocument(code2, ".");
using HTMLDocument document3 = new HTMLDocument(code3, ".");
// Create an instance of HTML Renderer
using HtmlRenderer renderer = new HtmlRenderer();
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "merge-html.pdf");
// Create an instance of PDF device
using PdfDevice device = new PdfDevice(savePath);
// Merge all HTML documents into PDF
renderer.Render(device, document1, document2, document3);
// Prepare HTML code
string code1 = @"<br><span style='color: green'>Hello, World!!</span>";
string code2 = @"<br><span style='color: blue'>Hello, World!!</span>";
string code3 = @"<br><span style='color: red'>Hello, World!!</span>";
// Create three HTML documents to merge later
using HTMLDocument document1 = new HTMLDocument(code1, ".");
using HTMLDocument document2 = new HTMLDocument(code2, ".");
using HTMLDocument document3 = new HTMLDocument(code3, ".");
// Create an instance of HTML Renderer
using HtmlRenderer renderer = new HtmlRenderer();
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "merge-html-options.pdf");
// Create the instance of Rendering Options and set a custom page-size
PdfRenderingOptions options = new PdfRenderingOptions();
options.PageSetup.AnyPage = new Page(new Size(400, 100));
options.BackgroundColor = System.Drawing.Color.Azure;
// Create an instance of PDF device
using PdfDevice device = new PdfDevice(options, savePath);
// Merge all HTML documents into PDF
renderer.Render(device, document1, document2, document3);
// Initialize an SVG document from the file
using SVGDocument document1 = new SVGDocument(Path.Combine(DataDir, "shapes.svg"));
using SVGDocument document2 = new SVGDocument(Path.Combine(DataDir, "aspose.svg"));
// Create an instance of SVG Renderer
using SvgRenderer renderer = new SvgRenderer();
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "merge-svg.pdf");
// Create the instance of Rendering Options and set a custom page-size
PdfRenderingOptions options = new PdfRenderingOptions();
options.PageSetup.AnyPage = new Page(new Size(600, 500));
// Create an instance of the Pdfdevice class
using PdfDevice device = new PdfDevice(options, savePath);
// Merge all SVG documents into PDF
renderer.Render(device, document1, document2);
// Create an instance of MemoryStreamProvider
using MemoryStreamProvider streamProvider = new MemoryStreamProvider();
// Open an existing MHTML file for reading
using FileStream stream = File.OpenRead(DataDir + "sample.mht");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "stream-provider.docx");
// Convert MHTML to DOCX by using the MemoryStreamProvider class
Converter.ConvertMHTML(stream, new DocSaveOptions(), streamProvider);
// Get access to the memory stream that contains the result data
MemoryStream memory = streamProvider.Streams.First();
memory.Seek(0, SeekOrigin.Begin);
// Flush the result data to the output file
using (FileStream fs = File.Create(savePath))
{
memory.CopyTo(fs);
}
// Open an existing MHTML file for reading
using FileStream stream = File.OpenRead(DataDir + "sample.mht");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "sample-options.docx");
// Create an instance of DocxSaveOptions and set A5 as a page size
DocSaveOptions options = new DocSaveOptions();
options.PageSetup.AnyPage = new Page(new Aspose.Html.Drawing.Size(Length.FromInches(8.3f), Length.FromInches(5.8f)));
// Call the ConvertMHTML() method to convert MHTML to DOCX
Converter.ConvertMHTML(stream, options, savePath);
// Create an instance of MemoryStreamProvider
using MemoryStreamProvider streamProvider = new MemoryStreamProvider();
// Open an existing MHTML file for reading
using FileStream stream = File.OpenRead(DataDir + "sample.mht");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "stream-provider.jpg");
// Convert MHTML to JPG by using the MemoryStreamProvider class
Converter.ConvertMHTML(stream, new ImageSaveOptions(ImageFormat.Jpeg), streamProvider);
// Get access to the memory streams that contain the resulted data
for (int i = 0; i < streamProvider.Streams.Count; i++)
{
MemoryStream memory = streamProvider.Streams[i];
memory.Seek(0, SeekOrigin.Begin);
// Flush the page to the output file
using (FileStream fs = File.Create(savePath))
{
memory.CopyTo(fs);
}
}
// Open an existing MHTML file for reading
using FileStream stream = File.OpenRead(DataDir + "sample.mht");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "sample-options.jpg");
// Initailize the ImageSaveOptions with a custom page-size and a background color
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Jpeg)
{
PageSetup =
{
AnyPage = new Page()
{
Size = new Aspose.Html.Drawing.Size(Length.FromPixels(1000), Length.FromPixels(500))
}
},
BackgroundColor = System.Drawing.Color.Beige
};
// Call the ConvertMHTML() method to convert MHTML to JPG
Converter.ConvertMHTML(stream, options, savePath);
// Create an instance of MemoryStreamProvider
using MemoryStreamProvider streamProvider = new MemoryStreamProvider();
// Open an existing MHTML file for reading
using FileStream stream = File.OpenRead(DataDir + "sample.mht");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "stream-provider.pdf");
// Convert MHTML to PDF by using the MemoryStreamProvider class
Converter.ConvertMHTML(stream, new PdfSaveOptions(), streamProvider);
// Get access to the memory stream that contains the result data
MemoryStream memory = streamProvider.Streams.First();
memory.Seek(0, SeekOrigin.Begin);
// Flush the result data to the output file
using (FileStream fs = File.Create(savePath))
{
memory.CopyTo(fs);
}
// Open an existing MHTML file for reading
using FileStream stream = File.OpenRead(DataDir + "sample.mht");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "sample-options.pdf");
// Create an instance of PdfSaveOptions. Set up the page-size and change the background color to AliceBlue
PdfSaveOptions options = new PdfSaveOptions()
{
PageSetup =
{
AnyPage = new Page()
{
Size = new Aspose.Html.Drawing.Size(Length.FromPixels(3000), Length.FromPixels(1000))
}
},
BackgroundColor = System.Drawing.Color.AliceBlue
};
// Call the ConvertMHTML() method to convert MHTML to PDF
Converter.ConvertMHTML(stream, options, savePath);
// Create an instance of MemoryStreamProvider
using MemoryStreamProvider streamProvider = new MemoryStreamProvider();
// Open an existing MHTML file for reading
using FileStream stream = File.OpenRead(DataDir + "sample.mht");
// Prepare a path for converted file saving
string savePath = Path.Combine(OutputDir, "stream-provider.xps");
// Convert MHTML to XPS by using the MemoryStreamProvider class
Converter.ConvertMHTML(stream, new XpsSaveOptions(), streamProvider);
// Get access to the memory stream that contains the result data
MemoryStream memory = streamProvider.Streams.First();
memory.Seek(0, SeekOrigin.Begin);
// Flush the result data to the output file
using (FileStream fs = File.Create(savePath))
{
memory.CopyTo(fs);
}
// Open an existing MHTML file for reading
using FileStream stream = File.OpenRead(DataDir + "sample.mht");
// Prepare a path for converted file saving
string savePath = Path.Combine(OutputDir, "sample-options.xps");
// Create an instance of XpsSaveOptions. Set up the page-size and change the background color to AliceBlue
XpsSaveOptions options = new XpsSaveOptions();
options.PageSetup.AnyPage = new Page(new Aspose.Html.Drawing.Size(Length.FromInches(8.3f), Length.FromInches(5.8f)));
options.BackgroundColor = System.Drawing.Color.AliceBlue;
// Call the ConvertMHTML() method to convert MHTML to XPS
Converter.ConvertMHTML(stream, options, savePath);
// 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();
}
// Prepare HTML code
string html_code = "<span>Hello,</span> <span>World!</span>";
// Initialize a document from the prepared code
using (HTMLDocument document = new HTMLDocument(html_code, "."))
{
// Get the reference to the first child (first <span>) of the <body>
Node element = document.Body.FirstChild;
Console.WriteLine(element.TextContent); // output: Hello,
// Get the reference to the whitespace between html elements
element = element.NextSibling;
Console.WriteLine(element.TextContent); // output: ' '
// Get the reference to the second <span> element
element = element.NextSibling;
Console.WriteLine(element.TextContent); // output: World!
// Set an html variable for the document
string html = document.DocumentElement.OuterHTML;
Console.WriteLine(html); // output: <html><head></head><body><span>Hello,</span> <span>World!</span></body></html>
}
// Define the NetworkChangeMessageHandler class that is derived from the MessageHandler class
public class NetworkChangeMessageHandler : MessageHandler
{
// Override the Invoke() method
public override void Invoke(INetworkOperationContext context)
{
if (context.Request.RequestUri.Protocol == "file:" || context.Request.RequestUri.Protocol == "base64:")
{
Next(context);
return;
}
context.Request.RequestUri = new Url(context.Request.RequestUri.Pathname, "http://localhost:8080");
}
}
// Define the NetworkDisabledMessageHandler class that is derived from the MessageHandler class
public class NetworkDisabledMessageHandler : MessageHandler
{
// Override the Invoke() method
public override void Invoke(INetworkOperationContext context)
{
if (context.Request.RequestUri.Protocol == "file:" ||
context.Request.RequestUri.Protocol == "base64:" ||
context.Request.RequestUri.Protocol == "about:")
Next(context);
}
}
// 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);
}
}
}
// Create an instance of the Configuration class
using Configuration configuration = new Configuration();
// Call the INetworkService which contains the functionality for managing network operations
INetworkService network = configuration.GetService<INetworkService>();
// Add the TimeoutMessageHandler to the top of existing message handler chain
network.MessageHandlers.Insert(0, new TimeoutMessageHandler());
// Prepare path to a source document file
string documentPath = Path.Combine(DataDir, "document.html");
// Prepare a path for converted file saving
string savePath = Path.Combine(OutputDir, "document.pdf");
// Convert HTML to PDF with customized configuration
Converter.ConvertHTML(documentPath, configuration, new PdfSaveOptions(), savePath);
// Create an instance of the Configuration class
using Configuration configuration = new Configuration();
// Call the INetworkService which contains the functionality for managing network operations
INetworkService network = configuration.GetService<INetworkService>();
// Add the TimeoutMessageHandler to the top of existing message handler chain
network.MessageHandlers.Insert(0, new TimeoutMessageHandler());
// Prepare path to a source document file
string documentPath = Path.Combine(DataDir, "document.html");
// Create an HTML document with a custom configuration
using HTMLDocument document = new HTMLDocument(documentPath, configuration);
// Prepare HTML code
string code = @"
<p>Hello,</p>
<img src='image1.png'>
<img src='image2.png'>
<p>World!</p>";
// Initialize a document based on the prepared code
using (HTMLDocument document = new HTMLDocument(code, "."))
{
// To start HTML navigation, we need to create an instance of TreeWalker
// The specified parameters mean that it starts walking from the root of the document, iterating all nodes and using our custom implementation of the filter
using (ITreeWalker iterator = document.CreateTreeWalker(document, NodeFilter.SHOW_ALL, new OnlyImageFilter()))
{
while (iterator.NextNode() != null)
{
// Since we are using our own filter, the current node will always be an instance of the HTMLImageElement
// So, we don't need the additional validations here
HTMLImageElement image = (HTMLImageElement)iterator.CurrentNode;
Console.WriteLine(image.Src);
// output: image1.png
// output: image2.png
// Set an html variable for the document
string html = document.DocumentElement.OuterHTML;
}
}
}
class OnlyImageFilter : Aspose.Html.Dom.Traversal.Filters.NodeFilter
{
public override short AcceptNode(Node n)
{
// The current filter skips all elements, except IMG elements
return string.Equals("img", n.LocalName)
? FILTER_ACCEPT
: FILTER_SKIP;
}
}
string htmlPath = Path.Combine(DataDir, "input.html");
using (HTMLDocument document = new HTMLDocument(htmlPath))
{
AccessibilityValidator validator = new WebAccessibility().CreateValidator();
ValidationResult validationresult = validator.Validate(document);
using (StringWriter sw = new StringWriter())
{
validationresult.SaveTo(sw, ValidationResultSaveFormat.XML);
string xml = sw.ToString();
Console.WriteLine(xml);
try
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
}
catch (Exception)
{
Console.WriteLine("Wrong xml format");
}
}
}
// 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: 500px'>Second Page</div>";
// Initialize an HTML document from the HTML code
using HTMLDocument document = new HTMLDocument(code, ".");
// Create the instance of Rendering Options and set a custom page-size
PdfRenderingOptions options = new PdfRenderingOptions();
options.PageSetup.AnyPage = new Page(new Size(400, 200));
// Enable auto-adjusting for the page size
options.PageSetup.AdjustToWidestPage = true;
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "output-widest-page-size.pdf");
// Create the PdfDevice and specify options and output file
using PdfDevice device = new PdfDevice(options, savePath);
// Render HTML to PDF
document.RenderTo(device);
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "document.docx");
// 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");
// Create an instance of the DocRenderingOptions class
DocRenderingOptions docOptions = new DocRenderingOptions();
// Create the DocDevice object and specify the output file to render
using DocDevice device = new DocDevice(docOptions, savePath);
// Render HTML to DOCX
document.RenderTo(device);
// Prepare path to a source HTML file
string documentPath = Path.Combine(DataDir, "spring.html");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "spring-output.jpg");
// Initialize an HTML document from the file
using HTMLDocument document = new HTMLDocument(documentPath);
// Create an instance of the ImageRenderingOptions class
ImageRenderingOptions imageOptions = new ImageRenderingOptions(ImageFormat.Jpeg);
// Create the Image Device and specify the output file to render
using ImageDevice device = new ImageDevice(imageOptions, savePath);
// Render HTML to JPG
document.RenderTo(device);
// Prepare HTML code
string code = @"<span>Hello, World!!</span>";
// Prepare a path to save a converted file
string savePath = Path.Combine(OutputDir, "document.pdf");
// Initialize an HTML document from the HTML code
using HTMLDocument document = new HTMLDocument(code, ".");
// Create a PDF Device and specify the output file to render
using PdfDevice device = new PdfDevice(savePath);
// Render HTML to PDF
document.RenderTo(device);
// Prepare path to a source HTML file
string documentPath = Path.Combine(DataDir, "spring.html");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "spring.xps");
// Initialize an HTML document from the file
using HTMLDocument document = new HTMLDocument(documentPath);
// Create an instance of the XpsDevice and specify the output file to render
using XpsDevice device = new XpsDevice(savePath);
// Render HTML to XPS
document.RenderTo(device);
// Initialize an SVG document from the file
using SVGDocument document = new SVGDocument(Path.Combine(DataDir, "shapes.svg"));
// Create an instance of SVG Renderer
using SvgRenderer renderer = new SvgRenderer();
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "rendering-svg.pdf");
// Create the instance of Rendering Options and set a custom page-size
PdfRenderingOptions options = new PdfRenderingOptions();
options.PageSetup.AnyPage = new Page(new Size(600, 500));
// Create an instance of the Pdfdevice class
using PdfDevice device = new PdfDevice(options, savePath);
// Merge all SVG documents into PDF
renderer.Render(device, document);
// Define the RequestDurationLoggingMessageHandler class that is derived from the MessageHandler class
abstract class RequestDurationLoggingMessageHandler : MessageHandler
{
private static ConcurrentDictionary<Url, Stopwatch> requests = new ConcurrentDictionary<Url, Stopwatch>();
protected void StartTimer(Url url)
{
requests.TryAdd(url, Stopwatch.StartNew());
}
protected TimeSpan StopTimer(Url url)
{
Stopwatch timer = requests[url];
timer.Stop();
return timer.Elapsed;
}
}
class StartRequestDurationLoggingMessageHandler : RequestDurationLoggingMessageHandler
{
// Override the Invoke() method
public override void Invoke(INetworkOperationContext context)
{
// Start the stopwatch
StartTimer(context.Request.RequestUri);
// Invoke the next message handler in the chain
Next(context);
}
}
class StopRequestDurationLoggingMessageHandler : RequestDurationLoggingMessageHandler
{
// Override the Invoke() method
public override void Invoke(INetworkOperationContext context)
{
// Stop the stopwatch
TimeSpan duration = StopTimer(context.Request.RequestUri);
// Print the result
Debug.WriteLine($"Elapsed: {duration:g}, resource: {context.Request.RequestUri.Pathname}");
// Invoke the next message handler in the chain
Next(context);
}
}
// 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"));
}
}
// 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"));
}
}
// Create a blank document; it is required to access the network operations functionality
using HTMLDocument document = new HTMLDocument();
// Create a URL with the path to the resource you want to download
Url url = new Url("https://docs.aspose.com/html/net/message-handlers/message-handlers.png");
// Create a file request message
using RequestMessage request = new RequestMessage(url);
// Download file from URL
using ResponseMessage response = document.Context.Network.Send(request);
// Check whether response is successful
if (response.IsSuccess)
{
// Save file to a local file system
File.WriteAllBytes(Path.Combine(OutputDir, url.Pathname.Split('/').Last()), response.Content.ReadAsByteArray());
}
// 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);
}
// 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);
}
// 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();
}
// 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);
}
// Prepare an output path for a document saving
string documentPath = Path.Combine(OutputDir, "save-html-to-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);
}
// 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);
}
// 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);
}
}
// 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));
}
string htmlPath = Path.Combine(DataDir, "input.html");
using (HTMLDocument document = new HTMLDocument(htmlPath))
{
AccessibilityValidator validator = new WebAccessibility().CreateValidator();
ValidationResult validationresult = validator.Validate(document);
// get rules errors in string format
string content = validationresult.SaveToString();
// SaveToString - return only errors and warnings
// if everything is ok, it will return "validationResult:true"
Console.WriteLine(content);
}
// Initialize an HTML document from a URL
using HTMLDocument document = new HTMLDocument("https://docs.aspose.com/html/net/message-handlers/");
// Prepare a path to save the downloaded file
string savePath = Path.Combine(OutputDir, "root/result.html");
// Save the HTML document to the specified file
document.Save(savePath);
// Load an HTML document from a URL
using HTMLDocument document = new HTMLDocument("https://docs.aspose.com/html/net/message-handlers/");
// Create an HTMLSaveOptions object and set the MaxHandlingDepth property
HTMLSaveOptions options = new HTMLSaveOptions
{
ResourceHandlingOptions =
{
MaxHandlingDepth = 1
}
};
// Prepare a path for downloaded file saving
string savePath = Path.Combine(OutputDir, "rootAndAdjacent/result.html");
// Save the HTML document to the specified file
document.Save(savePath, options);
// Initialize an HTML document from a URL
using HTMLDocument document = new HTMLDocument("https://docs.aspose.com/html/net/message-handlers/");
// Create an HTMLSaveOptions object and set MaxHandlingDepth and PageUrlRestriction properties
HTMLSaveOptions options = new HTMLSaveOptions
{
ResourceHandlingOptions =
{
MaxHandlingDepth = 1,
PageUrlRestriction = UrlRestriction.SameHost
}
};
// Prepare a path to save the downloaded file
string savePath = Path.Combine(OutputDir, "rootAndManyAdjacent/result.html");
// Save the HTML document to the specified file
document.Save(savePath, options);
// Initialize an HTML document from a URL
using HTMLDocument document = new HTMLDocument("https://docs.aspose.com/html/net/message-handlers/");
// Create an HTMLSaveOptions object and set the JavaScript property
HTMLSaveOptions options = new HTMLSaveOptions
{
ResourceHandlingOptions =
{
JavaScript = ResourceHandling.Embed
}
};
// Prepare a path to save the downloaded file
string savePath = Path.Combine(OutputDir, "rootAndEmbedJs/result.html");
// Save the HTML document to the specified file
document.Save(savePath, options);
// 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);
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 });
// 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);
}
// 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"));
}
// Prepare HTML code
string code = @"
<script>
var count = 0;
setInterval(function()
{
var element = document.createElement('div');
var message = (++count) + '. ' + 'Hello, World!! I know how to use Renderers!';
var text = document.createTextNode(message);
element.appendChild(text);
document.body.appendChild(element);
}, 1000);
</script>";
// Initialize an HTML document based on prepared HTML code
using HTMLDocument document = new HTMLDocument(code, ".");
// Create an instance of HTML Renderer
using HtmlRenderer renderer = new HtmlRenderer();
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "output-timeout.pdf");
// Create an instance of the PdfDevice class
using PdfDevice device = new PdfDevice(savePath);
// Render HTML to PDF
renderer.Render(device, TimeSpan.FromSeconds(5), document);
string documentPath = Path.Combine(OutputDir, "save-options.html");
string savePath = Path.Combine(OutputDir, "save-options-output.docx");
// Prepare HTML code and save it to a file
string code = "<h1>DocSaveOptions Class</h1>\r\n" +
"<p>Using DocSaveOptions Class, you can programmatically apply a wide range of conversion parameters.</p>\r\n";
File.WriteAllText(documentPath, code);
// Initialize an HTML Document from the html file
using HTMLDocument document = new HTMLDocument(documentPath);
// Initialize DocSaveOptions. Set A5 as a page-size
DocSaveOptions options = new DocSaveOptions();
options.PageSetup.AnyPage = new Page(new Aspose.Html.Drawing.Size(Length.FromInches(8.3f), Length.FromInches(5.8f)));
// Convert HTML to DOCX
Converter.ConvertHTML(document, options, savePath);
string documentPath = Path.Combine(OutputDir, "save-options.html");
string savePath = Path.Combine(OutputDir, "save-options-output.jpg");
// Prepare HTML code and save it to a file
string code = "<h1> Image SaveOptions </h1>\r\n" +
"<p>Using ImageSaveOptions Class, you can programmatically apply a wide range of conversion parameters such as BackgroundColor, Format, Compression, PageSetup, etc.</p>\r\n";
File.WriteAllText(documentPath, code);
// Initialize an HTML Document from the html file
using HTMLDocument document = new HTMLDocument(documentPath);
// Set up the page-size 500x250 pixels, margins and change the background color to AntiqueWhite
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Jpeg)
{
BackgroundColor = System.Drawing.Color.AntiqueWhite
};
options.PageSetup.AnyPage = new Page(new Aspose.Html.Drawing.Size(500, 250), new Margin(40, 40, 20, 20));
// Convert HTML to JPG
Converter.ConvertHTML(document, options, savePath);
// Prepare a path for converted file saving
string savePath = Path.Combine(OutputDir, "options-output.md");
// Prepare HTML code and save it to the file
string code = "<h1>Header 1</h1>" +
"<h2>Header 2</h2>" +
"<p>Hello, World!!</p>" +
"<a href='aspose.com'>aspose</a>";
File.WriteAllText(Path.Combine(OutputDir, "options.html"), code);
// Create an instance of SaveOptions and set up the rule:
// - only <a> and <p> elements will be converted to Markdown
MarkdownSaveOptions options = new MarkdownSaveOptions();
options.Features = MarkdownFeatures.Link | MarkdownFeatures.AutomaticParagraph;
// Call the ConvertHTML() method to convert the HTML to Markdown
Converter.ConvertHTML(Path.Combine(OutputDir, "options.html"), options, savePath);
string documentPath = Path.Combine(OutputDir, "save-options.html");
string savePath = Path.Combine(OutputDir, "save-options-output.pdf");
// Prepare HTML code and save it to a file
string code = "<h1> PdfSaveOptions Class</h1>\r\n" +
"<p>Using PdfSaveOptions Class, you can programmatically apply a wide range of conversion parameters such as BackgroundColor, HorizontalResolution, VerticalResolution, PageSetup, etc.</p>\r\n";
File.WriteAllText(documentPath, code);
// Initialize an HTML Document from the html file
using HTMLDocument document = new HTMLDocument(documentPath);
// Set up the page-size, margins and change the background color to AntiqueWhite
PdfSaveOptions options = new PdfSaveOptions()
{
BackgroundColor = System.Drawing.Color.AntiqueWhite
};
options.PageSetup.AnyPage = new Page(new Aspose.Html.Drawing.Size(Length.FromInches(4.9f), Length.FromInches(3.5f)), new Margin(30, 20, 10, 10));
// Convert HTML to PDF
Converter.ConvertHTML(document, options, savePath);
string documentPath = Path.Combine(OutputDir, "save-options.html");
string savePath = Path.Combine(OutputDir, "save-options-output.xps");
// Prepare HTML code and save it to a file
string code = "<h1> XpsSaveOptions Class</h1>\r\n" +
"<p>Using XpsSaveOptions Class, you can programmatically apply a wide range of conversion parameters such as BackgroundColor, PageSetup, etc.</p>\r\n";
File.WriteAllText(documentPath, code);
// Initialize an HTML Document from the html file
using HTMLDocument document = new HTMLDocument(documentPath);
// Set up the page-size, margins and change the background color to AntiqueWhite
XpsSaveOptions options = new XpsSaveOptions()
{
BackgroundColor = System.Drawing.Color.AntiqueWhite
};
options.PageSetup.AnyPage = new Page(new Aspose.Html.Drawing.Size(Length.FromInches(4.9f), Length.FromInches(3.5f)), new Margin(30, 20, 10, 10));
// Convert HTML to XPS
Converter.ConvertHTML(document, options, savePath);
// Prepare a path to a source SVG file
string documentPath = Path.Combine(DataDir, "flower1.svg");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "flower-options.bmp");
// Initialize an SVG document from the file
using SVGDocument document = new SVGDocument(documentPath);
// Initialize ImageSaveOptions. Set up the SmoothingMode, resolutions, and change the background color to AliceBlue
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Bmp)
{
HorizontalResolution = 200,
VerticalResolution = 200,
BackgroundColor = System.Drawing.Color.AliceBlue,
UseAntialiasing = true,
};
// Convert SVG to BMP
Converter.ConvertSVG(document, options, savePath);
// Prepare a path to a source SVG file
string documentPath = Path.Combine(DataDir, "shapes.svg");
// Prepare a path for converted file saving
string savePath = Path.Combine(OutputDir, "shapes-options.docx");
// Initialize an SVG document from the file
using SVGDocument document = new SVGDocument(documentPath);
// Initialize DocSaveOptions. Set up the page-size and margins
DocSaveOptions options = new DocSaveOptions();
options.PageSetup.AnyPage = new Page(new Aspose.Html.Drawing.Size(500, 500), new Margin(30, 10, 10, 10));
// Convert SVG to DOCX
Converter.ConvertSVG(document, options, savePath);
// Prepare a path to a source SVG file
string documentPath = Path.Combine(DataDir, "gradient.svg");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "gradient-options.gif");
// Initialize an SVG document from the file
using SVGDocument document = new SVGDocument(documentPath);
// Initialize ImageSaveOptions. Set up the SmoothingMode, resolutions, and change the background color to AliceBlue
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Gif)
{
UseAntialiasing = true,
HorizontalResolution = 200,
VerticalResolution = 200,
BackgroundColor = System.Drawing.Color.AliceBlue
};
// Convert SVG to GIF
Converter.ConvertSVG(document, options, savePath);
// Create an instance of MemoryStreamProvider
using MemoryStreamProvider streamProvider = new MemoryStreamProvider();
// Prepare SVG code
string code = "<svg xmlns='http://www.w3.org/2000/svg'>" +
"<circle cx='50' cy='50' r='40' stroke='black' stroke-width='3' fill='red' />" +
"</svg>";
// Convert SVG to JPG using the MemoryStreamProvider
Converter.ConvertSVG(code, ".", new ImageSaveOptions(ImageFormat.Jpeg), streamProvider);
// Get access to the memory stream that contains the result data
MemoryStream memory = streamProvider.Streams.First();
memory.Seek(0, SeekOrigin.Begin);
// Flush the result data to the output file
using (FileStream fs = File.Create(Path.Combine(OutputDir, "stream-provider.jpg")))
{
memory.CopyTo(fs);
}
// Prepare a path to a source SVG file
string documentPath = Path.Combine(DataDir, "flower.svg");
// Prepare a path for converted file saving
string savePath = Path.Combine(OutputDir, "flower-options.jpg");
// Initialize an SVG document from the file
using SVGDocument document = new SVGDocument(documentPath);
// Create an instance of the ImageSaveOptions class. Set up the resolutions, SmoothingMode and change the background color to AliceBlue
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Jpeg)
{
UseAntialiasing = true,
HorizontalResolution = 200,
VerticalResolution = 200,
BackgroundColor = System.Drawing.Color.AliceBlue
};
// Convert SVG to JPG
Converter.ConvertSVG(document, options, savePath);
// Create an instance of MemoryStreamProvider
using MemoryStreamProvider streamProvider = new MemoryStreamProvider();
// Prepare SVG code
string code = "<svg xmlns='http://www.w3.org/2000/svg'>" +
"<circle cx='50' cy='50' r='40' stroke='black' stroke-width='3' fill='red' />" +
"</svg>";
// Convert SVG to PDF using the MemoryStreamProvider
Converter.ConvertSVG(code, ".", new PdfSaveOptions(), streamProvider);
// Get access to the memory stream that contains the result data
MemoryStream memory = streamProvider.Streams.First();
memory.Seek(0, SeekOrigin.Begin);
// Flush the result data to the output file
using (FileStream fs = File.Create(Path.Combine(OutputDir, "stream-provider.pdf")))
{
memory.CopyTo(fs);
}
// Prepare a path to a source SVG file
string documentPath = Path.Combine(DataDir, "aspose.svg");
// Prepare a path for converted file saving
string savePath = Path.Combine(OutputDir, "aspose-options.pdf");
// Initialize an SVG document from the file
using SVGDocument document = new SVGDocument(documentPath);
// Initialize PdfSaveOptions. Set up the page-size, margins, resolutions, JpegQuality, and change the background color to AliceBlue
PdfSaveOptions options = new PdfSaveOptions()
{
HorizontalResolution = 200,
VerticalResolution = 200,
BackgroundColor = System.Drawing.Color.AliceBlue,
JpegQuality = 100
};
options.PageSetup.AnyPage = new Page(new Aspose.Html.Drawing.Size(500, 500), new Margin(30, 10, 10, 10));
// Convert SVG to PDF
Converter.ConvertSVG(document, options, savePath);
// Create an instance of MemoryStreamProvider
using MemoryStreamProvider streamProvider = new MemoryStreamProvider();
// Prepare SVG code
string code = "<svg xmlns='http://www.w3.org/2000/svg'>" +
"<circle cx='50' cy='50' r='40' stroke='black' stroke-width='3' fill='red' />" +
"</svg>";
// Convert SVG to PNG using the MemoryStreamProvider
Converter.ConvertSVG(code, ".", new ImageSaveOptions(), streamProvider);
// Get access to the memory stream that contains the result data
MemoryStream memory = streamProvider.Streams.First();
memory.Seek(0, SeekOrigin.Begin);
// Flush the result data to the output file
using (FileStream fs = File.Create(Path.Combine(OutputDir, "stream-provider.png")))
{
memory.CopyTo(fs);
}
// Prepare a path to a source SVG file
string documentPath = Path.Combine(DataDir, "flower1.svg");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "flower-options.png");
// Initialize an SVG document from the file
using SVGDocument document = new SVGDocument(documentPath);
// Create an instance of the ImageSaveOptions class. Set up the SmoothingMode, resolutions, and change the background color to AliceBlue
ImageSaveOptions options = new ImageSaveOptions()
{
HorizontalResolution = 200,
VerticalResolution = 200,
BackgroundColor = System.Drawing.Color.AliceBlue,
UseAntialiasing = true,
};
// Convert SVG to PNG
Converter.ConvertSVG(document, options, savePath);
// Prepare a path to a source SVG file
string documentPath = Path.Combine(DataDir, "gradient.svg");
// Prepare a path for converted file saving
string savePath = Path.Combine(OutputDir, "gradient-options.tiff");
// Initialize an SVG document from the file
using SVGDocument document = new SVGDocument(documentPath);
// Initialize ImageSaveOptions. Set up the compression, resolutions, and change the background color to AliceBlue
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Tiff)
{
Compression = Compression.None,
HorizontalResolution = 200,
VerticalResolution = 200,
BackgroundColor = System.Drawing.Color.AliceBlue
};
// Convert SVG to TIFF
Converter.ConvertSVG(document, options, savePath);
// Create an instance of MemoryStreamProvider
using MemoryStreamProvider streamProvider = new MemoryStreamProvider();
// Prepare SVG code
string code = "<svg xmlns='http://www.w3.org/2000/svg'>" +
"<circle cx='50' cy='50' r='40' stroke='black' stroke-width='3' fill='red' />" +
"</svg>";
// Convert SVG to XPS using the MemoryStreamProvider
Converter.ConvertSVG(code, ".", new XpsSaveOptions(), streamProvider);
// Get access to the memory stream that contains the result data
MemoryStream memory = streamProvider.Streams.First();
memory.Seek(0, SeekOrigin.Begin);
// Flush the result data to the output file
using (FileStream fs = File.Create(Path.Combine(OutputDir, "stream-provider.xps")))
{
memory.CopyTo(fs);
}
// Prepare a path to a source SVG file
string documentPath = Path.Combine(DataDir, "aspose.svg");
// Prepare a path for converted file saving
string savePath = Path.Combine(OutputDir, "aspose-options.xps");
// Initialize an SVG document from the file
using SVGDocument document = new SVGDocument(documentPath);
// Initialize XpsSaveOptions. Set up the page-size 500x500 pixels, margins, resolutions and change the background color to AliceBlue
XpsSaveOptions options = new XpsSaveOptions()
{
HorizontalResolution = 200,
VerticalResolution = 200,
BackgroundColor = System.Drawing.Color.AliceBlue
};
options.PageSetup.AnyPage = new Page(new Aspose.Html.Drawing.Size(500, 500), new Margin(30, 10, 10, 10));
// Convert SVG to XPS
Converter.ConvertSVG(document, options, savePath);
// Define the TimeLoggerMessageHandler class that is derived from the MessageHandler class
public class TimeLoggerMessageHandler : MessageHandler
{
// Override the Invoke() method
public override void Invoke(INetworkOperationContext context)
{
// Start the stopwatch
Stopwatch stopwatch = Stopwatch.StartNew();
// Invoke the next message handler in the chain
Next(context);
// Stop the stopwatch
stopwatch.Stop();
// Print the result
Debug.WriteLine("Request: " + context.Request.RequestUri);
Debug.WriteLine("Time: " + stopwatch.ElapsedMilliseconds + "ms");
}
}
// Define the TimeoutMessageHandler class that is derived from the MessageHandler class
public class TimeoutMessageHandler : MessageHandler
{
public override void Invoke(INetworkOperationContext context)
{
context.Request.Timeout = TimeSpan.FromSeconds(1);
Next(context);
}
}
// Create a template with a string of HTML code
string htmlCode = "<input type=\"checkbox\" disabled {{attr}} />";
// Create an empty data source that won't set an attribute
string dataSource = "<Data><attr></attr></Data>";
// Convert template to HTML
using (HTMLDocument htmlDocument = Converter.ConvertTemplate(htmlCode, string.Empty,
new TemplateData(new TemplateContentOptions(dataSource, TemplateContent.XML)),
new TemplateLoadOptions()))
{
// Request the input checkbox element that we specified in the template
HTMLInputElement input = (HTMLInputElement)htmlDocument.GetElementsByTagName("input").First();
// Сheck if the checkbox is checked - it should not be there
Console.WriteLine("Checked: " + input.Checked);
Console.WriteLine("Attributes.Length: " + input.Attributes.Length);
Console.WriteLine("Attributes[0].Name: " + input.Attributes[0].Name);
Console.WriteLine("Attributes[1].Name: " + input.Attributes[1].Name);
/*
This example produces the following results:
Checked: False
Attributes.Length: 2
Attributes[0].Name: type
Attributes[1].Name: disabled
*/
// Save the HTML document to a file
htmlDocument.Save(Path.Combine(OutputDir, "out-unchecked.html"));
// Prepare a path to the output file
string outputPath = Path.Combine(OutputDir, "out-unchecked.png");
// Convert HTML to PNG
htmlDocument.RenderTo(new ImageDevice(new ImageRenderingOptions(), outputPath));
}
// Prepare path to a source HTML file
string documentPath = Path.Combine(DataDir, "spring.html");
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "spring.pdf");
// Create an instance of HTML document
using HTMLDocument document = new HTMLDocument(documentPath);
// Initialize options with 'Azure' as a background-color
PdfRenderingOptions options = new PdfRenderingOptions()
{
BackgroundColor = System.Drawing.Color.Azure
};
// Create an instance of PDF device
using PdfDevice device = new PdfDevice(options, savePath);
// Render HTML to PDF
document.RenderTo(device);
// Prepare a path to a source HTML file
string documentPath = Path.Combine(DataDir, "nature.html");
// Initialize the HTML document from the file
using HTMLDocument document = new HTMLDocument(documentPath);
// Create an instance of Rendering Options and set a custom page size
DocRenderingOptions options = new DocRenderingOptions();
options.PageSetup.AnyPage = new Page(new Size(Length.FromInches(8), Length.FromInches(10)));
options.FontEmbeddingRule = (FontEmbeddingRule.Full);
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "nature-options.docx");
// Create an instance of the DocDevice and specify options and output file
using DocDevice device = new DocDevice(options, savePath);
// Render HTML to DOCX
document.RenderTo(device);
// 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);
}
}
// Prepare HTML code and save it to a file
string code = @"
<style>
p
{
background: #a7d3fe;
}
@media(min-resolution: 300dpi)
{
p
{
/* high resolution screen color */
background: orange
}
}
</style>
<p>Hello, World!!</p>";
File.WriteAllText("document.html", code);
// Prepare a path to save output file
string savePath1 = Path.Combine(OutputDir, "output_resolution_50.pdf");
string savePath2 = Path.Combine(OutputDir, "output_resolution_300.pdf");
// Create an instance of HTML document
using (HTMLDocument document = new HTMLDocument("document.html"))
{
// Create options for low-resolution screens
PdfRenderingOptions options1 = new PdfRenderingOptions()
{
HorizontalResolution = 50,
VerticalResolution = 50
};
// Create an instance of PDF device
using PdfDevice device1 = new PdfDevice(options1, savePath1);
// Render HTML to PDF
document.RenderTo(device1);
// Create options for high-resolution screens
PdfRenderingOptions options2 = new PdfRenderingOptions()
{
HorizontalResolution = 300,
VerticalResolution = 300
};
// Create an instance of PDF device
using PdfDevice device2 = new PdfDevice(options2, savePath2);
// Render HTML to PDF
document.RenderTo(device2);
}
// Prepare a path to a source HTML file
string documentPath = Path.Combine(DataDir, "color.html");
// Initialize the HTML document from the file
using HTMLDocument document = new HTMLDocument(documentPath);
// Create an instance of Rendering Options
ImageRenderingOptions options = new ImageRenderingOptions(ImageFormat.Jpeg)
{
// Disable smoothing mode
UseAntialiasing = false,
// Set the image resolution as 75 dpi
VerticalResolution = Resolution.FromDotsPerInch(75),
HorizontalResolution = Resolution.FromDotsPerInch(75),
};
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "color-options.jpg");
// Create an instance of the ImageDevice and specify options and output file
using ImageDevice device = new ImageDevice(options, savePath);
// Render HTML to JPG
document.RenderTo(device);
// Prepare HTML code
string code = @"<style>div { page-break-after: always; }</style>
<div>First Page</div>
<div>Second Page</div>
<div>Third Page</div>
<div>Fourth Page</div>";
// Initialize an HTML document from the HTML code
using HTMLDocument document = new HTMLDocument(code, ".");
// Create the instance of Rendering Options and set a custom page size
PdfRenderingOptions options = new PdfRenderingOptions();
options.PageSetup.SetLeftRightPage(
new Page(new Size(400, 150)),
new Page(new Size(400, 50))
);
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "output-custom-page-size.pdf");
// Create the PDF Device and specify options and output file
using PdfDevice device = new PdfDevice(options, savePath);
// Render HTML to PDF
document.RenderTo(device);
// Prepare a path to a source HTML file
string documentPath = Path.Combine(DataDir, "document.html");
// Initialize the HTML document from the file
using HTMLDocument document = new HTMLDocument(documentPath);
// Create the instance of Rendering Options
PdfRenderingOptions options = new PdfRenderingOptions();
// Set the permissions to the file
options.Encryption = new PdfEncryptionInfo(
"user_pwd",
"owner_pwd",
PdfPermissions.PrintDocument,
PdfEncryptionAlgorithm.RC4_128);
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "output-options.pdf");
// Create an instance of the PdfDevice and specify options and output file
using PdfDevice device = new PdfDevice(options, savePath);
// Render HTML to PDF
document.RenderTo(device);
// 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"));
}
}
// 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"));
}
}
// 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"));
}
}
string code = @"<span>Hello, World!!</span>";
// Initialize an HTML document from HTML code
using HTMLDocument document = new HTMLDocument(code, ".");
// Create an instance of PdfRenderingOptions and set a custom page size
PdfRenderingOptions options = new PdfRenderingOptions()
{
PageSetup =
{
AnyPage = new Page(new Size(Length.FromInches(4),Length.FromInches(2)))
}
};
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "file-with-custom-page-size.pdf");
// Create an instance of the PdfDevice and specify the options and output file to render
using PdfDevice device = new PdfDevice(options, savePath);
// Render HTML to PDF
document.RenderTo(device);
// Prepare a path to a source HTML file
string documentPath = Path.Combine(DataDir, "spring.html");
// Create an instance of HTML document
using HTMLDocument document = new HTMLDocument(documentPath);
// Prepare path to save output file
string savePath1 = Path.Combine(OutputDir, "output_resolution_50.png");
string savePath2 = Path.Combine(OutputDir, "output_resolution_300.png");
// Create options for low-resolution screens
ImageRenderingOptions options1 = new ImageRenderingOptions()
{
HorizontalResolution = 50,
VerticalResolution = 50
};
// Create an instance of Image device
using ImageDevice device1 = new ImageDevice(options1, savePath1);
// Render HTML to PNG
document.RenderTo(device1);
// Create options for high-resolution screens
ImageRenderingOptions options2 = new ImageRenderingOptions()
{
HorizontalResolution = 300,
VerticalResolution = 300
};
// Create an instance of Image device
using ImageDevice device2 = new ImageDevice(options2, savePath2);
// Render HTML to PNG
document.RenderTo(device2);
// 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);
}
}
}
// 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);
}
}
// 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);
}
}
// Prepare a path to a source HTML file
string documentPath = Path.Combine(DataDir, "document.html");
// Initialize the HTML document from the file
using HTMLDocument document = new HTMLDocument(documentPath);
// Create an instance of Rendering Options
XpsRenderingOptions options = new XpsRenderingOptions();
options.PageSetup.AnyPage = new Page(new Size(Length.FromInches(5), Length.FromInches(2)));
// Prepare a path to save the converted file
string savePath = Path.Combine(OutputDir, "document-options.xps");
// Create an instance of the XpsDevice and specify options and output file
using XpsDevice device = new XpsDevice(options, savePath);
// Render HTML to XPS
document.RenderTo(device);
// 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);
// 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);
// 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"));
// 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));
// 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);
}
}
// 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);
// 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);
// 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>
}
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);
}
// Initialize a webAccessibility container
WebAccessibility webAccessibility = new WebAccessibility();
// Get from the rules list Principle "1.Perceivable" by code "1" and get guideline "1.2 Time-based Media"
Guideline guideline = webAccessibility.Rules.GetPrinciple("1").GetGuideline("1.2");
//Create an accessibility validator, pass the found guideline as parameters, and specify the full validation settings
AccessibilityValidator validator = webAccessibility.CreateValidator(guideline, ValidationBuilder.All);
// Initialize an HTMLDocument object
using (HTMLDocument document = new HTMLDocument("https://www.youtube.com/watch?v=Yugq1KyZCI0&t=4s"))
{
// Check the document
ValidationResult validationResult = validator.Validate(document);
// Checking for success
if (!validationResult.Success)
{
// Get all result details
foreach (RuleValidationResult ruleResult in validationResult.Details)
{
// If the result of the rule is unsuccessful
if (!ruleResult.Success)
{
// Get an errors list
foreach (ITechniqueResult result in ruleResult.Errors)
{
// Check the type of the erroneous element
if (result.Error.Target.TargetType == TargetTypes.HTMLElement)
{
HTMLElement rule = (HTMLElement)result.Error.Target.Item;
Console.WriteLine("Error in rule {0} : {1}", result.Rule.Code, result.Error.ErrorMessage);
Console.WriteLine("HTML Element: {0}", rule.OuterHTML);
}
}
}
}
}
}
// Initialize webAccessibility container
WebAccessibility webAccessibility = new WebAccessibility();
// Create an accessibillity validator with static instance for all rules from repository that match the builder settings
AccessibilityValidator validator = webAccessibility.CreateValidator(ValidationBuilder.All);
// Initialize an HTMLDocument object
using (HTMLDocument document = new HTMLDocument("https://products.aspose.com/html/net/generators/video/"))
{
// Check the document
ValidationResult validationResult = validator.Validate(document);
// Checking for success
if (!validationResult.Success)
{
// Get a list of Details
foreach (RuleValidationResult detail in validationResult.Details)
{
Console.WriteLine("{0}:{1} = {2}", detail.Rule.Code, detail.Rule.Description, detail.Success);
}
}
}
// Initialize a webAccessibility container
WebAccessibility webAccessibility = new WebAccessibility();
// Create an accessibillity validator with static instance for all rules from repository that match the builder settings
AccessibilityValidator validator = webAccessibility.CreateValidator(ValidationBuilder.All);
// Prepare a path to a source HTML file
string documentPath = Path.Combine(DataDir, "input.html");
// Initialize an object of the HTMLDocument class
using (HTMLDocument document = new HTMLDocument(documentPath))
{
// Check the document
ValidationResult validationResult = validator.Validate(document);
// Checking for success
if (!validationResult.Success)
{
// Get a list of RuleValidationResult Details
foreach (RuleValidationResult detail in validationResult.Details)
{
Console.WriteLine("{0}:{1} = {2}", detail.Rule.Code, detail.Rule.Description, detail.Success);
}
}
}
// Initialize a webAccessibility container
WebAccessibility webAccessibility = new WebAccessibility();
// Create an accessibility validator
AccessibilityValidator validator = webAccessibility.CreateValidator();
// Prepare a path to a source HTML file
string documentPath = Path.Combine(DataDir, "test-checker.html");
// Initialize an HTMLDocument object
using (HTMLDocument document = new HTMLDocument(documentPath))
{
// Check the document
ValidationResult result = validator.Validate(document);
// Checking for success
if (!result.Success)
{
foreach (RuleValidationResult detail in result.Details)
{
// ... do the analysis here...
Console.WriteLine("{0}:{1} = {2}", detail.Rule.Code, detail.Rule.Description, detail.Success);
}
}
}
// Create an instance of the Configuration class
using Configuration configuration = new Configuration();
// Add the TimeLoggerMessageHandler to the chain of existing message handlers
INetworkService service = configuration.GetService<INetworkService>();
MessageHandlerCollection handlers = service.MessageHandlers;
handlers.Insert(0, new TimeLoggerMessageHandler());
// Prepare path to a source document file
string documentPath = Path.Combine(DataDir, "input.htm");
// Initialize an HTML document with specified configuration
using HTMLDocument document = new HTMLDocument(documentPath, configuration);
// Prepare HTML code
string code = @"
<div class='happy'>
<div>
<span>Hello,</span>
</div>
</div>
<p class='happy'>
<span>World!</span>
</p>
";
// Initialize a document based on the prepared code
using (HTMLDocument document = new HTMLDocument(code, "."))
{
// Here we evaluate the XPath expression where we select all child <span> elements from elements whose 'class' attribute equals to 'happy':
IXPathResult result = document.Evaluate("//*[@class='happy']//span",
document,
null,
XPathResultType.Any,
null);
// Iterate over the resulted nodes
for (Node node; (node = result.IterateNext()) != null;)
{
Console.WriteLine(node.TextContent);
// output: Hello,
// output: World!
}
}
// This message handler prints a message about start and finish processing request
class ZipArchiveMessageHandler : MessageHandler, IDisposable
{
private string filePath;
private Archive archive;
// Initialize an instance of the ZipArchiveMessageHandler class
public ZipArchiveMessageHandler(string path)
{
this.filePath = path;
Filters.Add(new ProtocolMessageFilter("zip"));
}
// Override the Invoke() method
public override void Invoke(INetworkOperationContext context)
{
// Call the GetFile() method that defines the logic in the Invoke() method
byte[] buff = GetFile(context.Request.RequestUri.Pathname.TrimStart('/'));
if (buff != null)
{
// Checking: if a resource is found in the archive, then return it as a Response
context.Response = new ResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(buff)
};
context.Response.Headers.ContentType.MediaType = MimeType.FromFileExtension(context.Request.RequestUri.Pathname);
}
else
{
context.Response = new ResponseMessage(HttpStatusCode.NotFound);
}
// Call the next message handler
Next(context);
}
byte[] GetFile(string path)
{
path = path.Replace(@"\", @"/");
ArchiveEntry result = GetArchive().Entries.FirstOrDefault(x => path == x.Name);
if (result != null)
{
using (Stream fs = result.Open())
using (MemoryStream ms = new MemoryStream())
{
fs.CopyTo(ms);
return ms.ToArray();
}
}
return null;
}
Archive GetArchive()
{
return archive ??= new Archive(filePath);
}
public void Dispose()
{
archive?.Dispose();
}
}
// Define the ZipFileSchemaMessageHandler class that is derived from the CustomSchemaMessageHandler class
class ZipFileSchemaMessageHandler : CustomSchemaMessageHandler
{
private readonly Archive archive;
public ZipFileSchemaMessageHandler(Archive archive) : base("zip-file")
{
this.archive = archive;
}
// Override the Invoke() method
public override void Invoke(INetworkOperationContext context)
{
string pathInsideArchive = context.Request.RequestUri.Pathname.TrimStart('/').Replace("\\", "/");
Stream stream = GetFile(pathInsideArchive);
if (stream != null)
{
// If a resource is found in the archive, then return it as a Response
ResponseMessage response = new ResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(stream);
response.Headers.ContentType.MediaType = MimeType.FromFileExtension(context.Request.RequestUri.Pathname);
context.Response = response;
}
else
{
context.Response = new ResponseMessage(HttpStatusCode.NotFound);
}
// Invoke the next message handler in the chain
Next(context);
}
Stream GetFile(string path)
{
ArchiveEntry result = archive
.Entries
.FirstOrDefault(x => x.Name == path);
return result?.Open();
}
}
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();
}
}
// Add this line before you try to use the 'IBM437' encoding
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
// Prepare path to a source zip file
string documentPath = Path.Combine(DataDir, "test.zip");
// Prepare path for converted file saving
string savePath = Path.Combine(OutputDir, "zip-to-pdf-duration.pdf");
// Create an instance of the Configuration class
using Configuration configuration = new Configuration();
INetworkService service = configuration.GetService<INetworkService>();
MessageHandlerCollection handlers = service.MessageHandlers;
// Custom Schema: ZIP. Add ZipFileSchemaMessageHandler to the end of the pipeline
handlers.Add(new ZipFileSchemaMessageHandler(new Archive(documentPath)));
// Duration Logging. Add the StartRequestDurationLoggingMessageHandler at the first place in the pipeline
handlers.Insert(0, new StartRequestDurationLoggingMessageHandler());
// Add the StopRequestDurationLoggingMessageHandler to the end of the pipeline
handlers.Add(new StopRequestDurationLoggingMessageHandler());
// Initialize an HTML document with specified configuration
using HTMLDocument document = new HTMLDocument("zip-file:///test.html", configuration);
// Create the PDF Device
using PdfDevice device = new PdfDevice(savePath);
// Render ZIP to PDF
document.RenderTo(device);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment