Skip to content

Instantly share code, notes, and snippets.

@aspose-com-gists
Last active May 6, 2025 09:37
Show Gist options
  • Save aspose-com-gists/b2199f957c72708d4d2b0de93bca3098 to your computer and use it in GitHub Desktop.
Save aspose-com-gists/b2199f957c72708d4d2b0de93bca3098 to your computer and use it in GitHub Desktop.
This Gist contains examples for Aspose.HTML for Java.
Aspose.HTML for Java
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("FirstFile.html");
java.io.FileOutputStream fileOutputStream = new java.io.FileOutputStream("FirstFileOut.html");
byte[] bytes = new byte[fileInputStream.available()];
fileInputStream.read(bytes);
fileOutputStream.write(bytes);
String style = "<style>\n" +
".st\n" +
"{\n" +
"color:\n" +
"green;\n" +
"}\n" +
"</style >\n" +
"<div id = id1 > Aspose.Html rendering Text in Black Color</div >\n" +
"<div id = id2 class='' st '' > Aspose.Html rendering Text in Green Color</div >\n" +
"<div id = id3 class='' st '' style = 'color: blue;' > Aspose.Html rendering Text in Blue Color</div >\n" +
"<div id = id3 class='' st '' style = 'color: red;' ><font face = 'Arial' > Aspose.Html rendering Text in Red\n" +
"Color</font ></div >\n";
fileOutputStream.write(style.getBytes(java.nio.charset.StandardCharsets.UTF_8));
String pdf_output;
// Create HtmlRenderer object
HtmlRenderer pdf_renderer = new HtmlRenderer();
// Create HtmlDocument instnace while passing path of already created HTML file
HTMLDocument html_document = new HTMLDocument("FirstFileOut.html");
// Set the page size less than document min-width. The content in the resulting file will be cropped becuase of element with width: 200px
PdfRenderingOptions pdf_options =
new PdfRenderingOptions();
PageSetup pageSetup = new PageSetup();
pageSetup.setAnyPage(new Page(new Size(100, 100)));
pageSetup.setAdjustToWidestPage(false);
pdf_options.setPageSetup(pageSetup);
pdf_output = "not-adjusted-to-widest-page_out.pdf";
PdfDevice device = new PdfDevice(pdf_options, pdf_output);
// Render the output
pdf_renderer.render(device, html_document);
// Set the page size less than document min-width and enable AdjustToWidestPage option. The page size of the resulting file will be changed according to content width
pdf_options = new PdfRenderingOptions();
pageSetup = new PageSetup();
pageSetup.setAnyPage(new Page(new Size(100, 100)));
pageSetup.setAdjustToWidestPage(true);
pdf_options.setPageSetup(pageSetup);
pdf_output = "adjusted-to-widest-page_out.pdf";
device = new PdfDevice(pdf_options, pdf_output);
// Render the output
pdf_renderer.render(device, html_document);
// Set input file name.
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("FirstFile.html");
java.io.FileOutputStream fileOutputStream = new java.io.FileOutputStream("FirstFileOut.html");
byte[] bytes = new byte[fileInputStream.available()];
fileInputStream.read(bytes);
fileOutputStream.write(bytes);
String style = "<style>\n" +
".st\n" +
"{\n" +
"color: green;\n" +
"}\n" +
"</style>\n" +
"<div id=id1>Aspose.Html rendering Text in Black Color</div>\n" +
"<div id=id2 class=''st''>Aspose.Html rendering Text in Green Color</div>\n" +
"<div id=id3 class=''st'' style='color: blue;'>Aspose.Html rendering Text in Blue Color</div>\n" +
"<div id=id3 class=''st'' style='color: red;'>Aspose.Html rendering Text in Red Color</div>\n";
fileOutputStream.write(style.getBytes(java.nio.charset.StandardCharsets.UTF_8));
// Create HtmlRenderer object
HtmlRenderer renderer = new HtmlRenderer();
// Create HtmlDocument instnace while passing path of already created HTML file
HTMLDocument html_document = new HTMLDocument("FirstFileOut.html");
// Set the page size less than document min-width. The content in the resulting file will be cropped becuase of element with width: 200px
XpsRenderingOptions xps_options = new XpsRenderingOptions();
Page page = new Page(new Size(100, 100));
PageSetup pageSetup = new PageSetup();
pageSetup.setAnyPage(page);
pageSetup.setAdjustToWidestPage(false);
xps_options.setPageSetup(pageSetup);
String output = "not-adjusted-to-widest-page_out.1.xps";
XpsDevice device = new XpsDevice(xps_options, output);
// Render the output
renderer.render(device, html_document);
// Set the page size less than document min-width and enable AdjustToWidestPage option
// The page size of the resulting file will be changed according to content width
xps_options = new XpsRenderingOptions();
page = new Page(new Size(100, 100));
pageSetup = new PageSetup();
pageSetup.setAnyPage(page);
pageSetup.setAdjustToWidestPage(true);
xps_options.setPageSetup(pageSetup);
output = "not-adjusted-to-widest-page_out.2.xps";
device = new XpsDevice(xps_options, output);
// Render the output
renderer.render(device, html_document);
// 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.pdf");
// Render HTML5 Canvas to PDF
document.renderTo(device);
// 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 { " +
" /* 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
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);
// 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");
// 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", "[email protected]");
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
}
}
// 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
java.nio.file.Files.copy(memory, new java.io.File("output.jpg").toPath());
// 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();
HTMLDocument document = new HTMLDocument("canvas.html");
// Create an instance of HTML renderer and XPS output device
HtmlRenderer renderer = new HtmlRenderer();
PdfDevice device = new PdfDevice("canvas.output.pdf");
// Render the document to the specified device
renderer.render(device, document);
// Prepare a path to a source HTML file
String documentPath = "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.getRules()
.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.getAll()
);
// Initialize an HTMLDocument object
final HTMLDocument document = new HTMLDocument(documentPath);
ValidationResult validationResult = validator.validate(document);
if (!validationResult.getSuccess()) {
// Get all the result details
for (RuleValidationResult ruleResult : validationResult.getDetails()) {
// If the result of the rule is unsuccessful
if (!ruleResult.getSuccess()) {
// Get an errors list
for (ITechniqueResult result : ruleResult.getErrors()) {
// Check the type of the erroneous element, in this case,
// we have an error in the HTML Element
if (result.getError().getTarget().getTargetType() == TargetTypes.HTMLElement) {
HTMLElement rule = (HTMLElement) result.getError().getTarget().getItem();
System.out.println(String.format("Error in rule %s : %s",
result.getRule().getCode(),
result.getError().getErrorMessage()
));
System.out.println(String.format("HTML Element: %s",
rule.getOuterHTML()
));
}
}
}
}
}
// Prepare a path to a source HTML file
String documentPath = "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.getRules()
.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
List<IRule> rules = new List<>();
rules.add(criterion143);
rules.add(criterion146);
AccessibilityValidator validator = webAccessibility.createValidator(
rules,
ValidationBuilder.getAll()
);
final HTMLDocument document = new HTMLDocument(documentPath);
ValidationResult validationResult = validator.validate(document);
if (!validationResult.getSuccess()) {
System.out.println(validationResult.saveToString());
}
// Prepare a path to a source HTML file
String documentPath = "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.getRules()
.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.getAll()
);
final HTMLDocument document = new HTMLDocument(documentPath);
ValidationResult validationResult = validator.validate(document);
if (!validationResult.getSuccess()) {
// Get all result details
for (RuleValidationResult ruleResult : validationResult.getDetails()) {
// If the result of the rule is unsuccessful
if (!ruleResult.getSuccess()) {
// Get errors list
for (ITechniqueResult result : ruleResult.getErrors()) {
// Check the type of the erroneous element, in this case
// we have an error in the html element rule
if (result.getError().getTarget().getTargetType() == TargetTypes.HTMLElement) {
// Element of file with error
HTMLElement rule = (HTMLElement) result.getError().getTarget().getItem();
System.out.println(String.format("Error in rule %s : %s",
result.getRule().getCode(), result.getError().getErrorMessage()));
System.out.println(String.format("CSS Rule: %s",
rule.getOuterHTML()));
}
}}}}
String htmlPath = "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
List<IRule> rules = webAccessibility.getRules().getRules(rulesCode);
// Create an accessibility validator, pass the found rules as parameters,
// and specify the full validation settings
AccessibilityValidator validator = webAccessibility.createValidator(
rules, ValidationBuilder.getAll());
// Initialize an object of the HTMLDocument
final 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
System.out.println(validationResult.saveToString());
// Source EPUB document
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("input.epub");
// Initialize ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Jpeg);
// Output file path
String outputFile = "EPUBtoImageOutput.jpeg";
// Convert SVG to Image
Converter.convertEPUB(
fileInputStream,
options,
outputFile
);
// Source EPUB document
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("input.epub");
// Initialize pdfSaveOptions
PdfSaveOptions options = new PdfSaveOptions();
options.setJpegQuality(100);
// Output file path
String outputFile = "EPUBtoPDF_Output.pdf";
// Convert EPUB to PDF
Converter.convertEPUB(
fileInputStream,
options,
outputFile
);
// Convert HTML to PDF
Converter.convertHTML("document.html", new PdfSaveOptions(), "output.pdf");
// Open an existing EPUB file for reading
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("input.epub");
// Initialize ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Bmp);
// Call the convertEPUB() method to convert the EPUB file to BMP
Converter.convertEPUB(fileInputStream, options, "output.bmp");
// Open an existing EPUB file for reading
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("input.epub");
// Initialize ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Gif);
// Call the convertEPUB() method to convert the EPUB file to GIF
Converter.convertEPUB(fileInputStream, options, "output.gif");
// Open an existing EPUB file for reading
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("input.epub");
// Create an instance of the ImageSaveOptions class
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Jpeg);
// Call the сonvertEPUB() method to convert EPUB to JPG
Converter.convertEPUB(fileInputStream, options, "input-output.jpg");
// Open an existing EPUB file for reading
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("input.epub");
// Create an instance of the ImageSaveOptions class
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Png);
// Call the сonvertEPUB() method to convert EPUB to PNG
Converter.convertEPUB(fileInputStream, options, "input-output.png");
// Open an existing EPUB file for reading
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("input.epub");
// Initialize ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Tiff);
// Call the convertEPUB() method to convert the EPUB file to TIFF
Converter.convertEPUB(fileInputStream, options, "output.tiff");
// Open an existing EPUB file for reading
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("input.epub");
// Create an instance of MemoryStreamProvider
MemoryOutputStreamProvider streamProvider = new MemoryOutputStreamProvider();
// Convert HTML to JPG using the MemoryStreamProvider
Converter.convertEPUB(fileInputStream, new ImageSaveOptions(ImageFormat.Jpeg), streamProvider);
// Get access to the memory streams that contain the resulted data
for (int i = 0; i < streamProvider.getStreams().size(); i++) {
OutputStream memory = streamProvider.getStreams().get(i);
memory.seek(0, SeekOrigin.Begin);
// Flush the page to the output file
java.io.File fs = new java.io.File("page_{" + (i + 1) + "}.jpg");
FileHelper.save(memory, fs);
}
// Open an existing EPUB file for reading
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("input.epub");
// Initialize ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Jpeg);
options.setSmoothingMode(SmoothingMode.HighQuality);
options.setHorizontalResolution(Resolution.to_Resolution(400));
options.setVerticalResolution(Resolution.to_Resolution(400));
options.setBackgroundColor(Color.getAliceBlue());
options.getPageSetup().setAnyPage(new Page(new Size(800, 500), new Margin(30, 20, 10, 10)));
// Convert EPUB to JPG
Converter.convertEPUB(fileInputStream, options, "input-options.jpg");
// Open an existing EPUB file for reading
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("input.epub");
// Invoke the convertEPUB() method to convert EPUB to JPG
Converter.convertEPUB(fileInputStream, new ImageSaveOptions(ImageFormat.Jpeg), "convert-by-two-lines.jpg");
// Open an existing EPUB file for reading
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("input.epub");
// Create an instance of the PdfSaveOptions class
PdfSaveOptions options = new PdfSaveOptions();
// Call the convertEPUB() method to convert EPUB to PDF
Converter.convertEPUB(fileInputStream, options, "output-epub-to-pdf.pdf");
// Create an instance of MemoryStreamProvider
MemoryOutputStreamProvider streamProvider = new MemoryOutputStreamProvider();
// Open an existing EPUB file for reading
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("input.epub");
// Convert EPUB to PDF by using the MemoryStreamProvider class
Converter.convertEPUB(fileInputStream, new PdfSaveOptions(), streamProvider);
// Get access to the memory stream that contains the result data
OutputStream memory = streamProvider.getStreams().stream().findFirst().get();
memory.seek(0, SeekOrigin.Begin);
// Flush the result data to the output file
java.io.File fs = new java.io.File("stream-provider.pdf");
FileHelper.save(memory, fs);
// Open an existing EPUB file for reading
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("input.epub");
// Create an instance of PdfSaveOptions. Set up the page-size and change the background color to AliceBlue
PdfSaveOptions options = new PdfSaveOptions();
options.setBackgroundColor(Color.getAliceBlue());
options.getPageSetup().setAnyPage(new Page());
options.getPageSetup().getAnyPage().setSize(new Size(Length.fromPixels(1000), Length.fromPixels(1000)));
// Call the convertEPUB() method to convert EPUB to PDF
Converter.convertEPUB(fileInputStream, options, "input-options.pdf");
// Open an existing EPUB file for reading
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("input.epub");
// Invoke the convertEPUB() method to convert EPUB to PDF
Converter.convertEPUB(fileInputStream, new PdfSaveOptions(), "convert-by-two-lines.pdf");
// Open an existing EPUB file for reading
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("input.epub");
// Create an instance of MemoryStreamProvider
MemoryOutputStreamProvider streamProvider = new MemoryOutputStreamProvider();
// Convert HTML to PNG using the MemoryStreamProvider
Converter.convertEPUB(fileInputStream, new ImageSaveOptions(), streamProvider);
// Get access to the memory streams that contain the resulted data
for (int i = 0; i < streamProvider.getStreams().size(); i++) {
OutputStream memory = streamProvider.getStreams().get(i);
memory.seek(0, SeekOrigin.Begin);
// Flush the page to the output file
java.io.File fs = new java.io.File("input-page_{" + (i + 1) + "}.png");
FileHelper.save(memory, fs);
}
// Open an existing EPUB file for reading
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("input.epub");
// Create an instance of the PngSaveOptions with a custom page-size and a background-color.
ImageSaveOptions options = new ImageSaveOptions();
PageSetup pageSetup = new PageSetup();
Page anyPage = new Page();
anyPage.setSize(
new Size(
Length.fromPixels(3000),
Length.fromPixels(1000)
)
);
pageSetup.setAnyPage(anyPage);
options.setPageSetup(pageSetup);
options.setBackgroundColor(Color.getAliceBlue());
// Call the ConvertEPUB method to convert the EPUB to PNG.
Converter.convertEPUB(fileInputStream, options, "output.png");
// Open an existing EPUB file for reading
FileInputStream inputStream = new FileInputStream("input.epub");
// Convert EPUB to PNG
Converter.convertEPUB(inputStream, new ImageSaveOptions(), "convert-with-single-line.png");
// Open an existing EPUB file for reading
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("input.epub");
// Initialize ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions();
options.setBackgroundColor(Color.getAliceBlue());
options.setSmoothingMode(SmoothingMode.HighQuality);
options.setVerticalResolution(Resolution.to_Resolution(400));
options.setHorizontalResolution(Resolution.to_Resolution(400));
// Call the convertEPUB() method to convert EPUB to PNG
Converter.convertEPUB(fileInputStream, options, "input-options.png");
// Open an existing EPUB file for reading
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("input.epub");
// Create an instance of XpsSaveOptions
XpsSaveOptions options = new XpsSaveOptions();
// Call the ConvertEPUB() method to convert EPUB to XPS
Converter.convertEPUB(fileInputStream, options, "input-output.xps");
// Open an existing EPUB file for reading
MemoryOutputStreamProvider streamProvider = new MemoryOutputStreamProvider();
// Open an existing EPUB file for reading
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("input.epub");
// Convert EPUB to XPS by using the MemoryStreamProvider class
Converter.convertEPUB(fileInputStream, new XpsSaveOptions(), streamProvider);
// Get access to the memory stream that contains the result data
OutputStream memory = streamProvider.getStreams().stream().findFirst().get();
memory.seek(0, SeekOrigin.Begin);
// Flush the result data to the output file
java.io.File fs = new java.io.File("stream-provider.xps");
FileHelper.save(memory, fs);
// Open an existing EPUB file for reading
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("input.epub");
// Create an instance of XpsSaveOptions. Set up the page-size and change the background color to LightGray
XpsSaveOptions options = new XpsSaveOptions();
options.setBackgroundColor(Color.getLightGray());
options.getPageSetup().setAnyPage(new Page());
options.getPageSetup().getAnyPage().setSize(new Size(Length.fromPixels(500), Length.fromPixels(500)));
// Call the convertEPUB() method
Converter.convertEPUB(fileInputStream, options, "input-options.xps");
// Open an existing EPUB file for reading
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("input.epub");
// Invoke the ConvertEPUB() method to convert EPUB to XPS
Converter.convertEPUB(fileInputStream, new XpsSaveOptions(), "convert-by-two-lines.xps");
// Initialize an HTML document from a file
HTMLDocument document = new HTMLDocument("canvas.html");
// Initialize DocSaveOptions
DocSaveOptions options = new DocSaveOptions();
// Convert HTML to DOCX
Converter.convertHTML(document, options, "canvas-output.docx");
// Create an instance of MemoryStreamProvider
MemoryOutputStreamProvider streamProvider = new MemoryOutputStreamProvider();
// Initialize an HTML document
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
OutputStream memory = streamProvider.getStreams().stream().findFirst().get();
memory.seek(0, SeekOrigin.Begin);
// Flush the result data to the output file
java.io.File fs = new java.io.File("stream-provider.docx");
FileHelper.save(memory, fs);
// Initialize an HTML document from a file
HTMLDocument document = new HTMLDocument("canvas.html");
// Initialize DocSaveOptions. Set up the pag size 600x400 pixels and margins
DocSaveOptions options = new DocSaveOptions();
options.getPageSetup().setAnyPage(new Page(new Size(600, 400), new Margin(10, 10, 10, 10)));
// Convert HTML to DOCX
Converter.convertHTML(document, options, "canvas-output-options.docx");
// Invoke the convertHTML() method to convert HTML to DOCX
Converter.convertHTML("<h1>Convert HTML to DOCX!</h1>", ".", new DocSaveOptions(), "convert-with-single-line.docx");
// Prepare HTML code and save it to a file
String code = "<span>Hello,</span> <span>World!!</span>";
try (java.io.FileWriter fileWriter = new java.io.FileWriter("bmp.html")) {
fileWriter.write(code);
}
// Initialize an HTML document from the file
HTMLDocument document = new HTMLDocument("bmp.html");
// Initialize ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Bmp);
// Convert HTML to BMP
Converter.convertHTML(document, options, "bmp-output.bmp");
// Prepare HTML code and save it to a file
String code = "<span>Hello,</span> <span>World!!</span>";
try (java.io.FileWriter fileWriter = new java.io.FileWriter("gif.html")) {
fileWriter.write(code);
}
// Initialize an HTML document from the file
HTMLDocument document = new HTMLDocument("gif.html");
// Initialize ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Gif);
// Convert HTML to GIF
Converter.convertHTML(document, options, "gif-output.gif");
// Prepare HTML code and save it to a file
String code = "<span>Hello,</span> <span>World!!</span>";
try (java.io.FileWriter fileWriter = new java.io.FileWriter("jpg.html")) {
fileWriter.write(code);
}
// Initialize an HTML document from the file
HTMLDocument document = new HTMLDocument("jpg.html");
// Create an instance of the ImageSaveOptions class
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Jpeg);
// Convert HTML to JPG
Converter.convertHTML(document, options, "jpg-output.jpg");
// Prepare HTML code and save it to a file
String code = "<span>Hello,</span> <span>World!!</span>";
try (java.io.FileWriter fileWriter = new java.io.FileWriter("png.html")) {
fileWriter.write(code);
}
// Initialize an HTML document from the file
HTMLDocument document = new HTMLDocument("png.html");
// Initialize ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Png);
// Convert HTML to PNG
Converter.convertHTML(document, options, "png-output.png");
// Prepare HTML code and save it to a file
String code = "<span>Hello,</span> <span>World!!</span>";
try (java.io.FileWriter fileWriter = new java.io.FileWriter("tiff.html")) {
fileWriter.write(code);
}
// Initialize an HTML document from the file
HTMLDocument document = new HTMLDocument("tiff.html");
// Initialize ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Tiff);
// Convert HTML to TIFF
Converter.convertHTML(document, options, "tiff-output.bmp");
// Create an instance of MemoryStreamProvider
MemoryOutputStreamProvider streamProvider = new MemoryOutputStreamProvider();
// Initialize an HTML document
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
OutputStream memory = streamProvider.getStreams().stream().findFirst().get();
memory.seek(0, SeekOrigin.Begin);
// Flush the result data to the output file
java.io.File fs = new java.io.File("stream-provider.jpg");
FileHelper.save(memory, fs);
// Prepare HTML code and save it to a file
String code = "<h1> Image SaveOptions </h1> " +
"<p>Using ImageSaveOptions Class, you can programmatically apply a wide range of " +
"conversion parameters such as BackgroundColor, Format, Compression, PageSetup, etc.</p>";
FileHelper.writeAllText("save-options.html", code);
// Initialize an HTML Document from the HTML file
HTMLDocument document = new HTMLDocument("save-options.html");
// Initialize an ImageSaveOptions object and customize save options
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Jpeg);
options.setHorizontalResolution(new Resolution(200, UnitType.AUTO));
options.setVerticalResolution(new Resolution(200, UnitType.AUTO));
options.setBackgroundColor(Color.getAntiqueWhite());
options.getPageSetup().setAnyPage(new Page(new Size(500, 250), new Margin(40, 40, 20, 20)));
// Convert HTML to JPG
Converter.convertHTML(document, options, "save-options-output.jpg");
// Invoke the convertHTML() method to convert HTML code to image
Converter.convertHTML(
"<h1>Convert HTML to JPG!</h1>",
".",
new ImageSaveOptions(ImageFormat.Jpeg),
"convert-with-single-line.jpg"
);
// Prepare HTML code and save it to a file
String code = "<h1>Header 1</h1>" +
"<h2>Header 2</h2>" +
"<p>Hello, World!!</p>";
FileHelper.writeAllText("document.html", code);
// Call convertHTML() method to convert HTML to Markdown
Converter.convertHTML("document.html", MarkdownSaveOptions.getGit(), "output-git.md");
// Prepare HTML code and save it to a file
String code = "text<div markdown='inline'><code>text</code></div>";
FileHelper.writeAllText("inline.html", code);
// Call convertHTML() method to convert HTML to Markdown
Converter.convertHTML("inline.html", new MarkdownSaveOptions(), "inline-html.md");
// Output file will contain: text\r\n<div markdown="inline"><code>text</code></div>
// 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>";
FileHelper.writeAllText("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.setFeatures(MarkdownFeatures.Link | MarkdownFeatures.AutomaticParagraph);
// Call the convertHTML() method to convert HTML to Markdown
Converter.convertHTML("options.html", options, "options-output.md");
// Prepare HTML code and save it to a file
String code = "<h1>Header 1</h1>\n" +
"<h2>Header 2</h2>\n" +
"<p>Hello, World!!</p>\n";
try (java.io.FileWriter fileWriter = new java.io.FileWriter("document.html")) {
fileWriter.write(code);
}
// Call ConvertHTML method to convert HTML to Markdown.
Converter.convertHTML("document.html", new MarkdownSaveOptions(), "output.md");
// Prepare HTML code and save it to a file
String code = "<span>Hello, World!!</span>";
try (java.io.FileWriter fileWriter = new java.io.FileWriter("document.html")) {
fileWriter.write(code);
}
// Initialize an HTML document from the file
HTMLDocument document = new HTMLDocument("document.html");
// Initialize MHTMLSaveOptions
MHTMLSaveOptions options = new MHTMLSaveOptions();
// Convert HTML to MHTML
Converter.convertHTML(document, options, "output.mht");
// 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>";
FileHelper.writeAllText("document.html", code);
// Prepare HTML code and save it to the file as "document2.html"
code = "<span>Hello, World!!</span>";
FileHelper.writeAllText("document2.html", code);
// Change the value of the resource linking depth to 1 in order to convert document with directly linked resources
MHTMLSaveOptions options = new MHTMLSaveOptions();
options.getResourceHandlingOptions().setMaxHandlingDepth(1);
// Convert HTML to MHTML
Converter.convertHTML("document.html", options, "output-options.mht");
// Invoke the convertHTML() method to convert HTML code to MHTML file
Converter.convertHTML("<h1>Hello, Word!</h1>", ".", new MHTMLSaveOptions(), "convert-with-single-line.mht");
// Invoke the ConvertHTML method to convert the HTML to PDF.
Converter.convertHTML("<span>Hello, World!!</span>", ".", new PdfSaveOptions(), "output.pdf");
// Prepare HTML code and save it to a file
String code = "<span>Hello, World!!</span>";
try (java.io.FileWriter fileWriter = new java.io.FileWriter("link-to-incoming-document.html")) {
fileWriter.write(code);
}
// Initialize an HTML document from the file
HTMLDocument document = new HTMLDocument("link-to-incoming-document.html");
// Initialize PdfSaveOptions
PdfSaveOptions options = new PdfSaveOptions();
// Convert HTML to PDF
Converter.convertHTML(document, options, "document-output.pdf");
// Create an instance of MemoryStreamProvider
MemoryOutputStreamProvider streamProvider = new MemoryOutputStreamProvider();
// Initialize an HTML document
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
OutputStream memory = streamProvider.getStreams().stream().findFirst().get();
memory.seek(0, SeekOrigin.Begin);
// Flush the result data to the output file
java.io.File fs = new java.io.File("stream-provider.pdf");
FileHelper.save(memory, fs);
// Initialize an HTML document from a file
HTMLDocument document = new HTMLDocument("drawing.html");
// Initialize PdfSaveOptions. Set up the page-size 500x300 pixels, margins,
// resolutions and change the background color to AliceBlue
PdfSaveOptions options = new PdfSaveOptions();
options.setHorizontalResolution(new Resolution(200, UnitType.AUTO));
options.setVerticalResolution(new Resolution(200, UnitType.AUTO));;
options.setBackgroundColor(Color.getAliceBlue());
options.setJpegQuality(100);
options.getPageSetup().setAnyPage(new Page(new Size(500, 300), new Margin(20, 10, 10, 10)));
// Convert HTML to PDF
Converter.convertHTML(document, options, "drawing-options.pdf");
// Invoke the convertHTML() method to convert the HTML to PDF
Converter.convertHTML("<h1>Convert HTML to PDF!</h1>", ".", new PdfSaveOptions(), "convert-with-single-line.pdf");
// Prepare HTML code and save it to a file
String code = "<h1> PdfSaveOptions Class</h1> " +
"<p>Using PdfSaveOptions Class, you can programmatically " +
"apply a wide range of conversion parameters " +
"such as BackgroundColor, HorizontalResolution, VerticalResolution, PageSetup, etc.</p>";
FileHelper.writeAllText("save-options.html", code);
// Initialize an HTML Document from the HTML file
HTMLDocument document = new HTMLDocument("save-options.html");
// Set up the page-size, margins and change the background color to AntiqueWhite
PdfSaveOptions options = new PdfSaveOptions();
options.setBackgroundColor(Color.getAntiqueWhite());
options.getPageSetup().setAnyPage(
new Page(
new Size(Length.fromInches(4.9f), Length.fromInches(3.5f)),
new Margin(30, 20, 10, 10)
)
);
// Convert HTML to PDF
Converter.convertHTML(document, options, "save-options-output.pdf");
// Prepare a path to an HTML source file
String sourcePath = "SampleHtmlForm.html";
// Initialize an HTML document from the file
HTMLDocument document = new HTMLDocument(sourcePath);
// Prepare PDF save options
PdfSaveOptions options = new PdfSaveOptions();
options.setFormFieldBehaviour(FormFieldBehaviour.Flattened);
// Prepare a path to the result file
String resultPath = "document.pdf";
// Convert HTML to PDF
Converter.convertHTML(document, options, resultPath);
// Initialize an HTML document from a file
HTMLDocument document = new HTMLDocument("nature.html");
// Initialize ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Png);
// Convert HTML to PNG
Converter.convertHTML(document, options, "nature-output.png");
// Prepare HTML code and save it to a file
String code = "<span>Hello, World!!</span>";
try (java.io.FileWriter fileWriter = new java.io.FileWriter("document.html")) {
fileWriter.write(code);
}
// Initialize an HTML document from the file
HTMLDocument document = new HTMLDocument("canvas.html");
// Initialize XpsSaveOptions
XpsSaveOptions options = new XpsSaveOptions();
// Convert HTML to XPS
Converter.convertHTML(document, options, "canvas-output.xps");
// Create an instance of MemoryStreamProvider
MemoryOutputStreamProvider streamProvider = new MemoryOutputStreamProvider();
// Initialize an HTML document
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
OutputStream memory = streamProvider.getStreams().stream().findFirst().get();
memory.seek(0, SeekOrigin.Begin);
// Flush the result data to the output file
java.io.File fs = new java.io.File("stream-provider.xps");
FileHelper.save(memory, fs);
// 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>";
FileHelper.writeAllText("save-options.html", code);
// Initialize an HTML document from the html file
HTMLDocument document = new HTMLDocument("save-options.html");
// Set up the page-size, margins and change the background color to AntiqueWhite
XpsSaveOptions options = new XpsSaveOptions();
options.setBackgroundColor(Color.getAntiqueWhite());
options.getPageSetup().setAnyPage(new Page(new Size(Length.fromInches(4.9f), Length.fromInches(3.5f)), new Margin(30, 20, 10, 10)));
// Convert HTML to XPS
Converter.convertHTML(document, options, "save-options-output.xps");
// Invoke the convertHTML() method to convert HTML to XPS
Converter.convertHTML("<h1>Convert HTML to XPS!</h1>", ".", new XpsSaveOptions(), "convert-with-single-line.xps");
// Convert Markdown to HTML
Converter.convertMarkdown("nature.md", "nature-output.html");
// Convert Markdown to HTML
HTMLDocument document = Converter.convertMarkdown("nature.md");
// Initialize PdfSaveOptions
PdfSaveOptions options = new PdfSaveOptions();
// Convert the HTML document to PDF file format
Converter.convertHTML(document, options, "nature-output.pdf");
// Prepare a simple Markdown example
String code = "### Hello, World! \n" +
"[visit applications](https://products.aspose.app/html/family)";
// Create a Markdown file
FileHelper.writeAllText("document.md", code);
// Convert Markdown to HTML
Converter.convertMarkdown("document.md", "document-output.html");
// Prepare a simple Markdown example
String code = "### Hello, World! \n" +
"[visit applications](https://products.aspose.app/html/family)";
// Create a Markdown file
FileHelper.writeAllText("document.md", code);
// Convert Markdown to HTML
HTMLDocument document = Converter.convertMarkdown("document.md");
// Convert HTML document to JPG image file format
Converter.convertHTML(document, new ImageSaveOptions(ImageFormat.Jpeg), "document-output.jpg");
// Prepare a simple Markdown example
String code = "### Hello, World! \n\n" +
"[visit applications](https://products.aspose.app/html/applications)";
// Create a Markdown file
FileHelper.writeAllText("document.md", code);
// Convert Markdown to HTML
HTMLDocument document = Converter.convertMarkdown("document.md");
// Convert the HTML document to PDF file format
Converter.convertHTML(document, new PdfSaveOptions(), "document-output.pdf");
// Prepare a simple Markdown example
String code = "### Hello, World\n\n" +
"[visit applications](https://products.aspose.app/html/family)";
// Create a Markdown file
try (java.io.FileWriter fileWriter = new java.io.FileWriter("document.md")) {
fileWriter.write(code);
}
// Convert Markdown to HTML document
HTMLDocument document = Converter.convertMarkdown("document.md");
// Convert HTML document to PNG image file format
Converter.convertHTML(document, new ImageSaveOptions(ImageFormat.Png), "output_md.png");
// Prepare a simple Markdown example
String code = "### Hello, World\n\n" +
"[visit applications](https://products.aspose.app/html/family)\n";
// Create a Markdown file
try (java.io.FileWriter fileWriter = new java.io.FileWriter("document.md")) {
fileWriter.write(code);
}
// Convert Markdown to HTML
Converter.convertMarkdown("document.md", "document.html");
// Convert Markdown to HTML
HTMLDocument document = Converter.convertMarkdown("nature.md");
// Initialize ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Jpeg);
options.setSmoothingMode(SmoothingMode.HighQuality);
options.setHorizontalResolution(Resolution.to_Resolution(200));
options.setVerticalResolution(Resolution.to_Resolution(200));
options.setBackgroundColor(Color.getAliceBlue());
options.getPageSetup().setAnyPage(new Page(new Size(600, 950), new Margin(30, 20, 10, 10)));
// Convert HTML to JPG
Converter.convertHTML(document, options, "nature-options.jpg");
// Convert Markdown to HTML
HTMLDocument document = Converter.convertMarkdown("nature.md");
// Initialize PdfSaveOptions. Set up the resolutions, JpegQuality and change the background color to AliceBlue
PdfSaveOptions options = new PdfSaveOptions();
options.setHorizontalResolution(Resolution.to_Resolution(200));
options.setVerticalResolution(Resolution.to_Resolution(200));
options.setBackgroundColor(Color.getAliceBlue());
options.setJpegQuality(100);
// Convert the HTML document to PDF file format
Converter.convertHTML(document, options, "nature-output.pdf");
// Open an existing MHTML file for reading
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("sample.mht");
// Initialize ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Bmp);
// Call the convertMHTML() method to convert the MHTML file to BMP
Converter.convertMHTML(fileInputStream, options, "output.bmp");
// Open an existing MHTML file for reading
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("sample.mht");
// Initialize ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Gif);
// Call the ConvertMHTML method to convert the MHTML file to GIF.
Converter.convertMHTML(fileInputStream, options, "output.gif");
// Open an existing MHTML file for reading
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("sample.mht");
// Create an instance of the ImageSaveOptions class
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Jpeg);
// Call the convertMHTML() method to convert MHTML to JPG
Converter.convertMHTML(fileInputStream, options, "sample-output.jpg");
// Open an existing MHTML file for reading
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("sample.mht");
// Initialize ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Png);
// Call the convertMHTML() method to convert MHTML to PNG
Converter.convertMHTML(fileInputStream, options, "sample-output.png");
// Open an existing MHTML file for reading
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("sample.mht");
// Initialize ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Tiff);
// Call the ConvertMHTML method to convert the MHTML file to TIFF.
Converter.convertMHTML(fileInputStream, options, "output.tiff");
// Open an existing MHTML file for reading
MemoryOutputStreamProvider streamProvider = new MemoryOutputStreamProvider();
// Open an existing MHTML file for reading
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("sample.mht");
// Convert MHTML to JPG by using the MemoryStreamProvider class
Converter.convertMHTML(fileInputStream, new ImageSaveOptions(ImageFormat.Jpeg), streamProvider);
// Get access to the memory streams that contain the resulted data
for (int i = 0; i < streamProvider.getStreams().size(); i++) {
OutputStream memory = streamProvider.getStreams().get(i);
memory.seek(0, SeekOrigin.Begin);
// Flush the page to the output file
java.io.File fs = new java.io.File("stream-provider.jpg");
FileHelper.save(memory, fs);
}
// Open an existing MHTML file for reading
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("sample.mht");
// Initialize the ImageSaveOptions with a custom page-size and background color
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Jpeg);
options.setBackgroundColor(Color.getGreen());
options.getPageSetup().setAnyPage(new Page());
options.getPageSetup().getAnyPage().setSize(new Size(Length.fromPixels(1000), Length.fromPixels(500)));
// Call the convertMHTML() method to convert MHTML to JPG
Converter.convertMHTML(fileInputStream, options, "sample-options.jpg");
// Open an existing MHTML file for reading
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("sample.mht");
// Invoke the convertMHTML() method to convert MHTML to JPG
Converter.convertMHTML(fileInputStream, new ImageSaveOptions(ImageFormat.Jpeg), "convert-by-few-lines.jpg");
// Open an existing MHTML file for reading
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("sample.mht");
// Create an instance of the PdfSaveOptions class
PdfSaveOptions options = new PdfSaveOptions();
// Call the convertMHTML() method to convert MHTML to PDF
Converter.convertMHTML(fileInputStream, options, "sample-output.pdf");
MemoryOutputStreamProvider streamProvider = new MemoryOutputStreamProvider();
// Open an existing MHTML file for reading
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("sample.mht");
// Convert MHTML to PDF by using the MemoryStreamProvider class
Converter.convertMHTML(fileInputStream, new PdfSaveOptions(), streamProvider);
// Get access to the memory stream that contains the result data
OutputStream memory = streamProvider.getStreams().stream().findFirst().get();
memory.seek(0, SeekOrigin.Begin);
// Flush the result data to the output file
java.io.File fs = new java.io.File("stream-provider.pdf");
FileHelper.save(memory, fs);
// Open an existing MHTML file for reading
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("sample.mht");
// Create an instance of PdfSaveOptions. Set up the page-size and change the background color to AliceBlue
PdfSaveOptions options = new PdfSaveOptions();
options.setBackgroundColor(Color.getAliceBlue());
options.getPageSetup().setAnyPage(new Page());
options.getPageSetup().getAnyPage().setSize(new Size(Length.fromPixels(3000), Length.fromPixels(1000)));
// Call the convertMHTML() method to convert MHTML to PDF
Converter.convertMHTML(fileInputStream, options, "sample-options.pdf");
// Open an existing MHTML file for reading
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("sample.mht");
// Invoke the convertMHTML() method to convert MHTML to PDF
Converter.convertMHTML(fileInputStream, new PdfSaveOptions(), "convert-by-two-lines.pdf");
// Prepare a path to an MHTML source file
String sourcePath = "SampleHtmlForm.mhtml";
// Initialize PDF save options
PdfSaveOptions options = new PdfSaveOptions();
options.setFormFieldBehaviour(FormFieldBehaviour.Interactive);
// Prepare a path to the result file
String resultPath = "document-flattened.pdf";
// Convert MHTML to PDF
Converter.convertMHTML(sourcePath, options, resultPath);
// Open an existing MHTML file for reading
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("sample.mht");
// Create an instance of MemoryStreamProvider
MemoryOutputStreamProvider streamProvider = new MemoryOutputStreamProvider();
// Convert HTML to JPG using the MemoryStreamProvider
Converter.convertEPUB(fileInputStream, new ImageSaveOptions(ImageFormat.Png), streamProvider);
// Get access to the memory streams that contain the resulted data
for (int i = 0; i < streamProvider.getStreams().size(); i++) {
OutputStream memory = streamProvider.getStreams().get(i);
memory.seek(0, SeekOrigin.Begin);
// Flush the page to the output file
java.io.File fs = new java.io.File("page_{" + (i + 1) + "}.png");
FileHelper.save(memory, fs);
}
// Open an existing MHTML file for reading
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("sample.mht");
// Initialize the ImageSaveOptions with a custom page-size and background-color
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Png);
PageSetup pageSetup = new PageSetup();
Page anyPage = new Page();
anyPage.setSize(
new Size(
Length.fromPixels(3000),
Length.fromPixels(1000)
)
);
pageSetup.setAnyPage(anyPage);
options.setPageSetup(pageSetup);
options.setBackgroundColor(Color.getGreen());
// Call the convertMHTML() method to convert MHTML to PNG
Converter.convertMHTML(fileInputStream, options, "sample-options.png");
// Open an existing MHTML file for reading
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("sample.mht");
// Create an instance of XpsSaveOptions
XpsSaveOptions options = new XpsSaveOptions();
// Call the convertMHTML() method to convert MHTML to XPS
Converter.convertMHTML(fileInputStream, options, "sample-output.xps");
// Create an instance of the MemoryOutputStreamProvider class
MemoryOutputStreamProvider streamProvider = new MemoryOutputStreamProvider();
// Open an existing MHTML file for reading
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("sample.mht");
// Convert MHTML to XPS by using the MemoryStreamProvider class
Converter.convertMHTML(fileInputStream, new XpsSaveOptions(), streamProvider);
// Get access to the memory stream that contains the result data
OutputStream memory = streamProvider.getStreams().stream().findFirst().get();
memory.seek(0, SeekOrigin.Begin);
// Flush the result data to the output file
java.io.File fs = new java.io.File("stream-provider.xps");
FileHelper.save(memory, fs);
// Open an existing MHTML file for reading
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("sample.mht");
// Create an instance of XpsSaveOptions. Set up a page-size and change the background color to AliceBlue
XpsSaveOptions options = new XpsSaveOptions();
options.getPageSetup().setAnyPage(new Page(new Size(Length.fromInches(8.3f), Length.fromInches(5.8f))));
options.setBackgroundColor(Color.getAliceBlue());
// Call the convertMHTML() method to convert MHTML to XPS
Converter.convertMHTML(fileInputStream, options, "sample-options.xps");
// Open an existing MHTML file for reading
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("sample.mht");
// Сonvert MHTML to PDF
Converter.convertMHTML(fileInputStream, new XpsSaveOptions(), "convert-by-two-lines.xps");
// Prepare SVG code and save it to a file
String code = "<svg xmlns='http://www.w3.org/2000/svg'>\n" +
"<circle cx='50' cy='50' r='40' stroke='black' stroke-width='3' fill='red' />\n" +
"</svg>\n";
try (java.io.FileWriter fileWriter = new java.io.FileWriter("document.svg")) {
fileWriter.write(code);
}
// Initialize an SVG document from the svg file
SVGDocument document = new SVGDocument("document.svg");
// Initialize ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Bmp);
// Convert SVG to BMP
Converter.convertSVG(document, options, "output.bmp");
// Prepare SVG code and save it to a file
String code = "<svg xmlns='http://www.w3.org/2000/svg'>\n" +
"<circle cx='50' cy='50' r='40' stroke='black' stroke-width='3' fill='red' />\n" +
"</svg>\n";
try (java.io.FileWriter fileWriter = new java.io.FileWriter("document.svg")) {
fileWriter.write(code);
}
// Initialize an SVG document from the SVG file
SVGDocument document = new SVGDocument("document.svg");
// Initialize ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Gif);
// Convert SVG to GIF
Converter.convertSVG(document, options, "output.gif");
// Prepare SVG code and save it to a file
String code = "<svg xmlns='http://www.w3.org/2000/svg'>\n" +
"<circle cx='50' cy='50' r='40' stroke='black' stroke-width='3' fill='red' />\n" +
"</svg>\n";
try (java.io.FileWriter fileWriter = new java.io.FileWriter("document.svg")) {
fileWriter.write(code);
}
// Initialize an SVG document from the SVG file
SVGDocument document = new SVGDocument("document.svg");
// Initialize ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Jpeg);
// Convert SVG to JPG
Converter.convertSVG(document, options, "output.jpg");
// Prepare SVG code and save it to a file
String code = "<svg xmlns='http://www.w3.org/2000/svg'>\n" +
"<circle cx='50' cy='50' r='40' stroke='black' stroke-width='3' fill='red' />\n" +
"</svg>\n";
try (java.io.FileWriter fileWriter = new java.io.FileWriter("document.svg")) {
fileWriter.write(code);
}
// Initialize an SVG document from the SVG file
SVGDocument document = new SVGDocument("document.svg");
// Initialize ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Png);
// Convert SVG to PNG
Converter.convertSVG(document, options, "output.png");
// Prepare SVG code and save it to a file
String code = "<svg xmlns='http://www.w3.org/2000/svg'>\n" +
"<circle cx='50' cy='50' r='40' stroke='black' stroke-width='3' fill='red' />\n" +
"</svg>\n";
try (java.io.FileWriter fileWriter = new java.io.FileWriter("document.svg")) {
fileWriter.write(code);
}
// Initialize an SVG document from the svg file
SVGDocument document = new SVGDocument("document.svg");
// Initialize ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Tiff);
// Convert SVG to TIFF
Converter.convertSVG(document, options, "output.tiff");
// Prepare an SVG code and save it to the file
String code = "<svg xmlns='http://www.w3.org/2000/svg'>\n" +
"<circle cx='50' cy='50' r='40' stroke='black' stroke-width='3' fill='red' />\n" +
"</svg>\n";
// Create an instance of MemoryStreamProvider
MemoryOutputStreamProvider streamProvider = new MemoryOutputStreamProvider();
// Initialize the SVG document
SVGDocument document = new SVGDocument(code, ".");
// Convert SVG to Image by using the MemoryStreamProvider
Converter.convertSVG(document, new ImageSaveOptions(ImageFormat.Jpeg), streamProvider.lStream);
// Get access to the memory stream that contains the result data
java.io.InputStream inputStream = streamProvider.lStream.stream().findFirst().get();
// Flush the result data to the output file
try (java.io.FileOutputStream fileOutputStream = new java.io.FileOutputStream("output.jpg")) {
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
fileOutputStream.write(buffer);
}
// Prepare SVG code and save it to a file
String code =
"<svg width=\"450\" height=\"450\" xmlns=\"http://www.w3.org/2000/svg\">" +
" <g fill=\"RoyalBlue\">" +
" <rect x=\"100\" y=\"100\" rx=\"25\" ry=\"25\" width=\"200\" height=\"56\" />" +
" <rect x=\"100\" y=\"100\" rx=\"25\" ry=\"25\" width=\"200\" height=\"56\" transform =\"rotate(90 200 128)\" />" +
" <rect x=\"100\" y=\"100\" rx=\"25\" ry=\"25\" width=\"200\" height=\"56\" transform =\"rotate(-45 200 128)\" />" +
" <rect x=\"100\" y=\"100\" rx=\"25\" ry=\"25\" width=\"200\" height=\"56\" transform =\"rotate(45 200 128)\" />" +
" </g>" +
" <circle cx=\"200\" cy=\"128\" r=\"28\" stroke=\"pink\" stroke-width=\"50\" stroke-dasharray=\"3 13\" fill=\"Orange\" />" +
" <circle cx=\"200\" cy=\"128\" r=\"5\" />" +
"</svg>";
try (java.io.FileWriter fileWriter = new java.io.FileWriter("flower.svg")) {
fileWriter.write(code);
}
// Initialize ImageSaveOptions and set up smoothing mode, page size, and background color
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Jpeg);
PageSetup pageSetup = new PageSetup();
options.setSmoothingMode(SmoothingMode.HighQuality);
Page anyPage = new Page();
anyPage.setSize(new Size(Length.fromPixels(200), Length.fromPixels(200)));
pageSetup.setAnyPage(anyPage);
options.setPageSetup(pageSetup);
options.setBackgroundColor(Color.getAliceBlue());
// Call the convertSVG() method to convert the "flower.svg" file to a JPEG image
Converter.convertSVG("flower.svg", options, "flower.jpg");
// Prepare SVG code
String code = "<svg xmlns='http://www.w3.org/2000/svg'>\n" +
"<circle cx='50' cy='50' r='40' stroke='black' stroke-width='3' fill='red' />\n" +
"</svg>\n";
// Invoke the convertSVG() method to convert SVG to image
Converter.convertSVG(code, ".", new ImageSaveOptions(ImageFormat.Jpeg), "output.jpg");
// Prepare SVG code and save it to a file
String code = "<svg xmlns='http://www.w3.org/2000/svg'>\n" +
"<circle cx='50' cy='50' r='40' stroke='black' stroke-width='3' fill='red' />\n" +
"</svg>\n";
try (java.io.FileWriter fileWriter = new java.io.FileWriter("document.svg")) {
fileWriter.write(code);
}
// Initialize an SVG document from the svg file
SVGDocument document = new SVGDocument("document.svg");
// Initialize PdfSaveOptions
PdfSaveOptions options = new PdfSaveOptions();
// Convert SVG to PDF
Converter.convertSVG(document, options, "output.pdf");
// Create an instance of MemoryStreamProvider
MemoryOutputStreamProvider streamProvider = new MemoryOutputStreamProvider();
// Prepare an SVG code
String code = "<svg xmlns='http://www.w3.org/2000/svg'>\n" +
"<circle cx='50' cy='50' r='40' stroke='black' stroke-width='3' fill='red' />\n" +
"</svg>\n";
// Initialize an SVG document
SVGDocument document = new SVGDocument(code, ".");
// Convert SVG to PDF by using the MemoryStreamProvider
Converter.convertSVG(
document,
new PdfSaveOptions(),
streamProvider.lStream
);
// Get access to the memory stream that contains the result data
java.io.InputStream inputStream = streamProvider.lStream.stream().findFirst().get();
// Flush the result data to the output file
try (java.io.FileOutputStream fileOutputStream = new java.io.FileOutputStream("output.pdf")) {
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
fileOutputStream.write(buffer);
}
// Prepare SVG code and save it to a file
String code = "<svg xmlns='http://www.w3.org/2000/svg'>\n" +
"<circle cx='50' cy='50' r='40' stroke='black' stroke-width='3' fill='red' />\n" +
"</svg>\n";
try (java.io.FileWriter fileWriter = new java.io.FileWriter("document.svg")) {
fileWriter.write(code);
}
// Set A5 as a page-size and change the background color to green
PdfSaveOptions options = new PdfSaveOptions();
PageSetup pageSetup = new PageSetup();
Page anyPage = new Page();
anyPage.setSize(new Size(Length.fromInches(8.3f), Length.fromInches(5.8f)));
pageSetup.setAnyPage(anyPage);
options.setPageSetup(pageSetup);
options.setBackgroundColor(Color.getGreen());
// Convert SVG to PDF
Converter.convertSVG("document.svg", options, "output.pdf");
// Prepare SVG code
String code = "<svg xmlns='http://www.w3.org/2000/svg'>\n" +
"<circle cx='50' cy='50' r='40' stroke='black' stroke-width='3' fill='red' />\n" +
"</svg>\n";
// Call the convertSVG() method to convert SVG to PDF
Converter.convertSVG(code, ".", new PdfSaveOptions(), "output.pdf");
// Create an instance of MemoryStreamProvider
final MemoryOutputStreamProvider streamProvider = new MemoryOutputStreamProvider();
// 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
OutputStream memory = streamProvider.getStreams().stream().findFirst().get();
memory.seek(0, SeekOrigin.Begin);
// Flush the result data to the output file
final java.io.File fs = new java.io.File("stream-provider.png");
FileHelper.save(memory, fs);
// Create an instance of the ImageSaveOptions class. Set up the SmoothingMode, resolutions, and background color
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Png);
options.setHorizontalResolution(Resolution.to_Resolution(200));
options.setVerticalResolution(Resolution.to_Resolution(200));
options.setBackgroundColor(Color.getAliceBlue());
options.setSmoothingMode(SmoothingMode.HighQuality);
// Initialize an SVG document from a file
final SVGDocument document = new SVGDocument("flower1.svg");
// Convert SVG to PNG
Converter.convertSVG(document, options, "flower-options.png");
// Invoke the convertSVG() method for SVG to PNG conversion
Converter.convertSVG("shapes.svg", new ImageSaveOptions(ImageFormat.Png), "convert-with-single-line.png");
// Prepare SVG code and save it to a file
String code =
"<svg xmlns='http://www.w3.org/2000/svg'>\n" +
"<circle cx ='100' cy ='100' r ='60' fill='none' stroke='red' stroke-width='10' />\n"+
"</svg>\n";
try (java.io.FileWriter fileWriter = new java.io.FileWriter("document.svg")) {
fileWriter.write(code);
}
// Initialize an SVG document from the svg file
SVGDocument document = new SVGDocument("document.svg");
// Initialize XpsSaveOptions
XpsSaveOptions options = new XpsSaveOptions();
// Convert SVG to XPS
Converter.convertSVG(document, options, "output.xps");
// Create an instance of MemoryStreamProvider
MemoryOutputStreamProvider streamProvider = new MemoryOutputStreamProvider();
// Prepare an SVG code
String code = "<svg xmlns='http://www.w3.org/2000/svg'>\n" +
"<circle cx='50' cy='50' r='40' stroke='black' stroke-width='3' fill='red' />\n" +
"</svg>\n";
// Initialize an SVG document
SVGDocument document = new SVGDocument(code, ".");
// Convert SVG to XPS by using the MemoryStreamProvider
Converter.convertSVG(
document,
new XpsSaveOptions(),
streamProvider.lStream
);
// Get access to the memory stream that contains the resulted data
java.io.InputStream inputStream = streamProvider.lStream.stream().findFirst().get();
// Flush the result data to the output file
try (java.io.FileOutputStream fileOutputStream = new java.io.FileOutputStream("output.xps")) {
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
fileOutputStream.write(buffer);
}
// Prepare SVG code and save it to a file
String code = "<svg xmlns='http://www.w3.org/2000/svg'>\n" +
"<circle cx='50' cy='50' r='40' stroke='black' stroke-width='3' fill='red' />\n" +
"</svg>\n";
try (java.io.FileWriter fileWriter = new java.io.FileWriter("document.svg")) {
fileWriter.write(code);
}
// Initialize an SVG document from the file
SVGDocument document = new SVGDocument("document.svg");
// Initialize XpsSaveOptions. Set up the page size 500x500 pixels, margins, and resolutions
XpsSaveOptions options = new XpsSaveOptions();
options.setHorizontalResolution(new Resolution(200, UnitType.AUTO));
options.setVerticalResolution(new Resolution(200, UnitType.AUTO));
options.getPageSetup().setAnyPage(new Page(new Size(500, 500), new Margin(30, 10, 10, 10)));
// Convert SVG to XPS
Converter.convertSVG("document.svg", options, "output.xps");
// Prepare SVG code and save it to a file
String code = "<svg xmlns='http://www.w3.org/2000/svg'>\n" +
"<circle cx='50' cy='50' r='40' stroke='black' stroke-width='3' fill='red' />\n" +
"</svg>\n";
try (java.io.FileWriter fileWriter = new java.io.FileWriter("document.svg")) {
fileWriter.write(code);
}
// Set A5 as a page-size and change the background color to green
XpsSaveOptions options = new XpsSaveOptions();
PageSetup pageSetup = new PageSetup();
Page anyPage = new Page();
anyPage.setSize(new Size(Length.fromInches(8.3f), Length.fromInches(5.8f)));
pageSetup.setAnyPage(anyPage);
options.setPageSetup(pageSetup);
options.setBackgroundColor(Color.getGreen());
// Convert SVG document to XPS
Converter.convertSVG("document.svg", options, "output.xps");
// Prepare an SVG code.
String code = "<svg xmlns='http://www.w3.org/2000/svg'>\n" +
"<circle cx='50' cy='50' r='40' stroke='black' stroke-width='3' fill='red' />\n" +
"</svg>\n";
// Invoke the convertSVG() method to convert SVG to image
Converter.convertSVG(code, ".", new XpsSaveOptions(), "output.xps");
// Create an instance of the HTMLDocument class
HTMLDocument document = new HTMLDocument();
// Create a string variable for OuterHTML property reading
StringBuilder outerHTML = new StringBuilder();
// Subscribe to 'ReadyStateChange' event
// This event will be fired during the document loading process
document.OnReadyStateChange.add(new DOMEventHandler() {
@Override
public void invoke(Object sender, Event e) {
// 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.getReadyState().equals("complete")) {
// Fill the outerHTML variable by value of loaded document
outerHTML.append(document.getDocumentElement().getOuterHTML());
}
}
});
Thread.sleep(5000);
System.out.println("outerHTML = " + outerHTML);
// Initialize an empty HTML Document
HTMLDocument document = new HTMLDocument();
// Save the document to disk
document.save("create-empty-document.html");
// Prepare the "load-from-file.html" file
try (java.io.FileWriter fileWriter = new java.io.FileWriter("load-from-file.html")) {
fileWriter.write("Hello, World!");
}
// Load HTML from the file
HTMLDocument document = new HTMLDocument("load-from-file.html");
// Write the document content to the output stream
System.out.println(document.getDocumentElement().getOuterHTML());
// Initialize an HTML document from a file
HTMLDocument document = new HTMLDocument("Sprite.html");
document.save("Sprite_out.html");
// Create a memory stream object
String code = "<p>Hello, World! I love HTML!</p>";
java.io.InputStream inputStream = new java.io.ByteArrayInputStream(code.getBytes());
// Initialize a document from the stream variable
HTMLDocument document = new HTMLDocument(inputStream, ".");
// Save the document to disk
document.save("load-from-stream.html");
// Prepare HTML code
String html_code = "<p>Hello, World!</p>";
// Initialize a document from a string variable
HTMLDocument document = new HTMLDocument(html_code, ".");
// Save the document to disk
document.save("create-from-string.html");
// Load a document from https://docs.aspose.com/html/net/creating-a-document/document.html web page
HTMLDocument document = new HTMLDocument("https://docs.aspose.com/html/net/creating-a-document/document.html");
System.out.println(document.getDocumentElement().getOuterHTML());
// Initialize an empty HTML document
HTMLDocument document = new HTMLDocument();
// Create a text node and add it to the document
Text text = document.createTextNode("Hello, World!");
document.getBody().appendChild(text);
// Save the document to disk
document.save("create-new-document.html");
// Initialize an HTML document
HTMLDocument document = new HTMLDocument();
AtomicBoolean isLoading = new AtomicBoolean(false);
// Subscribe to the 'OnLoad' event
// This event will be fired once the document is fully loaded
document.OnLoad.add(new DOMEventHandler() {
@Override
public void invoke(Object o, Event event) {
isLoading.set(true);
}
});
// Navigate asynchronously at the specified Uri
document.navigate("https://docs.aspose.com/html/net/creating-a-document/document.html");
// Here the document is not loaded yet
// Wait 5 seconds for the file to load
Thread.sleep(5000);
// Here is the loaded document
System.out.println("outerHTML = " + document.getDocumentElement().getOuterHTML());
// Initialize an SVG document from a string object
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
System.out.println(document.getDocumentElement().getOuterHTML());
// Create an instance of the HTMLDocument class
HTMLDocument document = new HTMLDocument();
// Subscribe to the 'ReadyStateChange' event. This event will be fired during the document loading process
document.OnReadyStateChange.add(new DOMEventHandler() {
@Override
public void invoke(Object sender, Event e) {
// Check the value of '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.getReadyState().equals("complete")) {
System.out.println(document.getDocumentElement().getOuterHTML());
notifyAll();
}
}
});
// Navigate asynchronously at the specified Uri
document.navigate("https://html.spec.whatwg.org/multipage/introduction.html");
synchronized (this) {
wait(10000);
}
// 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);
// Prepare HTML code
String code =
"<div class='happy'>\n" +
" <div>\n" +
" <span>Hello,</span>\n" +
" </div>\n" +
"</div>\n" +
"<p class='happy'>\n" +
" <span>World!</span>\n" +
"</p>\n";
// Initialize a document based on the prepared code
final 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
for (Node element : elements) {
System.out.println(((HTMLElement) element).getInnerHTML());
// @output: Hello,
// @output: World!
}
// Create an empty HTML document
HTMLDocument document = new HTMLDocument();
// Create a mutation observer instance
MutationObserver observer = new MutationObserver(
new MutationCallback() {
@Override
public void invoke(
IGenericList<MutationRecord> mutations,
MutationObserver mutationObserver
) {
mutations.forEach(mutationRecord -> {
mutationRecord.getAddedNodes().forEach(node -> {
synchronized (this) {
System.out.println("The '" + node + "' node was added to the document.");
notifyAll();
}
});
});
}
});
// configuration of the observer
MutationObserverInit config = new MutationObserverInit();
config.setChildList(true);
config.setSubtree(true);
config.setCharacterData(true);
// pass in 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 an 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);
// Since, mutations are working in the async mode you should wait a bit.
// We use synchronized(object) and wait(milliseconds) for this purpose as example.
synchronized (this) {
wait(5000);
}
// Later, you can stop observing
observer.disconnect();
// Create an instance of an HTML document
HTMLDocument document = new HTMLDocument();
HTMLElement body = document.getBody();
// 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");
// Add the text to the paragraph
p.appendChild(text);
// Attach paragraph to the document body
body.appendChild(p);
// Save the HTML document to a file
document.save("edit-document-tree.html");
// Create an instance of the HTMLDocument class
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.setTextContent(".gr { color: green }");
// Find the document header element and append the style element to the header
Element head = document.getElementsByTagName("head").get_Item(0);
head.appendChild(style);
// Create a paragraph element with class-name "gr"
HTMLParagraphElement p = (HTMLParagraphElement) document.createElement("p");
p.setClassName("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.getBody().appendChild(p);
// Save the HTML document to a file
document.save("using-dom.html");
// Create an instance of the PDF output device and render the document into this device
PdfDevice device = new PdfDevice("using-dom.html");
// Render HTML to PDF
document.renderTo(device);
String content = "<div><p>Internal CSS</p><p>An internal CSS is used to define a style for a single HTML page</p></div>";
HTMLDocument document = new HTMLDocument(content, ".");
Element style = document.createElement("style");
style.setTextContent(".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").get_Item(0);
head.appendChild(style);
// Find the first paragraph element to inspect the styles
HTMLElement paragraph = (HTMLElement) document.getElementsByTagName("p").get_Item(0);
paragraph.setClassName("frame1");
// Find the last paragraph element to inspect the styles
HTMLElement lastParagraph = (HTMLElement) document.getElementsByTagName("p").get_Item(document.getElementsByTagName("p").getLength() - 1);
lastParagraph.setClassName("frame2");
// Set a font-size to the first paragraph
paragraph.getStyle().setFontSize("250%");
paragraph.getStyle().setTextAlign("center");
// Set a color and font-size to the last paragraph
lastParagraph.getStyle().setColor("#434343");
lastParagraph.getStyle().setFontSize("150%");
lastParagraph.getStyle().setFontFamily("verdana");
// Save the HTML document to a file
document.save("edit-internal-css.html");
// Create the instance of the PDF output device and render the document into this device
PdfDevice device = new PdfDevice("edit-internal-css.html");
document.renderTo(device);
// Prepare content for 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
java.nio.file.Files.write(java.nio.file.Paths.get("flower.css"), styleContent.getBytes());
// 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";
HTMLDocument document = new HTMLDocument(htmlContent, ".");
// Save the HTML document to a file
document.save("edit-external-css.html");
// Create an instance of an HTML document with specified content
String content = "<p> Inline CSS </p>";
HTMLDocument document = new HTMLDocument(content, ".");
// Find the paragraph element to set a style attribute
HTMLElement paragraph = (HTMLElement) document.getElementsByTagName("p").get_Item(0);
// Set the style attribute
paragraph.setAttribute("style", "font-size: 250%; font-family: verdana; color: #cd66aa");
// Save the HTML document to a file
document.save("edit-inline-css.html");
// Create an instance of the PDF output device and render the document into this device
PdfDevice device = new PdfDevice("edit-inline-css.html");
document.renderTo(device);
// Create an instance of the HTMLDocument class
HTMLDocument document = new HTMLDocument();
// Write the content of the HTML document into the console output
System.out.println(document.getDocumentElement().getOuterHTML());
// @output: <html><head></head><body></body></html>
// Set the content of the <body> element
document.getBody().setInnerHTML("<p>HTML is the standard markup language for Web pages.</p>");
// Write the content of the HTML document into the console output
System.out.println(document.getDocumentElement().getOuterHTML());
// @output: <html><head></head><body><p>HTML is the standard markup language for Web pages.</p></body></html>
// 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>";
HTMLDocument document = new HTMLDocument(content, ".");
// Create a style element with text content
Element style = document.createElement("style");
style.setTextContent(".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").get_Item(0);
head.appendChild(style);
// Find the first paragraph element to inspect the styles
HTMLElement paragraph = (HTMLElement) document.getElementsByTagName("p").get_Item(0);
paragraph.setClassName("frame1");
// Find the last paragraph element to inspect the styles
HTMLElement lastParagraph = (HTMLElement) document.getElementsByTagName("p").get_Item(document.getElementsByTagName("p").getLength() - 1);
lastParagraph.setClassName("frame2");
// Set a font-size to the first paragraph
paragraph.getStyle().setFontSize("250%");
paragraph.getStyle().setTextAlign("center");
// Set a color and font-size to the last paragraph
lastParagraph.getStyle().setColor("#434343");
lastParagraph.getStyle().setFontSize("150%");
lastParagraph.getStyle().setFontFamily("verdana");
// Save the HTML document to a file
document.save("edit-internal-css.html");
// Create an instance of the PDF output device and render the document on that device
PdfDevice device = new PdfDevice("edit-internal-css.html");
// 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";
try (java.io.FileWriter fileWriter = new java.io.FileWriter("user-agent-charset.html")) {
fileWriter.write(code);
}
// Create an instance of the Configuration class
Configuration configuration = new Configuration();
// Get the IUserAgentService
IUserAgentService userAgent = configuration.getService(IUserAgentService.class);
// Set ISO-8859-1 encoding to parse the document
userAgent.setCharSet("ISO-8859-1");
// Initialize an HTML document with specified configuration
HTMLDocument document = new HTMLDocument("user-agent-charset.html", configuration);
// Convert HTML to PDF
Converter.convertHTML(document, new PdfSaveOptions(), "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";
try (java.io.FileWriter fileWriter = new java.io.FileWriter("user-agent-fontsetting.html")) {
fileWriter.write(code);
}
// Initialize an instance of the Configuration class
Configuration configuration = new Configuration();
// Get the IUserAgentService
IUserAgentService userAgent = configuration.getService(IUserAgentService.class);
// Set a custom font folder path
userAgent.getFontsSettings().setFontsLookupFolder("fonts");
// Initialize an HTML document with specified configuration
HTMLDocument document = new HTMLDocument("user-agent-fontsetting.html", configuration);
// Convert HTML to PDF
Converter.convertHTML(document, new PdfSaveOptions(), "user-agent-fontsetting_out.pdf");
// Create a MessageHandler. This message handler logs all failed requests to the console
MessageHandler handler = new MessageHandler() {
@Override
public void invoke(INetworkOperationContext context) {
if (context.getResponse().getStatusCode() != HttpURLConnection.HTTP_OK) {
System.out.println(String.format("File '%s' Not Found", context.getRequest().getRequestUri().toString()));
}
// Invoke the next message handler in the chain
next(context);
}
};
// Prepare HTML code with missing image file
String code = "<img src='missing.jpg'>";
try (java.io.FileWriter fileWriter = new java.io.FileWriter("document.html")) {
fileWriter.write(code);
}
// Create an instance of the Configuration class
Configuration configuration = new Configuration();
// Add ErrorMessageHandler to the chain of existing message handlers
INetworkService network = configuration.getService(INetworkService.class);
LogMessageHandler logHandler = new LogMessageHandler();
network.getMessageHandlers().addItem(logHandler);
// Initialize an HTML document with specified configuration
// During the document loading, the application will try to load the image and we will see the result of this operation in the console
HTMLDocument document = new HTMLDocument("document.html", configuration);
// Convert HTML to PNG
Converter.convertHTML(document, new ImageSaveOptions(), "output.png");
// Prepare 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";
try (java.io.FileWriter fileWriter = new java.io.FileWriter("runtime-service.html")) {
fileWriter.write(code);
}
// Create an instance of the Configuration class
Configuration configuration = new Configuration();
// Limit JS execution time to 5 seconds
IRuntimeService runtimeService = configuration.getService(IRuntimeService.class);
runtimeService.setJavaScriptTimeout(TimeSpan.fromSeconds(5));
// Initialize an HTML document with specified configuration
HTMLDocument document = new HTMLDocument("runtime-service.html", configuration);
// Convert HTML to PNG
Converter.convertHTML(document, new ImageSaveOptions(), "runtime-service_out.png");
// Prepare HTML code and save it to a file
String code = "<span>Hello, World!!</span>\n" +
"<script>document.write('Have a nice day!');</script>\n";
try (java.io.FileWriter fileWriter = new java.io.FileWriter("sandboxing.html")) {
fileWriter.write(code);
}
// Create an instance of the Configuration class
Configuration configuration = new Configuration();
// Mark 'scripts' as an untrusted resource
configuration.setSecurity(com.aspose.html.Sandbox.Scripts);
// Initialize an HTML document with specified configuration
HTMLDocument document = new HTMLDocument("sandboxing.html", configuration);
// Convert HTML to PDF
Converter.convertHTML(document, new PdfSaveOptions(), "sandboxing_out.pdf");
// Prepare HTML code and save it to a file
String code = "<span>Hello, World!!!</span>";
try (java.io.FileWriter fileWriter = new java.io.FileWriter("user-agent-stylesheet.html")) {
fileWriter.write(code);
}
// Create an instance of the Configuration class
Configuration configuration = new Configuration();
// Get the IUserAgentService
IUserAgentService userAgent = configuration.getService(IUserAgentService.class);
// Set a custom color to the <span> element
userAgent.setUserStyleSheet("span { color: green; }");
// Initialize an HTML document with specified configuration
HTMLDocument document = new HTMLDocument("user-agent-stylesheet.html", configuration);
// Convert HTML to PDF
Converter.convertHTML(document, new PdfSaveOptions(), "user-agent-stylesheet_out.pdf");
// Source EPUB document
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("input.epub");
// Initialize XpsSaveOptions
XpsSaveOptions options = new XpsSaveOptions();
options.setBackgroundColor(Color.getCyan());
// Output file path
String outputFile = "EPUBtoXPS_Output.xps";
// Convert EPUB to XPS
Converter.convertEPUB(fileInputStream, options, outputFile);
// Initialize a webAccessibility container
WebAccessibility webAccessibility = new WebAccessibility();
// Create an accessibility validator with static instance
// for all rules from repository that match the builder settings
AccessibilityValidator validator = webAccessibility.createValidator(ValidationBuilder.getAll());
String documentPath = "input.html";
// Initialize an object of the HTMLDocument class
final HTMLDocument document = new HTMLDocument(documentPath);
ValidationResult validationResult = validator.validate(document);
for (RuleValidationResult ruleResult : validationResult.getDetails()) {
// list only unsuccessful rule
if (!ruleResult.getSuccess()) {
// print the code and description of the rule
System.out.println(String.format("%s: %s = %s",
ruleResult.getRule().getCode(),
ruleResult.getRule().getDescription(),
ruleResult.getSuccess()
));
// print the results of methods with errors
for (ITechniqueResult ruleDetail : ruleResult.getErrors()) {
// print the code and description of the method
StringBuilder str = new StringBuilder(String.format("\n{0}: {1} - {2}",
ruleDetail.getRule().getCode(),
ruleDetail.getSuccess(),
ruleDetail.getRule().getDescription()
));
// get an error object
IError error = ruleDetail.getError();
// get a target object
Target target = error.getTarget();
// get error type and message
str.append(String.format("\n\n\t%s : %s",
error.getErrorTypeName(),
error.getErrorMessage()
));
if (target != null) {
// Checking the type of the contained object for casting and working with it
if (target.getTargetType() == TargetTypes.CSSStyleRule) {
ICSSStyleRule cssRule = (ICSSStyleRule) target.getItem();
str.append(String.format("\n\n\t%s",
cssRule.getCSSText()
));
}
if (ruleDetail.getError().getTarget().getTargetType() == TargetTypes.CSSStyleSheet) {
str.append(String.format("\n\n\t%s",
((ICSSStyleSheet) target.getItem()).getTitle()
));
}
if (ruleDetail.getError().getTarget().getTargetType() == TargetTypes.HTMLElement) {
str.append(String.format("\n\n\t%s",
((HTMLElement) target.getItem()).getOuterHTML()
));
}
}
System.out.println(str);
}
}
}
// Open a document you want to download external SVGs from
final 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
java.util.Set<String> urls = new HashSet<>();
for (Element element : images) {
urls.add(element.getAttribute("src"));
}
// Filter out non SVG images
java.util.List<String> svgUrls = new ArrayList<>();
for (String url : urls) {
if (url.endsWith(".svg")) {
svgUrls.add(url);
}
}
// Create absolute SVG image URLs
java.util.List<Url> absUrls = svgUrls.stream()
.map(src -> new Url(src, document.getBaseURI()))
.collect(Collectors.toList());
// foreach to while statements conversion
for (Url url : absUrls) {
// Create a downloading request
final RequestMessage request = new RequestMessage(url);
// Download SVG image
final ResponseMessage response = document.getContext().getNetwork().send(request);
// Check whether response is successful
if (response.isSuccess()) {
String[] split = url.getPathname().split("/");
String path = split[split.length - 1];
// Save file to a local file system
FileHelper.writeAllBytes(path, response.getContent().readAsByteArray());
}
}
// Open a document you want to download icons from
final 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
java.util.Set<Element> icons = new HashSet<>();
for (Element link : links) {
if ("icon".equals(link.getAttribute("rel"))) {
icons.add(link);
}
}
// Create a distinct collection of relative icon URLs
java.util.Set<String> urls = new HashSet<>();
for (Element icon : icons) {
urls.add(icon.getAttribute("href"));
}
// Create absolute image URLs
java.util.List<Url> absUrls = urls.stream()
.map(src -> new Url(src, document.getBaseURI()))
.collect(Collectors.toList());
// foreach to while statements conversion
for (Url url : absUrls) {
// Create a downloading request
final RequestMessage request = new RequestMessage(url);
// Extract icon
final ResponseMessage response = document.getContext().getNetwork().send(request);
// Check whether a response is successful
if (response.isSuccess()) {
String[] split = url.getPathname().split("/");
String path = split[split.length - 1];
// Save file to a local file system
FileHelper.writeAllBytes(path, response.getContent().readAsByteArray());
}
}
// Open a document you want to download images from
final 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
Iterator<Element> iterator = images.iterator();
java.util.Set<String> urls = new HashSet<>();
for (Element e : images) {
urls.add(e.getAttribute("src"));
}
// Create absolute image URLs
java.util.List<Url> absUrls = urls.stream()
.map(src -> new Url(src, document.getBaseURI()))
.collect(Collectors.toList());
// foreach to while statements conversion
for (Url url : absUrls) {
// Create an image request message
final RequestMessage request = new RequestMessage(url);
// Extract image
final ResponseMessage response = document.getContext().getNetwork().send(request);
// Check whether a response is successful
if (response.isSuccess()) {
String[] split = url.getPathname().split("/");
String path = split[split.length - 1];
// Save file to a local file system
FileHelper.writeAllBytes(path, response.getContent().readAsByteArray());
}
}
// Open a document you want to download inline SVG images from
final 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.getLength(); i++) {
// Save every image to a local file system
FileHelper.writeAllText("{i}.svg", images.get_Item(i).getOuterHTML());
}
// Prepare HTML code
String code = " <style>\n" +
" div {\n" +
" page - break -after:always;\n" +
" }\n" +
" </style >\n" +
" <div style = 'border: 1px solid red; width: 400px' > First Page</div >\n" +
" <div style = 'border: 1px solid red; width: 600px' > Second Page</div >\n";
// Initialize an HTML document from HTML code
HTMLDocument document = new HTMLDocument(code, ".");
// Create an instance of the PdfRenderingOptions class and set a custom page-size
PdfRenderingOptions options = new PdfRenderingOptions();
options.getPageSetup().setAnyPage(new Page(new Size(500, 200)));
// Enable auto-adjusting for the page size
options.getPageSetup().setAdjustToWidestPage(true);
// Create an instance of the PdfDevice class and specify options and output file
PdfDevice device = new PdfDevice(options, "output.pdf");
// Render HTML to PDF
document.renderTo(device);
// 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
HTMLDocument document1 = new HTMLDocument(code1, ".");
HTMLDocument document2 = new HTMLDocument(code2, ".");
HTMLDocument document3 = new HTMLDocument(code3, ".");
// Create an instance of HTML Renderer
HtmlRenderer renderer = new HtmlRenderer();
// Create an instance of the PdfDevice class
PdfDevice device = new PdfDevice("output.pdf");
// Merge all HTML documents to PDF
renderer.render(device, new HTMLDocument[]{document1, document2, document3});
// Prepare HTML code
String code = "< script >\n" +
" var count = 0;\n" +
" setInterval(function()\n" +
" {\n" +
" var element = document.createElement('div');\n" +
" var message = (++count) + '. ' + 'Hello, World!!';\n" +
" var text = document.createTextNode(message);\n" +
" element.appendChild(text);\n" +
" document.body.appendChild(element);\n" +
" },1000);\n" +
"</script >\n";
// Initialize an HTML document based on prepared HTML code
HTMLDocument document = new HTMLDocument(code, ".");
// Create an instance of HTML Renderer
HtmlRenderer renderer = new HtmlRenderer();
// Create an instance of the PdfDevice class
PdfDevice device = new PdfDevice("output.pdf");
// Render HTML to PDF
renderer.render(device, 5, document);
// Prepare HTML code and save it to a file
String code = "<p>Hello, World!!</p>";
try (java.io.FileWriter fileWriter = new java.io.FileWriter("document.html")) {
fileWriter.write(code);
}
// Create an instance of the HTMLDocument class
HTMLDocument document = new HTMLDocument("document.html");
// Initialize options with 'cyan' as a background-color
PdfRenderingOptions options = new PdfRenderingOptions();
options.setBackgroundColor(Color.getCyan());
// Create an instance of the PdfDevice class
PdfDevice device = new PdfDevice(options, "output.pdf");
// Render HTML to PDF
document.renderTo(device);
// Prepare HTML code
String code = "<div>Hello, World!!</div>";
// Initialize an instance of the HTMLDocument class based on prepared code
HTMLDocument document = new HTMLDocument(code, ".");
// Create an instance of the ImageRenderingOptions class
ImageRenderingOptions options = new ImageRenderingOptions();
options.setFormat(ImageFormat.Jpeg);
// Disable smoothing mode
options.setSmoothingMode(SmoothingMode.None);
// Set the image resolution as 75 dpi
options.setVerticalResolution(Resolution.fromDotsPerInch(75));
options.setHorizontalResolution(Resolution.fromDotsPerInch(75));
// Create an instance of the ImageDevice class
ImageDevice device = new ImageDevice(options, "output.jpg");
// Render HTML to Image
document.renderTo(device);
// Prepare HTML code
String code = "<style>\n" +
" div { page-break-after: always; }\n" +
"</style>\n" +
"< div > First Page</div >\n" +
"<div > Second Page</div >\n" +
"<div > Third Page</div >\n" +
"<div > Fourth Page</div >\n";
// Initialize the HTML document from the HTML code
HTMLDocument document = new HTMLDocument(code, ".");
// Create the instance of the PdfRenderingOptions class and set a custom page-size
PdfRenderingOptions options = new PdfRenderingOptions();
options.getPageSetup().setLeftRightPage(
new Page(new Size(400, 200)),
new Page(new Size(400, 100))
);
// Create an instance of the PdfDevice class
PdfDevice device = new PdfDevice(options, "output.pdf");
// Render HTML to PDF
document.renderTo(device);
// Prepare HTML code
String code = "<span>Hello, World!!</span>";
// Initialize an HTML document from the HTML code
HTMLDocument document = new HTMLDocument(code, ".");
// Create an instance of the PdfRenderingOptions class
PdfRenderingOptions options = new PdfRenderingOptions();
// Set the 'screen' media-type
options.getCss().setMediaType(MediaType.Screen);
// Create a PDF Device and specify options and output file
PdfDevice device = new PdfDevice(options, "output.pdf");
// Render HTML to PDF
document.renderTo(device);
// Prepare HTML code
String code = "<span>Hello, World!!</span>";
// Initialize an HTML document from HTML code
HTMLDocument document = new HTMLDocument(code, ".");
// Create an instance of the PdfDevice class and specify the output file to render
PdfDevice device = new PdfDevice("output.pdf");
// Render HTML to PDF
document.renderTo(device);
// Prepare HTML code
String code = "<div>Hello, World!!</div>";
// Initialize an HTML document from the HTML code
HTMLDocument document = new HTMLDocument(code, ".");
// Create the instance of the PdfRenderingOptions class
PdfRenderingOptions options = new PdfRenderingOptions();
// Set file permissions
options.setEncryption(
new PdfEncryptionInfo(
"user_pwd",
"owner_pwd",
PdfPermissions.PrintDocument,
PdfEncryptionAlgorithm.RC4_128
)
);
// Create a PDF Device and specify options and output file
PdfDevice device = new PdfDevice(options, "output.pdf");
// Render HTML to PDF
document.renderTo(device);
// Prepare HTML code
String code = "<span>Hello, World!!</span>";
// Initialize a HTML document from the HTML code
HTMLDocument document = new HTMLDocument(code, ".");
// Create an instance of PdfRenderingOptions and set a custom page-size
PdfRenderingOptions options = new PdfRenderingOptions();
PageSetup pageSetup = new PageSetup();
Page anyPage = new Page();
anyPage.setSize(
new Size(
Length.fromInches(5),
Length.fromInches(2)
)
);
pageSetup.setAnyPage(anyPage);
options.setPageSetup(pageSetup);
// Create a PDF Device and specify options and output file
PdfDevice device = new PdfDevice(options, "output.pdf");
// Render HTML to PDF
document.renderTo(device);
// Prepare HTML code and save it to a file
String code = "< style >\n" +
" p\n" +
" {\n" +
" background:\n" +
" blue;\n" +
" }\n" +
" @media(min - resolution:300dpi)\n" +
" {\n" +
" p\n" +
" {\n" +
" /* high resolution screen color */\n" +
" background:\n" +
" green\n" +
" }\n" +
" }\n" +
" </style >\n" +
" <p > Hello World !! </p >\n";
try (java.io.FileWriter fileWriter = new java.io.FileWriter("document.html")) {
fileWriter.write(code);
}
// Create an instance of the HTMLDocument class
HTMLDocument document = new HTMLDocument("document.html");
// Create options for low-resolution screens
PdfRenderingOptions options = new PdfRenderingOptions();
options.setHorizontalResolution(Resolution.to_Resolution(50d));
options.setVerticalResolution(Resolution.to_Resolution(50d));
// Create an instance of the PdfDevice
PdfDevice device = new PdfDevice(
options,
"output_resolution_50.pdf"
);
// Render HTML to PDF
document.renderTo(device);
// Create options for high-resolution screens
options = new PdfRenderingOptions();
options.setHorizontalResolution(Resolution.to_Resolution(300d));
options.setVerticalResolution(Resolution.to_Resolution(300d));
// Create an instance of PDF device
device = new PdfDevice(
options,
"output_resolution_300.pdf"
);
// Render HTML to PDF
document.renderTo(device);
// Prepare HTML code
String code = "<span>Hello, World!!</span>";
// Initialize an HTML document from the HTML code
HTMLDocument document = new HTMLDocument(code, ".");
// Create an instance of XpsRenderingOptions and set a custom page-size
XpsRenderingOptions options = new XpsRenderingOptions();
Page anyPage = new Page();
anyPage.setSize(
new Size(
Length.fromInches(5),
Length.fromInches(2)
)
);
options.getPageSetup().setAnyPage(anyPage);
// Create an XPS Device and specify options and output file
XpsDevice device = new XpsDevice(options, "output.xps");
// Render HTML to XPS
document.renderTo(device);
// Initialize License Instance
com.aspose.html.License license = new com.aspose.html.License();
// Set license from Stream
license.setLicense(new java.io.FileInputStream("Aspose.HTML.lic"));
HTMLDocument document = new HTMLDocument("<style>p { color: green; }</style><p>my first paragraph</p>", "c:\\work\\");
// Initialize rendering optionss and set jpeg as output format
ImageRenderingOptions options = new ImageRenderingOptions(ImageFormat.Jpeg);
// Set the size and margin property for all pages.
options.getPageSetup().setAnyPage(
new Page(
new Size(500, 500),
new Margin(50, 50, 50, 50)
)
);
// If the document has an element which size is bigger than predefined by user page size output pages will be will be adjusted.
options.getPageSetup().setAdjustToWidestPage(true);
ImageDevice device = new ImageDevice(options, "document_out.jpg");
document.renderTo(device);
HTMLDocument document = new HTMLDocument("<style>p { color: green; }</style><p>my first paragraph</p>", "c:\\work\\");
ImageDevice device = new ImageDevice("document_out.png");
document.renderTo(device);
HTMLDocument document = new HTMLDocument("<style>p { color: green; }</style><p>my first paragraph</p>", "c:/work/");
XpsRenderingOptions xpsRenderingOptions = new XpsRenderingOptions();
PageSetup pageSetup = new PageSetup();
Page anyPage = new Page(
new Size(500, 500),
new Margin(50, 50, 50, 50)
);
pageSetup.setAnyPage(anyPage);
xpsRenderingOptions.setPageSetup(pageSetup);
XpsDevice device = new XpsDevice(
xpsRenderingOptions,
"document_out.xps"
);
document.renderTo(device);
// Initialize a webAccessibility container
WebAccessibility webAccessibility = new WebAccessibility();
// Get the principle by code
Principle principle = webAccessibility.getRules().getPrinciple("1");
// Get guideline
Guideline guideline = principle.getGuideline("1.1");
// Get criterion by code
Criterion criterion = guideline.getCriterion("1.1.1");
if (criterion != null) {
System.out.println(String.format("%s: %s - %s",
criterion.getCode(),
criterion.getDescription(),
criterion.getLevel()
));
// @output: 1.1.1:Non-text Content - A
// Get all Sufficient Techniques and write to console
for (IRule technique : criterion.getSufficientTechniques())
System.out.println(String.format("%s: %s",
technique.getCode(),
technique.getDescription()
));
}
// Initialize a webAccessibility container
WebAccessibility webAccessibility = new WebAccessibility();
// Get the principle by code
Principle principle = webAccessibility.getRules().getPrinciple("1");
// Get guideline 1.1
Guideline guideline = principle.getGuideline("1.1");
if (guideline != null) {
System.out.println(String.format("%s: %s, %s",
guideline.getCode(),
guideline.getDescription(),
guideline
));
// @output: 1.1:Text Alternatives
}
// Initialize a webAccessibility container
WebAccessibility webAccessibility = new WebAccessibility();
// Get the principle by code
Principle rule = webAccessibility.getRules().getPrinciple("1");
// Get code and description of principle
System.out.println(String.format("%s: %s",
rule.getCode(),
rule.getDescription()
));
// @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
List<IRule> rules = webAccessibility.getRules().getRules(rulesCodes);
// Get code and description of rule
for (IRule rule : rules) {
System.out.println(String.format("%s: %s",
rule.getCode(),
rule.getDescription()
));
}
// Create an empty HTML document
HTMLDocument document = new HTMLDocument();
// Create the Canvas element
HTMLCanvasElement canvas = (HTMLCanvasElement) document.createElement("canvas");
// with a specified size
canvas.setWidth(300);
canvas.setHeight(150);
// and append it to the document body
document.getBody().appendChild(canvas);
// Get the canvas rendering context to draw
ICanvasRenderingContext2D context = (ICanvasRenderingContext2D) canvas.getContext("2d");
// Prepare the 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 brush to the content
context.setFillStyle(gradient);
context.setStrokeStyle(gradient);
// Write the Text
context.fillText("Hello, World!", 10, 90, 500d);
// Fill the Rectangle
context.fillRect(0, 95, 300, 20);
// Create the PDF output device
PdfDevice device = new PdfDevice("canvas.output.2.pdf");
// Render HTML5 Canvas to PDF
document.renderTo(device);
// 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 >\n" +
"<script >\n" +
" var c = document.getElementById('myCanvas');\n" +
" var context = c.getContext('2d');\n" +
" context.font = '20px Arial';\n" +
" context.fillStyle = 'red';\n" +
" context.fillText('Hello, World', 40, 50);\n" +
"</script >\n";
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");
public class HTMLDocumentWaiter implements Runnable {
private final HTMLDocumentAsynchronouslyOnLoad html;
public HTMLDocumentWaiter(HTMLDocumentAsynchronouslyOnLoad html) throws Exception {
this.html = html;
this.html.execute();
}
@Override
public void run() {
System.out.println("Current Thread: " + Thread.currentThread().getName() + "; " + Thread.currentThread().getId());
while (!Thread.currentThread().isInterrupted() && html.getMsg() == null) {
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
Thread.currentThread().interrupt();
}
}
// 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 Form Editor
FormEditor editor = FormEditor.create(document, 0);
// You can fill the data up using direct access to the input elements, like this:
editor.get_Item("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> map = new java.util.HashMap<>();
map.put("custemail", "[email protected]");
map.put("custtel", "+1202-555-0290");
editor.fill(map);
// Create an instance of form submitter
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")) {
// Dump result data to the console
System.out.println(result.getContent().readAsString());
} else {
// Load the result data as an HTML document
Document resultDocument = result.loadDocument();
// Inspect HTML document here.
System.out.println(resultDocument.getDocumentElement().getTextContent());
}
}
// Prepare a JSON data-source and save it to a file
String data =
"{\n" +
" 'FirstName': 'John',\n" +
" 'LastName': 'Smith',\n" +
" 'Address': {\n" +
" 'City': 'Dallas',\n" +
" 'Street': 'Austin rd.',\n" +
" 'Number': '200'\n" +
" }\n" +
"}";
try (java.io.FileWriter fileWriter = new java.io.FileWriter("data-source.json")) {
fileWriter.write(data);
}
// Prepare an HTML Template and save it to a file
String template =
"<table border=1>\n" +
" <tr>\n" +
" <th>Person</th>\n" +
" <th>Address</th>\n" +
" </tr>\n" +
" <tr>\n" +
" <td>{{FirstName}} {{LastName}}</td>\n" +
" <td>{{Address.Street}} {{Address.Number}}, {{Address.City}}</td>\n" +
" </tr>\n" +
"</table>\n";
try (java.io.FileWriter fileWriter = new java.io.FileWriter("template.html")) {
fileWriter.write(template);
}
// Convert Template to HTML
com.aspose.html.converters.Converter.convertTemplate(
"template.html",
new com.aspose.html.converters.TemplateData("data-source.json"),
new com.aspose.html.loading.TemplateLoadOptions(), "document.html"
);
// Source HTML document
HTMLDocument htmlDocument = new HTMLDocument("input.html");
// Initialize ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Bmp);
// Output file path
String outputFile = "HTMLtoBMP_Output.bmp";
// Convert HTML to BMP
Converter.convertHTML(htmlDocument, options, outputFile);
// Source HTML document
HTMLDocument htmlDocument = new HTMLDocument("input.html");
// Initialize ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Gif);
// Output file path
String outputFile = "HTMLtoGIF_Output.gif";
// Convert HTML to GIF
Converter.convertHTML(htmlDocument, options, outputFile);
// Source HTML document
HTMLDocument htmlDocument = new HTMLDocument("input.html");
// Initialize ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Jpeg);
// Output file path
String outputFile = "HTMLtoJPEG_Output.jpeg";
// Convert HTML to JPEG
Converter.convertHTML(htmlDocument, options, outputFile);
HTMLDocument document = new HTMLDocument("<p>my first paragraph</p>", Resources.outputDirectory());
// Create MarkdownSaveOptions object
MarkdownSaveOptions options = new MarkdownSaveOptions();
// Set the rules: only <a>, <img> and <p> elements will be converted to markdown.
options.setFeatures(MarkdownFeatures.Link | MarkdownFeatures.Image | MarkdownFeatures.AutomaticParagraph);
document.save("output.rules.html.to.md", options);
// Prepare HTML code and save it to a file
String code = "<h1>Convert HTML to Markdown Using Java</h1>" +
"<h2>How to Convert HTML to MD in Java</h2>" +
"<p>The Aspose.HTML for Java library allows you to convert HTML to Markdown.</p>";
FileHelper.writeAllText("conversion.html", code);
// Call ConvertHTML() method to convert HTML to Markdown
Converter.convertHTML("conversion.html", new MarkdownSaveOptions(), "conversion.md");
HTMLDocument document = new HTMLDocument("<p>my first paragraph</p>", Resources.outputDirectory());
// Save to markdown by using default for the GIT formatting model
document.save("Markdown-with-options.out.md", MarkdownSaveOptions.getGit());
// Initialize an HTML document from the file
HTMLDocument document = new HTMLDocument("drawing.html");
// Initialize MHTMLSaveOptions
MHTMLSaveOptions options = new MHTMLSaveOptions();
// Convert HTML to MHTML
Converter.convertHTML(document, options, "drawing-output.mht");
// Source HTML document
HTMLDocument htmlDocument = new HTMLDocument("input.html");
// Initialize ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Png);
// Output file path
String outputFile = "HTMLtoPNG_Output.png";
// Convert HTML to PNG
Converter.convertHTML(htmlDocument, options, outputFile);
// Source HTML document
HTMLDocument htmlDocument = new HTMLDocument("input.html");
// Initialize ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Tiff);
// Output file path
String outputFile = "HTMLtoPNG_Output.tif";
// Convert HTML to TIFF
Converter.convertHTML(htmlDocument, options, outputFile);
// Source HTML document
HTMLDocument htmlDocument = new HTMLDocument("input.html");
// Initialize XpsSaveOptions
XpsSaveOptions options = new XpsSaveOptions();
options.setBackgroundColor(Color.getCyan());
// Output file path
String outputFile = "output.html.to.xps";
// Convert HTML to XPS
Converter.convertHTML(htmlDocument, options, outputFile);
// Load a document from a file
String documentPath = "html_file.html";
final HTMLDocument document = new HTMLDocument(documentPath);
// Get the html element of the document
Element element = document.getDocumentElement();
System.out.println(element.getTagName());
// Output: HTML
// Get the last element of the html element
element = element.getLastElementChild();
System.out.println(element.getTagName());
// Output: BODY
// Get the first element in the body element
element = element.getFirstElementChild();
System.out.println(element.getTagName());
// Output: H1
System.out.println(element.getTextContent());
// Output: Header 1
// Initialize a webAccessibility container
WebAccessibility webAccessibility = new WebAccessibility();
// Create an accessibility validator with static instance for all rules
// from repository that match the builder settings
AccessibilityValidator validator = webAccessibility.createValidator(ValidationBuilder.getAll());
String documentPath = "input.html";
// Initialize an object of the HTMLDocument class
final HTMLDocument document = new HTMLDocument(documentPath);
ValidationResult validationResult = validator.validate(document);
// Take a list of rules results
for (RuleValidationResult ruleResult : validationResult.getDetails()) {
// List only unsuccessful rule
if (!ruleResult.getSuccess()) {
// Print the code and description of the rule
System.out.println(String.format("%s: %s",
ruleResult.getRule().getCode(),
ruleResult.getRule().getDescription()
));
// Print the results of all methods
for (ITechniqueResult ruleDetail : ruleResult.getResults()) {
// Print the code and description of the criterions
StringBuilder str = new StringBuilder(String.format("\n{0}: {1} - {2}",
ruleDetail.getRule().getCode(),
ruleDetail.getSuccess(),
ruleDetail.getRule().getDescription()
));
System.out.println(str);
}
}
}
// instantiate License object
com.aspose.html.License license = new com.aspose.html.License();
// license file path information
license.setLicense("Aspose.HTML.lic");
// Convert markdown to HTML
Converter.convertMarkdown(
"input.md",
"Markdown-to-HTML.out.html"
);
public class MemoryOutputStreamProvider
implements java.io.Closeable,
ICreateOutputStreamProvider {
// List of InputStream objects created during the document rendering
public java.util.List<java.io.InputStream> lStream = new java.util.ArrayList<>();
private java.util.List<OutputStream> outpuStreamList = new java.util.ArrayList<>();
@Override
public void close()
throws
java.io.IOException {
for (java.io.InputStream stream : lStream) {
stream.close();
}
for (OutputStream stream : outpuStreamList) {
stream.close();
}
}
public List<OutputStream> getStreams() {
return outpuStreamList;
}
@Override
public OutputStream getOutputStream(
String name,
String extension
) {
// This method is called when only one output stream is required, for instance for XPS, PDF or TIFF formats
MemoryOutputStream result = new MemoryOutputStream();
getStreams().add(result);
return OutputStream.fromStream(result);
}
@Override
public OutputStream getOutputStream(
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.)
MemoryOutputStream result = new MemoryOutputStream();
getStreams().add(result);
return OutputStream.fromStream(result);
}
@Override
public void releaseOutputStream(OutputStream stream) {
// Here you can release the stream filled with data and, for instance, flush it to the hard-drive
}
@Override
public void dispose() {
// Releasing resources
// foreach to while statements conversion
Iterator tmp0 = (getStreams()).iterator();
while (tmp0.hasNext()) {
MemoryOutputStream stream = (MemoryOutputStream) tmp0.next();
stream.dispose();
}
}
}
// 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();
}
}
}
import com.aspose.html.net.INetworkOperationContext;
import com.aspose.html.net.MessageHandler;
public class CredentialHandler extends MessageHandler {
@Override
public void invoke(INetworkOperationContext context) {
// TODO: NetworkCredential is hidden class
// context.getRequest().setCredentials(new NetworkCredential("username", "securelystoredpassword"));
context.getRequest().setPreAuthenticate(true);
invoke(context);
}
}
// Create an instance of the Configuration class
Configuration configuration = new Configuration();
// Add the CredentialHandler to the chain of existing message handlers
INetworkService service = configuration.getService(INetworkService.class);
MessageHandlerCollection handlers = service.getMessageHandlers();
handlers.insertItem(0, new CredentialHandler());
// Initialize an HTML document with specified configuration
HTMLDocument document = new HTMLDocument("https://httpbin.org/basic-auth/username/securelystoredpassword", configuration);
import com.aspose.html.net.INetworkOperationContext;
import com.aspose.html.net.MessageFilter;
public class CustomSchemaMessageFilter extends MessageFilter {
private String schema;
CustomSchemaMessageFilter(String schema) {
this.schema = schema;
}
@Override
public boolean match(INetworkOperationContext context) {
String protocol = context.getRequest().getRequestUri().getProtocol();
return (schema + ":").equals(protocol);
}
}
public abstract class CustomSchemaMessageHandler extends MessageHandler {
protected CustomSchemaMessageHandler(String schema) {
getFilters().addItem(new CustomSchemaMessageFilter(schema));
}
}
// Create an instance of the Configuration class
Configuration configuration = new Configuration();
// Add the LogMessageHandler to the chain of existing message handlers
INetworkService service = configuration.getService(INetworkService.class);
MessageHandlerCollection handlers = service.getMessageHandlers();
handlers.insertItem(0, new LogMessageHandler());
// Initialize an HTML document with specified configuration
HTMLDocument document = new HTMLDocument("input.htm", configuration);
// Create an instance of the Configuration class
Configuration configuration = new Configuration();
// Call the INetworkService which contains the functionality for managing network operations
INetworkService network = configuration.getService(INetworkService.class);
// Add the TimeoutMessageHandler to the top of existing message handler chain
network.getMessageHandlers().insertItem(0, new TimeoutMessageHandler());
// Convert HTML to PDF with customized configuration
Converter.convertHTML("document.html", configuration, new PdfSaveOptions(), "document.pdf");
// Create an instance of the Configuration class
Configuration configuration = new Configuration();
INetworkService service = configuration.getService(INetworkService.class);
MessageHandlerCollection handlers = service.getMessageHandlers();
// Custom Schema: ZIP. Add ZipFileSchemaMessageHandler to the end of the pipeline
handlers.addItem(new ZIPFileSchemaMessageHandler("test.zip"));
// Duration Logging. Add the StartRequestDurationLoggingMessageHandler at the first place in the pipeline
handlers.insertItem(0, new StartRequestDurationLoggingMessageHandler());
// Add the StopRequestDurationLoggingMessageHandler to the end of the pipeline
handlers.addItem(new StopRequestDurationLoggingMessageHandler());
// Initialize an HTML document with specified configuration
HTMLDocument document = new HTMLDocument("zip-file:///test.html", configuration);
// Create the PDF Device
PdfDevice device = new PdfDevice("zip-to-pdf-duration.pdf");
// Render ZIP to PDF
document.renderTo(device);
public abstract class RequestDurationLoggingMessageHandler extends MessageHandler {
private static Map<Url, Long> requests = new HashMap<>();
protected void startTimer(Url url) {
requests.put(url, System.currentTimeMillis());
}
protected TimeSpan stopTimer(Url url) {
long end = System.currentTimeMillis();
long start = requests.get(url);
return new TimeSpan(end - start);
}
}
import com.aspose.html.net.INetworkOperationContext;
public class StartRequestDurationLoggingMessageHandler extends RequestDurationLoggingMessageHandler {
@Override
public void invoke(INetworkOperationContext context) {
// Start the stopwatch
startTimer(context.getRequest().getRequestUri());
// Invoke the next message handler in the chain
invoke(context);
}
}
import com.aspose.html.net.INetworkOperationContext;
public class StopRequestDurationLoggingMessageHandler extends RequestDurationLoggingMessageHandler {
@Override
public void invoke(INetworkOperationContext context) {
// Start the stopwatch
stopTimer(context.getRequest().getRequestUri());
// Invoke the next message handler in the chain
invoke(context);
}
}
import com.aspose.html.net.INetworkOperationContext;
import com.aspose.html.net.MessageHandler;
public class TimeLoggerMessageHandler extends MessageHandler {
@Override
public void invoke(INetworkOperationContext context) {
// Start the stopwatch
long start = System.currentTimeMillis();
// Invoke the next message handler in the chain
invoke(context);
// Stop the stopwatch
long end = System.currentTimeMillis();
// Print the result
System.out.println("Request: " + context.getRequest().getRequestUri());
System.out.println("Time: " + (end - start) + "ms");
}
}
import com.aspose.html.net.INetworkOperationContext;
import com.aspose.html.net.MessageHandler;
import com.aspose.html.utils.TimeSpan;
public class TimeoutMessageHandler extends MessageHandler {
@Override
public void invoke(INetworkOperationContext context) {
context.getRequest().setTimeout(TimeSpan.fromSeconds(1));
invoke(context);
}
}
// Create an instance of the Configuration class
Configuration configuration = new Configuration();
// Add the TimeLoggerMessageHandler to the chain of existing message handlers
INetworkService service = configuration.getService(INetworkService.class);
MessageHandlerCollection handlers = service.getMessageHandlers();
handlers.insertItem(0, new TimeLoggerMessageHandler());
// Initialize an HTML document with specified configuration
HTMLDocument document = new HTMLDocument("input.htm", configuration);
// Create an instance of ZipArchiveMessageHandler
ZIPArchiveMessageHandler zip = new ZIPArchiveMessageHandler("test.zip");
// Create an instance of the Configuration class
Configuration configuration = new Configuration();
// Add ZipArchiveMessageHandler to the chain of existing message handlers
configuration.getService(INetworkService.class).getMessageHandlers().addItem(zip);
// Initialize an HTML document with specified configuration
HTMLDocument document = new HTMLDocument("zip:///test.html", configuration);
// Create an instance of Rendering Options
ImageRenderingOptions options = new ImageRenderingOptions();
options.setFormat(ImageFormat.Jpeg);
// Create an instance of Image Device
ImageDevice device = new ImageDevice(options, "zip-to-jpg.jpg");
// Render ZIP to JPG
document.renderTo(device);
// Create an instance of the Configuration class
Configuration configuration = new Configuration();
// Add the LogMessageHandler to the chain of existing message handlers
INetworkService service = configuration.getService(INetworkService.class);
MessageHandlerCollection handlers = service.getMessageHandlers();
handlers.insertItem(0, new ZIPArchiveMessageHandler("test.zip"));
HTMLDocument document = new HTMLDocument("zip:///test.html", configuration);
// Create the PDF Device
PdfDevice device = new PdfDevice("zip-to-pdf.pdf");
// Render ZIP to PDF
document.renderTo(device);
// Source MHTML document
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("sample.mht");
// Initialize ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Jpeg);
// Output file path
String outputFile = "MHTMLtoImage.jpeg";
// Convert SVG to Image
Converter.convertMHTML(
fileInputStream,
options,
outputFile
);
// Source MHTML document
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("sample.mht");
// Initialize pdfSaveOptions
PdfSaveOptions options = new PdfSaveOptions();
options.setJpegQuality(100);
// Output file path
String outputFile = "MHTMLtoPDF_Output.pdf";
// Convert MHTML to PDF
Converter.convertMHTML(
fileInputStream,
options,
outputFile
);
// Source EPUUB document
java.io.FileInputStream fileInputStream = new java.io.FileInputStream("sample.mht");
// Initialize XpsSaveOptions
XpsSaveOptions options = new XpsSaveOptions();
options.setBackgroundColor(Color.getCyan());
// Output file path
String outputFile = "MHTMLtoXPS_Output.xps";
// Convert MHTML to XPS
Converter.convertMHTML(fileInputStream, options, outputFile);
// Prepare HTML code
String html_code = "<span>Hello,</span> <span>World!</span>";
// Initialize a document from the prepared code
final HTMLDocument document = new HTMLDocument(html_code, ".");
// Get the reference to the first child (first <span>) of the <body>
Node element = document.getBody().getFirstChild();
System.out.println(element.getTextContent());
// @output: Hello,
// Get the reference to the whitespace between html elements
element = element.getNextSibling();
System.out.println(element.getTextContent());
// @output: ' '
// Get the reference to the second <span> element
element = element.getNextSibling();
System.out.println(element.getTextContent());
// @output: World!
// Set an html variable for the document
String html = document.getDocumentElement().getOuterHTML();
System.out.println(html);
// @output: <html><head></head><body><span>Hello,</span> <span>World!</span></body></html>
// Prepare HTML code
String code =
"<p>Hello,</p>\n" +
"<img src='image1.png'>\n" +
"<img src='image2.png'>\n" +
"<p>World!</p>";
// Initialize a document based on the prepared code
final 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
final 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.getCurrentNode();
System.out.println(image.getSrc());
// @output: image1.png
// @output: image2.png
// Set an html variable for the document
String html = document.getDocumentElement().getOuterHTML();
}
public static class OnlyImageFilter extends NodeFilter {
@Override
public short acceptNode(Node n) {
// The current filter skips all elements, except IMG elements.
return "img".equals(n.getLocalName())
? FILTER_ACCEPT
: FILTER_SKIP;
}
}
String htmlPath = "input.html";
final HTMLDocument document = new HTMLDocument(htmlPath);
AccessibilityValidator validator = new WebAccessibility().createValidator();
ValidationResult validationresult = validator.validate(document);
final java.io.StringWriter sw = new java.io.StringWriter();
validationresult.saveTo(sw, ValidationResultSaveFormat.XML);
String xml = sw.toString();
System.out.println(xml);
DocumentBuilderFactory documentBuildFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuildFactory.newDocumentBuilder();
documentBuilder.parse(new java.io.ByteArrayInputStream(xml.getBytes()));
// Initialize an empty HTML document
HTMLDocument document = new HTMLDocument();
// Create a text node and add it to the document
Text text = document.createTextNode("Hello, World!");
document.getBody().appendChild(text);
// Save the HTML document to a file
document.save("save-to-file.html");
// Prepare a simple HTML file with a linked document
java.nio.file.Files.write(
java.nio.file.Paths.get("save-with-linked-file.html"),
"<p>Hello, World!</p><a href='linked.html'>linked file</a>".getBytes());
// Prepare a simple linked HTML file
java.nio.file.Files.write(java.nio.file.Paths.get(
"linked.html"),
"<p>Hello, linked file!</p>".getBytes());
// Load the "save-with-linked-file.html" into memory
HTMLDocument document = new HTMLDocument("save-with-linked-file.html");
// Create an instance of the HTMLSaveOptions class
HTMLSaveOptions options = new HTMLSaveOptions();
// The following line with the value "0" cuts off all other linked HTML-files while saving this instance
// If you remove this line or change the value to "1", the "linked.html" file will be saved as well to the output folder
options.getResourceHandlingOptions().setMaxHandlingDepth(1);
// Save the document with the save options
document.save("save-with-linked-file_out.html", options);
// Prepare HTML code
String html_code = "<H2>Hello, World!</H2>";
// Initialize a document from a string variable
HTMLDocument document = new HTMLDocument(html_code);
// Save the document as a Markdown file
document.save("save-to-MD.md", HTMLSaveFormat.Markdown);
// Prepare a simple HTML file with a linked document
java.nio.file.Files.write(
java.nio.file.Paths.get("document.html"),
"<p>Hello, World!</p><a href='linked-file.html'>linked file</a>".getBytes());
// Prepare a simple linked HTML file
java.nio.file.Files.write(
java.nio.file.Paths.get("linked-file.html"),
"<p>Hello, linked file!</p>".getBytes());
// Load the "document.html" into memory
HTMLDocument document = new HTMLDocument("document.html");
// Save the document to MHTML format
document.save("save-to-MTHML.mht", HTMLSaveFormat.MHTML);
// Create a blank document; it is required to access the network operations functionality
final 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
final RequestMessage request = new RequestMessage(url);
// Download file from URL
final ResponseMessage response = document.getContext().getNetwork().send(request);
// Check whether response is successful
if (response.isSuccess()) {
String[] split = url.getPathname().split("/");
String path = split[split.length - 1];
// Save file to a local file system
FileHelper.writeAllBytes(path, response.getContent().readAsByteArray());
}
String htmlPath = "input.html";
final 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"
System.out.println(content);
// Initialize an HTML document from a URL
final HTMLDocument document = new HTMLDocument("https://docs.aspose.com/html/net/message-handlers/");
// Prepare a path to save the downloaded file
String savePath = "root/result.html";
// Save the HTML document to the specified file
document.save(savePath);
// Load an HTML document from a URL
final 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();
options.getResourceHandlingOptions().setMaxHandlingDepth(1);
// Prepare a path for downloaded file saving
String savePath = "rootAndAdjacent/result.html";
// Save the HTML document to the specified file
document.save(savePath, options);
// Initialize an HTML document from a URL
final 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();
options.getResourceHandlingOptions().setMaxHandlingDepth(1);
options.getResourceHandlingOptions().setPageUrlRestriction(UrlRestriction.SameHost);
// Prepare a path to save the downloaded file
String savePath = "rootAndManyAdjacent/result.html";
// Save the HTML document to the specified file
document.save(savePath, options);
// Initialize an HTML document from a URL
final 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();
options.getResourceHandlingOptions().setJavaScript(ResourceHandling.Embed);
// Prepare a path to save the downloaded file
String savePath = "rootAndEmbedJs/result.html";
// Save the HTML document to the specified file
document.save(savePath, options);
// Initialize an SVG document from the file
SVGDocument document = new SVGDocument("gradient.svg");
// Initialize an instance of ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions();
// Convert SVG to PNG
Converter.convertSVG(document, options, "gradient-options.png");
// Prepare an SVG code
String code = "<svg xmlns='http://www.w3.org/2000/svg' height='80' width='300'>\n" +
" <g fill='none'>\n" +
" <path stroke='red' d='M5 20 l215 0' />\n" +
" <path stroke='black' d='M5 40 l215 0' />\n" +
" <path stroke='blue' d='M5 60 l215 0' />\n" +
" </g>\n" +
" </svg>\n";
// Initialize a SVG instance from the content string
SVGDocument document = new SVGDocument(code, ".");
// Initialize an instance of ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Png);
// Convert SVG to PNG
Converter.convertSVG(document, options, "gradient-options.png");
// Initialize an SVG document from the file
SVGDocument document = new SVGDocument("gradient.svg");
// Initialize an instance of ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions();
// Convert SVG to PNG
Converter.convertSVG(document, options, "gradient-options.png");
// Create an instance of the HTMLDocument class
HTMLDocument document = new HTMLDocument();
// Subscribe to the 'OnLoad' event. This event will be fired once the document is fully loaded
document.OnLoad.add(new DOMEventHandler() {
@Override
public void invoke(Object sender, Event e) {
msg = document.getDocumentElement().getOuterHTML();
System.out.println(msg);
}
});
// Navigate asynchronously at the specified Uri
document.navigate("https://html.spec.whatwg.org/multipage/introduction.html");
// Source SVG document
SVGDocument svgDocument = new SVGDocument("input.svg");
// Initialize ImageSaveOptions
ImageSaveOptions options = new ImageSaveOptions(ImageFormat.Jpeg);
// Output file path
String outputFile = "SVGtoImage_Output.jpeg";
// Convert SVG to Image
Converter.convertSVG(svgDocument, options, outputFile);
// Source SVG document
SVGDocument svgDocument = new SVGDocument("input.svg");
// Initialize pdfSaveOptions
PdfSaveOptions options = new PdfSaveOptions();
options.setJpegQuality(100);
// Output file path
String outputFile = "SVGtoPDF_Output.pdf";
// Convert SVG to PDF
Converter.convertSVG(svgDocument, options, outputFile);
// Source SVG document
SVGDocument svgDocument = new SVGDocument("input.svg");
// Initialize XpsSaveOptions
XpsSaveOptions options = new XpsSaveOptions();
options.setBackgroundColor(Color.getCyan());
// Output file path
String outputFile = "SVGtoXPS_Output.xps";
// Convert SVG to XPS
Converter.convertSVG(svgDocument, options, outputFile);
// Initialize configuration object and set up the page-margins for the document
Configuration configuration = new Configuration();
configuration.getService(IUserAgentService.class).setUserStyleSheet(
"@page\n" +
" {\n" +
" /* Page margins should be not empty in order to write content inside the margin-boxes */\n" +
" margin - top:1 cm;\n" +
" margin - left:2 cm;\n" +
" margin - right:2 cm;\n" +
" margin - bottom:2 cm;\n" +
"\n" +
" /* Page counter located at the bottom of the page */\n" +
" @bottom -right\n" +
" {\n" +
" -aspose - content:\"\" Page \"\" currentPageNumber() \"\" of \"\" totalPagesNumber();\n" +
" color:\n" +
" green;\n" +
" }\n" +
"\n" +
" /* Page title located at the top-center box */\n" +
" @top -center\n" +
" {\n" +
" -aspose - content:\"\" Document 's title\"\";\n" +
" vertical - align:bottom;\n" +
" }\n" +
" }\n"
);
// Initialize an empty document
HTMLDocument document = new HTMLDocument(configuration);
// Initialize an output device
XpsDevice device = new XpsDevice("output_out.xps");
// Send the document to the output device
document.renderTo(device);
// Initialize a metered object
com.aspose.html.Metered metered = new com.aspose.html.Metered();
// Apply the metered license using the public and private keys
metered.setMeteredKey("PublicKey", "PrivateKey");
// 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.getRules()
.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.getAll()
);
// Initialize an HTMLDocument object
final HTMLDocument document = new HTMLDocument("https://www.youtube.com/watch?v=Yugq1KyZCI0");
ValidationResult validationResult = validator.validate(document);
// Checking for success
if (!validationResult.getSuccess()) {
// Get all result details
for (RuleValidationResult ruleResult : validationResult.getDetails()) {
// If the result of the rule is unsuccessful
if (!ruleResult.getSuccess()) {
// Get an errors list
for (ITechniqueResult result : ruleResult.getErrors()) {
// Check the type of the erroneous element
if (result.getError().getTarget().getTargetType() == TargetTypes.HTMLElement) {
HTMLElement rule = (HTMLElement) result.getError().getTarget().getItem();
System.out.println(String.format("Error in rule %s : %s",
result.getRule().getCode(),
result.getError().getErrorMessage()
));
System.out.println(String.format("HTML Element: %s",
rule.getOuterHTML()
));
}
}
}
}
}
// Initialize webAccessibility container
WebAccessibility webAccessibility = new WebAccessibility();
// Create an accessibility validator with static instance
// for all rules from repository that match the builder settings
AccessibilityValidator validator = webAccessibility.createValidator(ValidationBuilder.getAll());
// Initialize an HTMLDocument object
final HTMLDocument document = new HTMLDocument("https://products.aspose.com/html/net/generators/video/");
ValidationResult validationResult = validator.validate(document);
// Checking for success
if (!validationResult.getSuccess()) {
// Get a list of Details
for (RuleValidationResult detail : validationResult.getDetails()) {
System.out.println(String.format("%s: %s = %s",
detail.getRule().getCode(),
detail.getRule().getDescription(),
detail.getSuccess()
));
}
}
// Initialize a webAccessibility container
WebAccessibility webAccessibility = new WebAccessibility();
// Create an accessibility validator with static instance for all rules
// from repository that match the builder settings
AccessibilityValidator validator = webAccessibility.createValidator(ValidationBuilder.getAll());
// Prepare a path to a source HTML file
String documentPath = "input.html";
// Initialize an object of the HTMLDocument class
final HTMLDocument document = new HTMLDocument(documentPath);
ValidationResult validationResult = validator.validate(document);
// Checking for success
if (!validationResult.getSuccess()) {
// Get a list of RuleValidationResult Details
for (RuleValidationResult detail : validationResult.getDetails()) {
System.out.println(String.format("%s: %s = %s",
detail.getRule().getCode(),
detail.getRule().getDescription(),
detail.getSuccess()));
}
}
// 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 = "test-checker.html";
// Initialize an HTMLDocument object
final HTMLDocument document = new HTMLDocument(documentPath);
ValidationResult result = validator.validate(document);
// Checking for success
if (!result.getSuccess()) {
for (RuleValidationResult detail : result.getDetails()) {
// ... do the analysis here...
System.out.println(String.format("%s: %s = %s",
detail.getRule().getCode(),
detail.getRule().getDescription(),
detail.getSuccess()
));
}
}
// Prepare HTML code
String code = "< div class='happy' >\n" +
" <div >\n" +
" <span > Hello, </span >\n" +
" </div >\n" +
" </div >\n" +
" <p class='happy' >\n" +
" <span > World ! </span >\n" +
" </p >\n";
// Initialize a document based on the prepared code
HTMLDocument document = new HTMLDocument(code, ".");
// Here, we create a CSS Selector that extracts all elements whose 'class' attribute equals to 'happy' and their child SPAN elements
NodeList elements = document.querySelectorAll(".happy span");
// Iterate over the resulted list of elements
elements.forEach(element -> {
System.out.println(((HTMLElement) element).getInnerHTML());
// @output: Hello,
// @output: World!
});
// Prepare HTML code
String html_code = "<span>Hello,</span> <span>World!</span>";
// Initialize a document from the prepared code
HTMLDocument document = new HTMLDocument(html_code, ".");
// Get the reference to the first child (first <span>) of the document body
Element element = document.getBody().getFirstElementChild();
System.out.println(element.getTextContent());
// @output: Hello,
// Get the reference to the second <span> element
element = element.getNextElementSibling();
System.out.println(element.getTextContent());
// @output: World!
// Prepare HTML code
String code = " < p > Hello, </p >\n" +
" <img src = 'image1.png' >\n" +
" <img src = 'image2.png' >\n" +
" <p > World ! </p >\n";
// Initialize a document based on the prepared code
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
ITreeWalker iterator = document.createTreeWalker(document, NodeFilter.SHOW_ALL, new HtmlNavigationTests.OnlyImageFilter());
// Use
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.getCurrentNode();
System.out.println(image.getSrc());
// @output: image1.png
// @output: image2.png
}
// Prepare HTML code
String code = "< div class='happy' >\n" +
" <div >\n" +
" <span > Hello! </span >\n" +
" </div >\n" +
" </div >\n" +
" <p class='happy' >\n" +
" <span > World! </span >\n" +
" </p >\n";
// Initialize a document based on the prepared code
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; ) {
System.out.println(node.getTextContent());
// @output: Hello!
// @output: World!
}
// 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
SVGDocument document = new SVGDocument(code, ".");
// Save the SVG file to disk
document.save("save-to-SVG.svg");
// Prepare HTML code
String code =
"<div class='happy'>\n" +
" <div>\n" +
" <span>Hello,</span>\n" +
" </div>\n" +
"</div>\n" +
"<p class='happy'>\n" +
" <span>World!</span>\n" +
"</p>";
// Initialize a document based on the prepared code
final 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; ) {
System.out.println(node.getTextContent());
// @output: Hello,
// @output: World!
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment