'Draws and outputs in PNG for ipython.
PNG is used instead of PDF, since it can be displayed in the qt console and
has wider browser support.'

def _repr_png_(self):

    import os
    import base64
    import subprocess
    import tempfile
    from nltk.draw.tree import tree_to_treesegment
    from nltk.draw.util import CanvasFrame
    from nltk.internals import find_binary
    _canvas_frame = CanvasFrame()
    widget = tree_to_treesegment(_canvas_frame.canvas(), self)
    _canvas_frame.add_widget(widget)
    (x, y, w, h) = widget.bbox()
    _canvas_frame.canvas()[u'scrollregion'] = (0, 0, w, h)
    with tempfile.NamedTemporaryFile() as file:
        in_path = u'{0:}.ps'.format(file.name)
        out_path = u'{0:}.png'.format(file.name)
        _canvas_frame.print_to_file(in_path)
        _canvas_frame.destroy_widget(widget)
        subprocess.call(([find_binary(u'gs', binary_names=[u'gswin32c.exe', u'gswin64c.exe'], env_vars=[u'PATH'], verbose=False)] + u'-q    -dEPSCrop    -sDEVICE=png16m    -r90    -dTextAlphaBits=4    -dGraphicsAlphaBits=4    -dSAFER    -dBATCH    -dNOPAUSE    -sOutputFile={0:}    {1:}'.format(out_path, in_path).split()))
        with open(out_path, u'rb') as sr:
            res = sr.read()
        os.remove(in_path)
        os.remove(out_path)
        return base64.b64encode(res).decode()
