## Sunday, June 12, 2011

### CDK-JChemPaint #7: rendering molecules as SVG

A very long time ago, Scalable Vector Graphics promised to revolutionalize images on the web. After initial cool work (including CMLSnap: animated chemical reactions by Peter's group!), things cooled down. There was simply a lack of support in browsers. Things have changed. SVG is much better supported now, and people are starting to use SVG again. Like Noel, visualizing 100 molecules in one blog post.

The new CDK-JChemPaint code has been refactored such that the original code for the core functionality is now independent from the drawing toolkit. And we have two well-developed implementations, one for Swing/AWT (used by the JChemPaint applet), and one for SWT (used by Bioclipse). And there is one that generates SVG too, written by Gileain as a proof of principle.

The code is almost identical to the code for rendering molecules as PNG. We just swap the AWTDrawVisitor for the SVGGenerator:

-renderer.paint(triazole, new AWTDrawVisitor(g2));
+svgGenerator = new SVGGenerator();
+renderer.paint(triazole, svgGenerator);


Additionally, we need to change how we output the results. The below code generate the SVG and the matching HTML snippet:

new File("triazole.svg").append(svgGenerator.getResult())

file = new PrintWriter(new FileWriter(new File("triazole.html")))
file.println("<html>");
file.println("<body>");
file.print("<embed width=\"100\" height=\"100\" src=\"triazole.svg\" />");
file.println("</body>");
file.println("<html>");
file.close()


The result looks like:

I did have to tweak the SVG generated with CDK-JChemPaint 20, so that the HTML ensures the initial scaling, by removing the width and height in the SVG (patch pending). But this output also nicely shows that there are glitches in the generated code. I hope people are interested in contributing to this part of the CDK-JChemPaint patch!

The full source code of the svgMol.groovy can be found in the Groovy JChemPaint repository.