Render a LaTeX string to PNG. Parameters ---------- s : str The raw string containing valid inline LaTeX. encode : bool, optional Should the PNG data base64 encoded to make it JSON'able. backend : {matplotlib, dvipng} Backend for producing PNG data. w
(s, encode=False, backend=None, wrap=False, color='Black',
scale=1.0)
| 57 | |
| 58 | |
| 59 | def latex_to_png(s, encode=False, backend=None, wrap=False, color='Black', |
| 60 | scale=1.0): |
| 61 | """Render a LaTeX string to PNG. |
| 62 | |
| 63 | Parameters |
| 64 | ---------- |
| 65 | s : str |
| 66 | The raw string containing valid inline LaTeX. |
| 67 | encode : bool, optional |
| 68 | Should the PNG data base64 encoded to make it JSON'able. |
| 69 | backend : {matplotlib, dvipng} |
| 70 | Backend for producing PNG data. |
| 71 | wrap : bool |
| 72 | If true, Automatically wrap `s` as a LaTeX equation. |
| 73 | color : string |
| 74 | Foreground color name among dvipsnames, e.g. 'Maroon' or on hex RGB |
| 75 | format, e.g. '#AA20FA'. |
| 76 | scale : float |
| 77 | Scale factor for the resulting PNG. |
| 78 | |
| 79 | None is returned when the backend cannot be used. |
| 80 | |
| 81 | """ |
| 82 | s = cast_unicode(s) |
| 83 | allowed_backends = LaTeXTool.instance().backends |
| 84 | if backend is None: |
| 85 | backend = allowed_backends[0] |
| 86 | if backend not in allowed_backends: |
| 87 | return None |
| 88 | if backend == 'matplotlib': |
| 89 | f = latex_to_png_mpl |
| 90 | elif backend == 'dvipng': |
| 91 | f = latex_to_png_dvipng |
| 92 | if color.startswith('#'): |
| 93 | # Convert hex RGB color to LaTeX RGB color. |
| 94 | if len(color) == 7: |
| 95 | try: |
| 96 | color = "RGB {}".format(" ".join([str(int(x, 16)) for x in |
| 97 | textwrap.wrap(color[1:], 2)])) |
| 98 | except ValueError: |
| 99 | raise ValueError('Invalid color specification {}.'.format(color)) |
| 100 | else: |
| 101 | raise ValueError('Invalid color specification {}.'.format(color)) |
| 102 | else: |
| 103 | raise ValueError('No such backend {0}'.format(backend)) |
| 104 | bin_data = f(s, wrap, color, scale) |
| 105 | if encode and bin_data: |
| 106 | bin_data = encodebytes(bin_data) |
| 107 | return bin_data |
| 108 | |
| 109 | |
| 110 | def latex_to_png_mpl(s, wrap, color='Black', scale=1.0): |
no test coverage detected