Created
August 24, 2018 16:33
-
-
Save raddy/275fb99eb95d300c27a092edc71558eb to your computer and use it in GitHub Desktop.
Convert Latex Equations to PNG (For Medium posts)
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
| import os | |
| import subprocess | |
| import argparse | |
| import shlex | |
| FIXED = r"""\documentclass{standalone} | |
| \usepackage{xcolor} | |
| \usepackage{amsmath} | |
| \usepackage[utf8]{inputenc} | |
| \usepackage[charter]{mathdesign} | |
| \begin{document} | |
| \begin{minipage}{178pt} | |
| \begin{align*} | |
| REPLACEME | |
| \end{align*} | |
| \end{minipage} | |
| \end{document}""" | |
| CMD = r"""convert -density 1200 temp_equation.pdf | |
| -resize 1400 | |
| -gravity South -background white -splice 0x1 | |
| -background black -splice 0x1 | |
| -trim +repage -chop 0x1 | |
| -gravity North -background white -splice 0x1 | |
| -background black -splice 0x1 | |
| -trim +repage -chop 0x1 | |
| REPLACEME""" | |
| if __name__ == '__main__': | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument('equation') | |
| parser.add_argument('name') | |
| args = parser.parse_args() | |
| print("~ Equation: {}".format(args.equation)) | |
| out = FIXED.replace("REPLACEME", args.equation) | |
| with open('temp_equation.tex','w') as f: | |
| f.write(out) | |
| cmd = ['pdflatex', '-interaction', 'nonstopmode', 'temp_equation.tex'] | |
| proc = subprocess.Popen(cmd) | |
| proc.communicate() | |
| retcode = proc.returncode | |
| if not retcode == 0: | |
| os.unlink('temp_equation.pdf') | |
| raise ValueError('Error {} executing command: {}'.format(retcode, ' '.join(cmd))) | |
| os.unlink('temp_equation.tex') | |
| os.unlink('temp_equation.log') | |
| os.unlink('temp_equation.aux') | |
| magick_cmd = CMD.replace("REPLACEME", args.name) | |
| cmd = shlex.split('{}'.format(magick_cmd)) | |
| print(cmd) | |
| proc = subprocess.Popen(cmd) | |
| proc.communicate() | |
| retcode = proc.returncode | |
| if not retcode == 0: | |
| os.unlink(args.name) | |
| raise ValueError('Error {} executing command: {}'.format(retcode, ' '.join(magick_cmd))) | |
| os.unlink('temp_equation.pdf') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment