One machine can do the work of fifty ordinary men. No machine can do the work of one extraordinary man

Friday, March 29, 2013

Generate HTML Content in JAVA

This post is for generating HTML content in java. You can use 3rd party jar called rendersnake to do this kind of thing very easily. This has class called HTMLCanvas and you use hierarchical structure to build the HTML.

You can find more samples and information from
http://rendersnake.org/index.html
https://code.google.com/p/rendersnake/

This is a free opensource library and can find the license here : http://www.apache.org/licenses/LICENSE-2.0.html

Here is a sample code snippet

    HtmlCanvas htmlCanvas = new HtmlCanvas();

HtmlAttributes tableAttributes = new HtmlAttributes();
tableAttributes
.add("border", "1")
.add("bgcolor", "#E8E8E8")
.add("cellspacing", "0")
.add("cellpadding", "5")
.add("bordercolor", "#B0B0B0");

HtmlAttributes rowHeaderAttribute = new HtmlAttributes();
rowHeaderAttribute.add("bgcolor", "#C8C8C8");

HtmlAttributes taskRowHeaderAttribute = new HtmlAttributes();
taskRowHeaderAttribute.add("bgcolor", "#C8C8C8");
taskRowHeaderAttribute.add("width", "400");
taskRowHeaderAttribute.add("height", "50");

HtmlAttributes cellColor = new HtmlAttributes();
cellColor.add("bgcolor", "#009933");

htmlCanvas.html()
.body()
.b().content("Status : OK")
.br()
.table(tableAttributes).th(taskRowHeaderAttribute).content("Task")
.th(rowHeaderAttribute).content("User")
.th(rowHeaderAttribute).content("Host")
.th(rowHeaderAttribute).content("Status");

for(int i=0; i<10; i++) {
htmlCanvas.tr().td().content("Task " + i)
.td().content("User " + i)
.td().content("Host " + i)
.td(cellColor).content("Status " + 1)
._tr();
}
htmlCanvas._table().br().br()._body()._html();
   System.out.println("Result : " + htmlCanvas.toHtml());

Following is the result of above code.



You need to add the jar that downloaded from the above link and can do this kind of table very easily. If there is a exception occurred when you run the application call specifically "commons-lang3-3.1.jar" not found, you need to add that jar file as well. You can find this jar from http://commons.apache.org/proper/commons-lang/download_lang.cgi

No comments:

Post a Comment