Created
March 31, 2011 03:55
-
-
Save diosmosis/895784 to your computer and use it in GitHub Desktop.
Uses inkscape to export an svg file using an optional, external CSS file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import xml.dom.minidom | |
from optparse import OptionParser | |
# usage exportsvg whatever.svg --css=abc.css --output=whatever.png | |
# uses inkscape | |
if __name__ == '__main__': | |
parser = OptionParser() | |
parser.add_option("-c", "--css", dest="css", help="CSS stylesheet to use when exporting") | |
parser.add_option("-o", "--output", dest="output", help="specify the output file to use") | |
(options, args) = parser.parse_args() | |
if len(args) < 1: | |
print '[error] input SVG must be supplied' | |
exit(1) | |
infile = args[0] | |
filetype = None | |
if options.output == None: | |
if infile.find('.') != -1: | |
infile_root = infile[0:infile.find('.')] | |
print '[note] no output file specified, outputting to %s.png' % infile_root | |
options.output = '%s.png' % infile_root | |
filetype = 'png' | |
else: | |
if options.output.find('.') == -1: | |
print '[error] cannot determine file type from \'%s\'' % options.output | |
exit(1) | |
filetype = options.output[options.output.find('.') + 1:] | |
if filetype != 'png': | |
print '[error] unknown output file type \'%s\'' % filetype | |
exit(1) | |
if options.css != None: | |
inf = open(infile, 'r') | |
dom = xml.dom.minidom.parseString(inf.read()) | |
inf.close() | |
defs = dom.getElementsByTagName('defs') | |
if len(defs) == 0: | |
defs = [dom.createElement('defs')] | |
dom.documentElement.appendChild(defs[0]) | |
style = dom.createElement('style') | |
defs[0].appendChild(style) | |
cssf = open(options.css, 'r') | |
styletxt = dom.createTextNode(cssf.read()) | |
cssf.close() | |
style.appendChild(styletxt) | |
tmpf = open('_' + infile, 'w+') | |
dom.writexml(tmpf, '', ' ', '\n') | |
tmpf.close() | |
infile = '_' + infile | |
if filetype == 'png': | |
os.system('inkscape --export-png=\'%s\' %s' % (options.output, infile)) | |
if options.css != None: | |
os.remove(infile) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment