Guest User

Untitled

a guest
Feb 24th, 2018
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.25 KB | None | 0 0
  1. import os
  2. import os.path as op
  3. from pathlib import Path
  4. import shutil
  5. import subprocess
  6. import tempfile
  7.  
  8. from IPython.lib.latextools import genelatex
  9.  
  10.  
  11. def latex_to_image(latex, eps_path):
  12. eps_path = op.realpath(eps_path)
  13. with tempfile.TemporaryDirectory() as tmpdir:
  14. tmpfile = os.path.join(tmpdir, "tmp.tex")
  15. dvifile = os.path.join(tmpdir, "tmp.dvi")
  16. psfile = os.path.join(tmpdir, "tmp.ps")
  17. pdffile = os.path.join(tmpdir, "tmp.pdf")
  18. epsfile = os.path.join(tmpdir, "tmp.eps")
  19. pngfile = os.path.join(tmpdir, "tmp.png")
  20.  
  21. contents = list(genelatex(latex, False))
  22. with open(tmpfile, "w") as f:
  23. f.writelines(contents)
  24.  
  25. with open(os.devnull, 'w') as devnull:
  26. try:
  27. subprocess.check_call(
  28. ["latex", "-halt-on-error", tmpfile], cwd=tmpdir,
  29. stdout=devnull, stderr=devnull)
  30. except Exception as e:
  31. print("************")
  32. print(len(contents))
  33. print('\n'.join(contents))
  34. raise(e)
  35.  
  36. subprocess.check_call(
  37. ["dvips", dvifile, "-o", psfile], cwd=tmpdir,
  38. stdout=devnull, stderr=devnull)
  39.  
  40. subprocess.check_call(
  41. ["gs",
  42. "-o",
  43. pdffile,
  44. "-dNoOutputFonts",
  45. "-sDEVICE=pdfwrite",
  46. "-dEPSCrop",
  47. psfile,
  48. ], cwd=tmpdir,
  49. stdout=devnull, stderr=devnull)
  50.  
  51. subprocess.check_call(
  52. ["pdf2ps", pdffile], cwd=tmpdir,
  53. stdout=devnull, stderr=devnull)
  54.  
  55. subprocess.check_call(
  56. ["ps2eps", psfile], cwd=tmpdir,
  57. stdout=devnull, stderr=devnull)
  58.  
  59. subprocess.check_call(
  60. ["dvipng", "-T", "tight", "-x", "6000", "-z", "9",
  61. "-bg", "transparent", "-o", pngfile, dvifile], cwd=tmpdir,
  62. stdout=devnull, stderr=devnull)
  63.  
  64. shutil.copy(epsfile, eps_path)
  65. shutil.copy(pngfile, Path(eps_path).with_suffix('.png'))
  66.  
  67.  
  68. if __name__ == '__main__':
  69. latex_to_image(r'$$\sum_{n=1}^{+\infty} \frac{1}{n^2} = \frac{\pi^2}{6}$$',
  70. 'zeta2.eps')
Add Comment
Please, Sign In to add comment