Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save aspose-com-gists/5ba403d14d7519e91e9863b458573bf6 to your computer and use it in GitHub Desktop.
Save aspose-com-gists/5ba403d14d7519e91e9863b458573bf6 to your computer and use it in GitHub Desktop.
This Gist contains examples Aspose.HTML Advanced Programming for Java.

Aspose.HTML for Java – Advanced Programming Examples

This gist repository contains advanced programming examples for Aspose.HTML for Java, a robust Java library for parsing, manipulating, and converting HTML documents into formats such as PDF, DOCX, Markdown, and more. These examples support the scenarios described in the Advanced Programming chapter of the documentation, and are intended for developers working with more complex HTML processing tasks. Unlock powerful HTML manipulation with Aspose.HTML for Java! Learn advanced code snippets for canvas rendering, DOM operations, using CSS extensions, and more.

Key Features

  • HTML5 Canvas Content Editing – Manage 2D drawing context to render dynamic HTML visuals to formats like PDF, DOCX, PNG, etc.
  • Advanced DOM manipulation with Mutation Observer – Learn how to log and monitor changes in the HTML document tree using MutationObserver.
  • Aspose.HTML for Java offers its own CSS prefix -aspose-, which provides advanced functionality for customizing the layout of a printed document, such as adding headers, footers, and page numbers.
  • Using the HTML Form Editor – Advanced capabilities for manipulating form elements – input and submission controls.
  • Memory Stream Output – Render documents directly to memory streams for use in non-file-based workflows.

Examples are ideal for Java developers utilizing Aspose.HTML for advanced HTML manipulation tasks.

Usage Instructions

  1. Install the latest version of Aspose.HTML for Java.
  2. To specify the Aspose repository configuration and define the Aspose.HTML for Java API dependency, refer to the How to Install Aspose.HTML for Java article.
  3. You can download a free trial of Aspose.HTML for Java and use a temporary license for unrestricted access.
  4. Browse the available gists and copy the code samples you need.
  5. Configure paths, settings, and inputs to suit your environment.

Prerequisites

  • Java SE 8 (or higher).
  • Supported operating systems: Windows, macOS, Linux.
  • A Java development environment (IntelliJ IDEA, Eclipse, or similar).
  • Build tool: Maven or Gradle for dependency management.
  • Aspose.HTML for Java library.

Related Resources

