Coverage for src/ensae_teaching_cs/homeblog/latex2html.py: 17%
36 statements
« prev ^ index » next coverage.py v7.1.0, created at 2023-04-28 06:23 +0200
« prev ^ index » next coverage.py v7.1.0, created at 2023-04-28 06:23 +0200
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
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.
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
25 You should not call the function twice at the same in the same folder.
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")
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")
39 if not os.path.exists(temp_folder):
40 os.makedirs(temp_folder)
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 "))
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)
58 if "FAILED" in err:
59 raise RuntimeError(
60 f"it failed\n-----\n{out}\n----------\n{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)
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