Saving and Organizing Multiple .svg Files to Multi-Paged PDF, PNG, or Other Common Image File Types in Python

735 views Asked by At

Goal: I want to be able to organize many SVG images of Lewis/Kekulé structures into a coherent list of reactions displayed in some common viewing file, like PDF or PNG; that is, each reaction might take up one line with the reactants and products separated by an arrow or some other divider, and there would exist as many lines on as many pages of a PDF as was needed to display each reaction in a given database.

Context: I am reading canonical SMILES representations of molecules from my local machine with pybel.readstring(), converting that string to an SVG string with molSVG = mol._repr_svg_(), then displaying the results on a jupyter notebook with display(SVG(molSVG)) while also saving the SVG string into a list and an .svg file. For example:

import pybel as pb
from IPython.display import display, SVG

molecules = []

# Read in canonical SMILES to some tractable object.
mol = pb.readstring('smi', '[O-][C]([C]1[CH][CH][CH][O]1)[O]')

# Convert it to an SVG string
molSVG = mol._repr_svg_()

# Display the SVG.
display(SVG(molSVG))

# Save the SVG to an .svg file and a list
with open('out.svg', 'w+') as result:
    result.write(molSVG)
molecules.append(result)

What I would like to do instead of displaying these is to save them to some singular image file.

Attempted Solutions: I've run through quite a few over the last six or seven weeks, so I've forgotten some, but I tried pybel's Outfile class, but I don't think that produced any images whatsoever as it was probably made to solely store OBAtom and OBMol class objects. Matplotlib's PdfPages from matplotlib.backends.backend_pdf seemed like a first step just to getting more than one SVG into a single file, but I think that failed because it requires plots as input, not SVG files. I've also seen modules like svgwrite and the like but haven't been able to get them to work.

As an example, a page of the finished product might have a similar structure to this albeit without some of the flourishes like the lines in between and labels on the arrows.

Also, just a note: I'm extremely inexperienced with all forms of coding and especially with Python, so please keep it as simple as possible for me. Any suggestions are greatly appreciated!

0

There are 0 answers