Aspose.HTML for Java - Advanced Programming
// Convert HTML5 Canvas with JavaScript text to PDF using Aspose.HTML for Java
// Learn more: https://docs.aspose.com/html/java/edit-html5-canvas/
// 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 = '20px Arial';" +
"context.fillStyle = 'red';" +
"context.fillText('Hello World', 40, 50);" +
"</script>";
try (java.io.FileWriter fileWriter = new java.io.FileWriter("document.html")) {
fileWriter.write(code);
}
// Initialize an HTML document from the HTML file
HTMLDocument document = new HTMLDocument("document.html");
// Convert HTML to PDF
Converter.convertHTML(document, new PdfSaveOptions(), "output.pdf");
// Convert HTML to JPEG in memory using Aspose.HTML for Java and save the result to a file
// Learn more: https://docs.aspose.com/html/java/output-streams/
// Create an instance of MemoryStreamProvider
MemoryOutputStreamProvider streamProvider = new MemoryOutputStreamProvider();
// Initialize an HTMLDocument instance
HTMLDocument document = new HTMLDocument("<span>Hello, World!!</span>", ".");
// Convert HTML to JPG using the MemoryStreamProvider
Converter.convertHTML(document, new ImageSaveOptions(ImageFormat.Jpeg), streamProvider.lStream);
// Get access to the memory stream that contains the result data
java.io.InputStream memory = streamProvider.lStream.get(0);
memory.reset();
// Flush the result data to the output file
Path outputFile = new File("output.jpg").toPath();
Files.copy(memory, outputFile, StandardCopyOption.REPLACE_EXISTING);
// Create HTML5 canvas with gradient text and rectangle, convert to PDF with Java
// Learn more: https://docs.aspose.com/html/java/edit-html5-canvas/
// Create an empty HTML document
HTMLDocument document = new HTMLDocument();
// Create a canvas element
HTMLCanvasElement canvas = (HTMLCanvasElement) document.createElement("canvas");
// with a specified size
canvas.setWidth(300);
canvas.setHeight(150);
// Append the canvas element to the document body
document.getBody().appendChild(canvas);
// Get the canvas rendering context to draw
ICanvasRenderingContext2D context = (ICanvasRenderingContext2D) canvas.getContext("2d");
// Prepare a gradient brush
ICanvasGradient gradient = context.createLinearGradient(0, 0, canvas.getWidth(), 0);
gradient.addColorStop(0, "magenta");
gradient.addColorStop(0.5, "blue");
gradient.addColorStop(1.0, "red");
// Assign the brush to the content
context.setFillStyle(gradient);
context.setStrokeStyle(gradient);
// Write the text
context.fillText("Hello, World!", 10, 90, 500);
// Fill the rectangle
context.fillRect(0, 95, 300, 20);
// Create a PDF output device
PdfDevice device = new PdfDevice("canvas.output.pdf");
// Render HTML5 Canvas to PDF
document.renderTo(device);
// Add custom page margins, header, and footer using CSS @page rules in Aspose.HTML for Java
// Learn more: https://docs.aspose.com/html/java/css-extensions/
// Initialize a configuration object
Configuration configuration = new Configuration();
// Get the User Agent Service
IUserAgentService userAgent = configuration.getService(IUserAgentService.class);
// Set a style of custom margins and create marks on it
userAgent.setUserStyleSheet(
"@page {\n" +
" /* Page margins should be not empty in order to write content inside the margin-boxes */\n" +
" margin-top: 1cm;\n" +
" margin-left: 2cm;\n" +
" margin-right: 2cm;\n" +
" margin-bottom: 2cm;\n" +
" /* Page counter located at the bottom of the page */\n" +
" @bottom-right {\n" +
" -aspose-content: \"Page \" currentPageNumber() \" of \" totalPagesNumber();\n" +
" color: green;\n" +
" }\n" +
" /* Page title located at the top-center box */\n" +
" @top-center {\n" +
" -aspose-content: \"Hello, World Document Title!!!\";\n" +
" vertical-align: bottom;\n" +
" color: blue;\n" +
" }\n" +
"}");
// Initialize an HTML document
HTMLDocument document = new HTMLDocument("<div>Hello, World!!!</div>", ".", configuration);
// Initialize an output device
XpsDevice device = new XpsDevice("output.xps");
// Send the document to the output device
document.renderTo(device);
// Fill out and submit an HTML form programmatically using Aspose.HTML for Java
// Learn more: https://docs.aspose.com/html/java/html-form-editor/
// Initialize an instance of HTML document from "https://httpbin.org/forms/post" url
HTMLDocument document = new HTMLDocument("https://httpbin.org/forms/post");
// Create an instance of FormEditor
FormEditor editor = FormEditor.create(document, 0);
// You can fill in the data using direct access to the input elements, like this:
InputElement custname = editor.addInput("custname");
custname.setValue("John Doe");
document.save("out.html");
// or this:
TextAreaElement comments = editor.getElement(TextAreaElement.class, "comments");
comments.setValue("MORE CHEESE PLEASE!");
// or even by performing a bulk operation, like this one:
java.util.Map<String, String> dictionary = new java.util.HashMap<>();
dictionary.put("custemail", "john.doe@gmail.com");
dictionary.put("custtel", "+1202-555-0290");
// Create an instance of FormSubmitter
FormSubmitter submitter = new 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.getResponseMessage().getHeaders().getContentType().getMediaType().equals("application/json")) {
// Print result data to console
System.out.println(result.getContent().readAsString());
} else {
// Load the result data as an HTML document
Document doc = result.loadDocument();
// Inspect HTML document here
}
}
// Implement a memory-based stream provider for handling InputStreams during document rendering in Aspose.HTML for Java
// Learn more: https://docs.aspose.com/html/java/output-streams/
// For complete examples and data files, please go to https://github.com/aspose-html/Aspose.HTML-for-Java
public class MemoryStreamProvider implements java.io.Closeable {
// List of InputStream objects created during the document rendering
public java.util.List<java.io.InputStream> lStream = new java.util.ArrayList<>();
@Override
public void close() throws java.io.IOException {
for (java.io.InputStream stream : lStream) {
stream.close();
}
}
}
// Monitor DOM tree changes using MutationObserver API in Aspose.HTML for Java
// Learn more: https://docs.aspose.com/html/java/mutationobserver/
// Create an empty HTML document
HTMLDocument document = new HTMLDocument();
// Create an instance of the MutationObserver class
MutationObserver observer = new MutationObserver(new MutationCallback() {
@Override
public void invoke(com.aspose.html.utils.collections.generic.IGenericList<MutationRecord> mutations, MutationObserver mutationObserver) {
for (int i = 0; i < mutations.size(); i++) {
MutationRecord record = mutations.get_Item(i);
for (Node node : record.getAddedNodes().toArray()) {
System.out.println("The '" + node + "' node was added to the document.");
}
}
}
});
// Configure options for the MutationObserver
MutationObserverInit config = new MutationObserverInit();
config.setChildList(true);
config.setSubtree(true);
config.setCharacterData(true);
// Pass to observer the target node to observe with the specified configuration
observer.observe(document.getBody(), 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.getBody().appendChild(p);
// Create a text and append it to the paragraph
Text text = document.createTextNode("Hello, World!");
p.appendChild(text);
System.out.println("Waiting for mutation. Press any key to continue...");
System.in.read();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment