Hi,

I am working in an analytical chemistry environment and recently found a 
way to render structures in various vector formats. On the outset we 
wanted to deliver EPS files to the software of our NMR spectrometers for 
inclusion on spectra printout.  I found the FreeHEP java library 
containing a vector graphics package 
(http://java.freehep.org/vectorgraphics/index.html) which nicely filled 
the gap. 

After a recent question about SVG rendering I thought I send an example to 
the list. Perhaps it is useful for others as well. It reads a MOL file and 
can output EPS, PDF, SVG and PNG files.

Regards,
Ekkehard



-- vectorRender.java --

import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.StringReader;

import javax.imageio.ImageIO;

import java.awt.Image;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;

import java.util.Properties;

import org.freehep.graphics2d.VectorGraphics;
import org.freehep.graphicsio.ps.PSGraphics2D;
import org.freehep.graphicsio.pdf.PDFGraphics2D;
import org.freehep.graphicsio.svg.SVGGraphics2D;


import org.openscience.cdk.Molecule;
import org.openscience.cdk.aromaticity.HueckelAromaticityDetector;
import org.openscience.cdk.geometry.GeometryTools;
import org.openscience.cdk.io.MDLReader;
import org.openscience.cdk.renderer.Renderer2D;
import org.openscience.cdk.renderer.Renderer2DModel;
import org.openscience.cdk.tools.HydrogenAdder;


/*
 *   @author Ekkehard Goerlach
 */

public class vectorRender {

    public static class ChemRenderer {

        private int vRenderSizeX = 600;
        private int vRenderSizeY = 400;
        private int vFontSize    = 26;
 
        /*
         * Creates a structure image based on a MOL string. The image 
rendering is
         * done with CDK.
         */
        public final java.awt.Image getImage4MOL(String molfile) throws 
Exception {

            // creates CDK Molecule object and get the renderer
            Molecule   mol      = prepareMolecule(molfile);
            Renderer2D renderer = prepareRenderer(mol);

            BufferedImage bimage = null;
            try {

                // paint molecule to java.awt.BufferedImage
                bimage = new BufferedImage(vRenderSizeX, vRenderSizeY,
 BufferedImage.TYPE_BYTE_INDEXED);
                Graphics2D g = bimage.createGraphics();
                g.setBackground(Color.WHITE);
                g.setColor(Color.WHITE);
                g.fillRect(0, 0, vRenderSizeX, vRenderSizeY);
                renderer.paintMolecule(mol, g, false, true);

            } catch (Exception e) {
                e.printStackTrace();
                throw new Exception("Rendering of structure(s) failed");
            }

            return bimage;
        }

        /*
         * Creates a structure EPS based on a MOL string
         */
        public final void writeMOL2PNGFile(String MOLString, File pngFile) 
throws Exception {

            BufferedImage bimage = null;
 
            try {
                bimage = (BufferedImage) getImage4MOL(MOLString);
                ImageIO.write(bimage, "png", pngFile);
 
            } catch (Exception e) {
                e.printStackTrace();
                throw new Exception("EPS rendering of structure(s) 
failed");
            }

        }

        /*
         * Creates a structure EPS based on a MOL string
         */
        public final void writeMOL2EPSFile(String MOLString, File epsFile) 
throws Exception {

            // creates CDK Molecule object and get the renderer
            Molecule   mol      = prepareMolecule(MOLString);
            Renderer2D renderer = prepareRenderer(mol);

            try {

                // paint molecule to java.awt.BufferedImage
                VectorGraphics vg = new PSGraphics2D(epsFile, new 
Dimension(vRenderSizeX, vRenderSizeY)); 

                Properties p = new Properties();
                p.setProperty("PageSize","A5");
                vg.setProperties(p);
                vg.startExport();
                renderer.paintMolecule(mol, vg, false, true);
                vg.endExport();
            } catch (Exception e) {
                e.printStackTrace();
                throw new Exception("EPS rendering of structure(s) 
failed");
            }

        }


        /*
         * Creates a structure PDF based on a MOL string
         */
        public final void writeMOL2PDFFile(String MOLString, File epsFile) 
throws Exception {

            // creates CDK Molecule object and get the renderer
            Molecule   mol      = prepareMolecule(MOLString);
            Renderer2D renderer = prepareRenderer(mol);

            try {

                // paint molecule to java.awt.BufferedImage
                VectorGraphics vg = new PDFGraphics2D(epsFile, new 
Dimension(vRenderSizeX, vRenderSizeY)); 

                Properties p = new Properties();
                p.setProperty("PageSize","A5");
                vg.setProperties(p);
                vg.startExport();
                renderer.paintMolecule(mol, vg, false, true);
                vg.endExport();
            } catch (Exception e) {
                e.printStackTrace();
                throw new Exception("PDF rendering of structure(s) 
failed");
            }

        }



        /*
         * Creates a structure SVG based on a MOL string
         */
        public final void writeMOL2SVGFile(String MOLString, File epsFile) 
throws Exception {

            // creates CDK Molecule object and get the renderer
            Molecule   mol      = prepareMolecule(MOLString);
            Renderer2D renderer = prepareRenderer(mol);

            try {

                // paint molecule to java.awt.BufferedImage
                VectorGraphics vg = new SVGGraphics2D(epsFile, new 
Dimension(vRenderSizeX, vRenderSizeY)); 

                Properties p = new Properties();
                p.setProperty("PageSize","A5");
                vg.setProperties(p);
                vg.startExport();
                renderer.paintMolecule(mol, vg, false, true);
                vg.endExport();
            } catch (Exception e) {
                e.printStackTrace();
                throw new Exception("SVG rendering of structure(s) 
failed");
            }

        }


        private org.openscience.cdk.renderer.Renderer2D 
prepareRenderer(Molecule mol) 
            throws Exception {

            Renderer2DModel r2dm;
            Renderer2D renderer;
            Dimension imgSize;

            try {
                r2dm     = new Renderer2DModel();
                renderer = new Renderer2D(r2dm);
                imgSize  = new Dimension(vRenderSizeX, vRenderSizeY); // 
1200,900
                // create renderer to render MOLString into an 
java.awt.Image
                // renders 2D structures
                r2dm.setBackgroundDimension(imgSize);
                r2dm.setBackColor(Color.WHITE);
                r2dm.setDrawNumbers(false);
                r2dm.setUseAntiAliasing(true);
                r2dm.setColorAtomsByType(false);
                r2dm.setShowImplicitHydrogens(true);
                r2dm.setShowReactionBoxes(false);
                r2dm.setKekuleStructure(false);
                r2dm.setShowAromaticityInCDKStyle(true);
                r2dm.setBondWidth(3);
                r2dm.setFont(new java.awt.Font("SansSerif", 
java.awt.Font.PLAIN, vFontSize));

                // scale and center molecule on image
                GeometryTools.translateAllPositive(mol, 
r2dm.getRenderingCoordinates());
                GeometryTools.scaleMolecule(mol, imgSize, 1.0, r2dm
                                            .getRenderingCoordinates());
                GeometryTools.center(mol, imgSize, 
r2dm.getRenderingCoordinates());

            } catch (Exception e) {
                e.printStackTrace();
                throw new Exception("Creation of renderer failed");
            }

            return renderer;
        }


        private org.openscience.cdk.Molecule prepareMolecule(String 
MOLString) throws Exception
        {

            // creates CDK Molecule object
            Molecule     mol    = null;
            try {

                // reads MOL file
                MDLReader mdlr = new MDLReader(new 
StringReader(MOLString));
                mol = (Molecule) mdlr.read(new Molecule());

                // adds implicit H atoms to molecule
                HydrogenAdder ha = new HydrogenAdder();
                ha.addImplicitHydrogensToSatisfyValency(mol);

                // detects aromaticity; used to display aromatic ring 
systems correctly
                HueckelAromaticityDetector.detectAromaticity(mol);

            } catch (Exception e) {
                e.printStackTrace();
                throw new Exception("Rendering of structure(s) failed");
            }

            return mol;
        }

    }



    public static final void main(final String[] args) {


        String mf;
        String molfile;

        try {
            BufferedReader reader = new BufferedReader(new 
FileReader("renderTest.mol"));
            StringBuffer   sbuff  = new StringBuffer();
            String         line;

            while ( (line = reader.readLine()) != null ) {
                sbuff.append(line + "\n");
            }
            reader.close();
            molfile = sbuff.toString();
            System.out.println(molfile);

            ChemRenderer crender = new ChemRenderer();

            crender.writeMOL2SVGFile(molfile,new File("Output.svg"));

        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage() + ".");
            e.printStackTrace();
        }

    }


}
_________________________

CONFIDENTIALITY NOTICE

The information contained in this e-mail message is intended only for the 
exclusive use of the individual or entity named above and may contain 
information that is privileged, confidential or exempt from disclosure 
under applicable law. If the reader of this message is not the intended 
recipient, or the employee or agent responsible for delivery of the 
message to the intended recipient, you are hereby notified that any 
dissemination, distribution or copying of this communication is strictly 
prohibited. If you have received this communication in error, please 
notify the sender immediately by e-mail and delete the material from any 
computer.  Thank you.
-------------------------------------------------------------------------
This SF.net email is sponsored by: Microsoft
Defy all challenges. Microsoft(R) Visual Studio 2008.
http://clk.atdmt.com/MRT/go/vse0120000070mrt/direct/01/
_______________________________________________
Cdk-user mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/cdk-user

Reply via email to