from IPython.display import display,SVG,Javascript def create_svg(text, name1="mySVG", tname='myText', rname='myRect'): """ Create an SVG and assign names to the components. """ svg = SVG(""" %s """ % (name1,tname,text,rname,9*len(text))) return svg create_svg('Exercise caution when entering the building') %%javascript var mytext = document.getElementById('myText'); var bb1 = mytext.getBBox(); var myrect = document.getElementById('myRect'); var bb2 = myrect.getBBox(); myrect.setAttribute('width',bb1.width); myrect.setAttribute('height',bb1.height); %%javascript var kernel = IPython.notebook.kernel; var mySVG = document.getElementById('mySVG'); var s = new XMLSerializer() var pp = s.serializeToString(mySVG); var command = 'svgs = """' + pp + '"""' kernel.execute(command); SVG(data=svgs) print svgs # output the saved SVG to a file. outf = open('sample.svg','w') outf.write(svgs); outf.close() def move_rectangle(tname, rname): ''' Change the height and width of the surrounding rectangle to match those of the text box. ''' return Javascript(''' var mytext = document.getElementById("%s"); var bb1 = mytext.getBBox(); var myrect = document.getElementById("%s"); var bb2 = myrect.getBBox(); myrect.setAttribute('width',bb1.width); myrect.setAttribute('height',bb1.height); ''' % (tname,rname)) svg = create_svg('An infinite number of screaming monkeys.') display(svg) svg = create_svg('An infinite number of screaming monkeys.',name1='bazonka',tname='xya',rname='abd') display(svg) move_rectangle('xya','abd') print svg.data # output the saved SVG to a file. outf = open('before.svg','w') outf.write(svg.data); outf.close() def recover_svg(name): """ obtain the string value of an SVG with a particular ID. """ display(Javascript(''' var kernel = IPython.notebook.kernel; var mySVG = document.getElementById('%s'); var s = new XMLSerializer() var pp = s.serializeToString(mySVG); var command = 'svgs = """' + pp + '"""' kernel.execute(command);''' % (name,))) return svgs svgs = recover_svg('bazonka') # output the saved SVG to a file. outf = open('after.svg','w') outf.write(svgs); outf.close() print svgs SVG(svgs)