Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Printing a SymPy LaTeX expression to png e.g. for Markdown or Medium
from subprocess import run
import sympy as sp
def print_to_file(fname, expr):
# See
t_start = r"""\documentclass[border=2pt]{standalone}
t_end = r"""\end{varwidth}
with open(fname, 'w') as f:
f.write(t_start + '\n')
f.write(f'\\[ {sp.latex(expr)} \\]\n')
f.write(t_end + '\n')
froot = fname.replace('tex', '')
run('pdflatex ' + fname, shell=True, check=True)
except Exception as ex:
print(f'Error converting {fname} to pdf')
run(f'convert -density 300 {froot}pdf -quality 90 -colorspace RGB {froot}png', shell=True, check=True)
except Exception as ex:
print('Error converting to png')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment