| 109 | |
| 110 | |
| 111 | def latex_to_png_mpl(s, wrap, color='Black', scale=1.0): |
| 112 | try: |
| 113 | from matplotlib import figure, font_manager, mathtext |
| 114 | from matplotlib.backends import backend_agg |
| 115 | from pyparsing import ParseFatalException |
| 116 | except ImportError: |
| 117 | return None |
| 118 | |
| 119 | # mpl mathtext doesn't support display math, force inline |
| 120 | s = s.replace('$$', '$') |
| 121 | if wrap: |
| 122 | s = u'${0}$'.format(s) |
| 123 | |
| 124 | try: |
| 125 | prop = font_manager.FontProperties(size=12) |
| 126 | dpi = 120 * scale |
| 127 | buffer = BytesIO() |
| 128 | |
| 129 | # Adapted from mathtext.math_to_image |
| 130 | parser = mathtext.MathTextParser("path") |
| 131 | width, height, depth, _, _ = parser.parse(s, dpi=72, prop=prop) |
| 132 | fig = figure.Figure(figsize=(width / 72, height / 72)) |
| 133 | fig.text(0, depth / height, s, fontproperties=prop, color=color) |
| 134 | backend_agg.FigureCanvasAgg(fig) |
| 135 | fig.savefig(buffer, dpi=dpi, format="png", transparent=True) |
| 136 | return buffer.getvalue() |
| 137 | except (ValueError, RuntimeError, ParseFatalException): |
| 138 | return None |
| 139 | |
| 140 | |
| 141 | def latex_to_png_dvipng(s, wrap, color='Black', scale=1.0): |