from sympy import preview from io import BytesIO import cairosvg, time, os def get_png(tex): buf = BytesIO() preview(tex, output = "svg", viewer = "BytesIO", outputbuffer = buf) buf.seek(0) fname = "/tmp/{}".format(time.time()) cairosvg.svg2png(bytestring=buf.read(), parent_widht=500, parent_height=500, write_to=fname) buf.seek(0) with open(fname, "rb") as fin: buf.write(fin.read()) with open(fname, "rb") as fin: with open("test.png", "wb") as fout: fout.write(fin.read()) os.unlink(fname) buf.seek(0) return buf