Skip to content

Instantly share code, notes, and snippets.

@mattmcd
Created January 24, 2021 15:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattmcd/6f167bd73e4691e830e5319505894ca2 to your computer and use it in GitHub Desktop.
Save mattmcd/6f167bd73e4691e830e5319505894ca2 to your computer and use it in GitHub Desktop.
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