Generating 2D SVG Images of MOL Files using RDKit Transparent Background
By Güngör Budak
- 2 minutes read - 219 wordsThe latest release of RDKit (2015-03) can generate SVG images with several lines of codes but by default the generated SVG image has a white background. The investigations on sources didn’t solve my problem as I couldn’t find any option for setting background to transparent background.
An example of SVG image generation can be found on RDKit blog post called New Drawing Code.
In [3] shows the SVG image generation and it returns the SVG file content in XML. When you open this file in a text editor, you’ll see there is a rect element with a style attribute having fill #ffffff
which is white. If you make this none, the whole SVG background becomes transparent.
So, if you obtain the SVG file content as XML from using moltosvg function in the blog post, just use the following function to make its background transparent.
1import xml.etree.ElementTree as ET
2
3
4def transparentsvg(svg):
5 # Make the white background transparent
6 tree = ET.fromstring(svg)
7 rect = tree.find('rect')
8 rect.set('style', rect.get('style').replace('#ffffff', 'none'))
9 # Recover some missing attributes for correct browser rendering
10 tree.set('version', '1.1')
11 tree.set('xmlns', 'http://www.w3.org/2000/svg')
12 tree.set('xmlns:rdkit', 'http://www.rdkit.org/xml')
13 tree.set('xmlns:xlink', 'http://www.w3.org/1999/xlink')
14 return '<?xml version="1.0" encoding="UTF-8"?>' + ET.tostring(tree).strip()
You can write this to an SVG file easily;
1svg = transparentsvg(svg)
2with open('path/to/svg/file', 'w') as f:
3 f.write(svg)