Use the parser to create HTML

512 views
Skip to first unread message

jebr...@gmail.com

unread,
Nov 11, 2013, 1:10:08 PM11/11/13
to java-p...@googlegroups.com

Hi everyone,

I needed to have some java code displayed in an HTML page with syntax highlighting. Something similar to what you can achieve with the PHP Library GeSHI but in pure Java.

Starting with the idea described here “Use the parser alone” [1], I wrote a converter method that convert the parserResults into HTML code.

I also wrote a method to convert a theme as css file.

==> See attached file for the source code.

Here is an example, how you can use it.

public static String parseAndConvert(String content, Theme theme) {

       StringBuilder sb = new StringBuilder();

       sb.append("<html>\n");

       sb.append("<head>\n");

       sb.append("<title>Source code</title>\n");

       sb.append("<style type=\"text/css\">/*<![CDATA[*/\n");

       sb.append(PrettifyToHtml.toCss(theme));

       sb.append("/*]]>*/\n");

       sb.append("</style>\n");

       sb.append("</head>\n");

       sb.append("<body>\n");

       sb.append("<h1>Source code</h1>\n");

       PrettifyParser parser = new PrettifyParser();

       List<ParseResult> parseResults = parser.parse("java", content);

       sb.append(PrettifyToHtml.toHtml(content, parseResults));

       sb.append("</body>\n");

       sb.append("</html>\n");

       return sb.toString();

}

To test this, you can run this Main:

public class Main2 {

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

        StringBuilder sb = new StringBuilder();

        sb.append("public class Person {\n");

        sb.append("    String name;\n");

        sb.append("    String lastname;\n");

        sb.append("    \n");

        sb.append("    public String getName() {\n");

        sb.append("        return name;\n");

        sb.append("    }\n");

        sb.append("    \n");

        sb.append("    public void setName(String name) {\n");

        sb.append("        this.name = name;\n");

        sb.append("    }\n");

        sb.append("    \n");

        sb.append("    public String getLastname() {\n");

        sb.append("        return lastname;\n");

        sb.append("    }\n");

        sb.append("    \n");

        sb.append("    public void setLastname(String lastname) {\n");

        sb.append("        this.lastname = lastname;\n");

        sb.append("    \n");

        sb.append("}\n");

        String content = sb.toString();

 

        String result = UsageExample.parseAndConvert(content, new ThemeDesert());

        System.out.println(result);

    }

}


I hope it will help other people. 

Cheers,

Jérémie Bresson.

[1] https://code.google.com/p/java-prettify/wiki/UseTheParserAlone

PrettifyToHtml.java
PrettifyToHtmlTest.java
Reply all
Reply to author
Forward
0 new messages