Advertisement
faubiguy

latexpng.py

Jul 29th, 2016
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.96 KB | None | 0 0
  1. #!/usr/bin/python
  2. import os, sys, argparse, tempfile, shutil, subprocess
  3.  
  4. parser = argparse.ArgumentParser(description='Convert LaTeX equation to png image')
  5. parser.add_argument('equation', help='LaTeX equation to convert')
  6. parser.add_argument('--confirm', help='Don\'t ask about outputting to terminal')
  7.  
  8. args = parser.parse_args()
  9.  
  10. if sys.stdout.isatty() and not args.confirm:
  11.     response = input('Are you sure you want to output binary PNG data to the terminal? [y/N] ')
  12.     if not (response and response[0] in 'yY'):
  13.         sys.exit()
  14.  
  15. dvipng_args = ['-T', 'tight', '-bg', 'transparent']
  16.  
  17. for program in ('latex', 'dvipng'):
  18.     if not shutil.which(program):
  19.         sys.exit('Error: {0} not installed'.format(program))
  20.  
  21. cwd = os.getcwd()
  22.  
  23. with tempfile.TemporaryDirectory() as tempdir:
  24.     os.chdir(tempdir)
  25.     try:
  26.         with open('file.tex', 'w') as latexfile:
  27.             latexfile.write(
  28.                 "\\nonstopmode\\documentclass[12pt]{article}\n"
  29.                 "\\usepackage{amsmath}\n"
  30.                 "\\usepackage{amssymb}\n"
  31.                 "\\usepackage{cancel}\n"
  32.                 "\\pagestyle{empty}\n"
  33.                 "\\begin{document}\n$$\n"
  34.                 + args.equation +
  35.                 "\n$$\n\\end{document}\n"
  36.             )
  37.         latexprocess = subprocess.run(
  38.             ['latex', 'file.tex', '-output-directory', tempdir],
  39.             stdout=subprocess.DEVNULL)
  40.         if latexprocess.returncode != 0:
  41.             print('Error running latex', file=sys.stderr)
  42.             sys.exit()
  43.         dvipngprocess = subprocess.run(
  44.             ['dvipng', 'file.dvi'] + dvipng_args,
  45.             stdout=subprocess.DEVNULL)
  46.         if dvipngprocess.returncode != 0:
  47.             print('Error running dvipng', file=sys.stderr)
  48.             subprocess.run(['zsh'])
  49.             sys.exit()
  50.         with open('file1.png', 'rb') as pngfile:
  51.             shutil.copyfileobj(pngfile, sys.stdout.buffer)
  52.     finally:
  53.         os.chdir(cwd)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement