May 7, 2006

I’ve been using the Java2HTML library for a while now and it’s been doing a great job in my usage as an Ant task. I discovered Markus Gebhard’s Java2HTML library a few years back and have been very happy with it. Markus has done a great job in creating this open source library that converts Java (and other) source code (complete files or snippets) to HTML, RTF, TeX and XHTML with syntax highlighting. Out of the box, Java2HTML provides a CLI interface, GUI client, Ant task, Eclipse plugin and a JSPWiki plugin.

I downloaded the latest version as I was looking for something that would allow me to create valid XHTML with CSS and I have been very impressed with the quality of this library. In addition to all the stuff that comes out of the box, you can use Java2HTML programmatically to take Java, XML or any other piece of code and output XHTML. Here’s a snippet of code that takes a String of code and output a XHTML document.

    public static void main(String[] args) throws IOException {

        String code = "... java code ....";

        JavaSourceConversionOptions options = JavaSourceConversionOptions.getDefault();
        options.setShowFileName(false);
        options.setShowLineNumbers(false);

        JavaSourceStyleTable style = JavaSourceStyleTable.getDefaultEclipseStyleTable();
        options.setStyleTable(style);

        JavaSourceParser parser = new JavaSourceParser(options);
        JavaSource javaCode = parser.parse(code);

        JavaSource2Xhtml11Converter conveter = new JavaSource2Xhtml11Converter();
        String header = conveter.getDocumentHeader(options, "Java2HTML now does XHTML");
        String footer = conveter.getDocumentFooter(options);
        StringWriter sr = new StringWriter();
        sr.write(header);
        conveter.convert(javaCode, options, sr);
        sr.write(footer);
        
        System.out.println("sr.getBuffer().toString() = " + sr.getBuffer().toString());
    }

The snippet has been edited for brevity but you can see the complete class here, rendered out as an XHTML document. Here’s a link to W3C’s validator.

java, java2html, ant, eclipse, jspwiki, xhtml, xhtml1.1, css, validator, Markus+Gebhard

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: