Created
January 24, 2021 15:41
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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