Skip to content

Instantly share code, notes, and snippets.

Embed
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 https://tex.stackexchange.com/questions/34054/tex-to-image-over-command-line/34058#34058
t_start = r"""\documentclass[border=2pt]{standalone}
\usepackage{amsmath}
\usepackage{varwidth}
\begin{document}
\begin{varwidth}{\linewidth}"""
t_end = r"""\end{varwidth}
\end{document}"""
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', '')
try:
run('pdflatex ' + fname, shell=True, check=True)
except Exception as ex:
print(f'Error converting {fname} to pdf')
try:
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