Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1""" 

2@file 

3@brief Convert a short latex script into an image 

4""" 

5import os 

6import shutil 

7import sys 

8from PIL import Image 

9from pyquickhelper.loghelper import run_cmd 

10 

11 

12def convert_short_latex_into_png(latex, temp_folder=".", fLOG=print, 

13 miktex=r"C:\Program Files\MiKTeX 2.9\miktex\bin\x64", 

14 final_name=None): 

15 """ 

16 Convert a short latex script into an image. 

17 

18 @param latex latex equation 

19 @param temp_folder temp_folder (where temporary files will be placed) 

20 @param fLOG logging function 

21 @param miktex miktex location 

22 @param final_name if not None, copy the image at this location using this name 

23 @return a location to the image (it should be copied), and its size 

24 

25 You should not call the function twice at the same in the same folder. 

26 

27 @warning The function ends the program if there was a failure. Something is missing on the command line. 

28 """ 

29 if not os.path.exists(miktex): 

30 raise FileNotFoundError("unable to find miktex") 

31 

32 if sys.platform.startswith("win"): 

33 htlatex = os.path.join(miktex, "htlatex.exe") 

34 if not os.path.exists(htlatex): 

35 raise FileNotFoundError("unable to find htlatex") 

36 else: 

37 htlatex = os.path.join(miktex, "htlatex") 

38 

39 if not os.path.exists(temp_folder): 

40 os.makedirs(temp_folder) 

41 

42 eq = os.path.join(temp_folder, "eq.tex") 

43 with open(eq, "w") as f: 

44 f.write(r"""\documentclass[12pt]{article} 

45 \pagestyle{empty} 

46 \begin{document} 

47 $$ 

48 %s 

49 $$ 

50 \end{document}""".replace(" ", "") % latex.strip("\n\r ")) 

51 

52 cmd = '"' + htlatex + '" eq.tex "html, graphics-300" "" "" "--interaction=nonstopmode"' 

53 cwd = os.getcwd() 

54 os.chdir(temp_folder) 

55 out, err = run_cmd(cmd, wait=True) 

56 os.chdir(cwd) 

57 

58 if "FAILED" in err: 

59 raise Exception( 

60 "it failed\n-----\n{0}\n----------\n{1}".format(out, err)) 

61 img = os.path.join(temp_folder, "eq0x.png") 

62 if not os.path.exists(img): 

63 with open(os.path.join(temp_folder, "eq.log"), "r") as f: 

64 log = f.read() 

65 raise FileNotFoundError("the compilation did not work\n" + log) 

66 

67 if final_name is not None: 

68 # size reduction 

69 im = Image.open(img) 

70 shutil.copy(img, final_name) 

71 return final_name, im.size 

72 else: 

73 im = Image.open(img) 

74 return img, im.size