-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtex4ht.py
73 lines (62 loc) · 1.8 KB
/
tex4ht.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import pathlib
import sys
import tempfile
import re
import subprocess
import shutil
import css_inline
if len(sys.argv) < 3:
print("Usage: tex4ht.py [in_file] [template_file] [out_file]")
exit(1)
in_file = pathlib.Path(sys.argv[1])
template_file = pathlib.Path(sys.argv[2])
out_file = pathlib.Path(sys.argv[3])
if out_file.exists():
exit(0)
with tempfile.TemporaryDirectory(prefix="tex4ht") as work_dir:
work_dir = pathlib.Path(work_dir)
with in_file.open() as f:
input_tex = f.read()
with template_file.open() as f:
template_str = f.read()
template_str = re.sub(r"\${{\s*\.Equation\s*}}\$", "[[REPLACE]]", template_str)
template_str = template_str.replace("[[REPLACE]]", input_tex)
template_str = template_str.replace(r"\strut{}", "")
with (work_dir / "in.tex").open("w") as f:
f.write(template_str)
with (work_dir / "conf.cfg").open("w") as f:
f.write(r"""\Preamble{xhtml}
\Configure{Gin-dim}{}
\Css{img {
max-width: 100\%;
height: auto;
}}
\begin{document}
\EndPreamble
""")
subprocess.run(
[
"/sbin/docker",
"run",
"--rm",
"-v",
f"{work_dir}:/workdir",
"danteev/texlive",
"/usr/bin/make4ht",
"-x",
"-c",
"conf",
"in.tex",
"mathml",
],
check=True,
cwd=work_dir,
)
html_file = work_dir / "in.html"
inliner = css_inline.CSSInliner(base_url="file://" + str(html_file.absolute()))
with html_file.open() as f:
inlined = inliner.inline(f.read())
inlined = re.sub(r'class="[^"]*"', "", inlined)
m = re.search(r"<body[^>]*>(.*)</body>", inlined, re.DOTALL)
with out_file.open("w") as f:
f.write(m.group(1).strip())