-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtex2pic
executable file
·87 lines (72 loc) · 2.54 KB
/
tex2pic
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#!/usr/bin/env python
def tex2pic(
texequation,
outfname = None,
verbose = False,
fmt='pdf',
resolution=300):
import subprocess
import tempfile
import os
import shutil
head = r"""% latex file create by sandbox.py
\documentclass[border=1pt]{standalone}
\begin{document}
$\displaystyle
"""
foot = r"""
$
\end{document}
"""
# overwriting options if contradictions
if outfname:
fmt = os.path.splitext(outfname)[1][1:]
else:
verbose = 0
# create temporary directory and filenames
tmpdir = tempfile.mkdtemp()
tmptex = os.path.join(tmpdir,"texeq.tex")
tmppdf = os.path.join(tmpdir,"texeq.pdf")
tmpout = os.path.join(tmpdir,"texeq."+fmt)
# write the tmp texfile
with open(tmptex,'w') as f:
f.write(head)
f.write(texequation)
f.write(foot)
# compile the tex file in tmpdir
stdout = None if verbose else open(os.devnull,'w')
popen = subprocess.Popen("pdflatex -interaction=nonstopmode -pdf %s"%tmptex,
shell=True,cwd=tmpdir,stdout=stdout,stderr=stdout)
popen.wait()
if not verbose: stdout.close()
# exit if not compiled
if popen.returncode != 0:
print("Compilation failed. Run again with -v to detect errors in your formula.")
exit()
# convert in tmpdir
formats = {'jpg':'jpg','jpeg':'jpg','png':'png','tiff':'tiff','ppm':''}
if fmt in formats.keys():
convertcmd = "pdftoppm -r %d -%s %s > %s" %(resolution,formats[fmt],tmppdf,tmpout)
subprocess.check_call(convertcmd,shell=True)
# return the actual output
if outfname:
shutil.copy(tmpout,outfname)
else:
with open(tmpout,'r') as f:
print(f.read())
# remove tmp files
shutil.rmtree(tmpdir)
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('texequation')
parser.add_argument('-v','--verbose',action='count', help='print compilation output of pdflatex if output not to stdout')
parser.add_argument('-o','--output',help='the output file which will be generated')
parser.add_argument('-f','--format',default='pdf',help='format of output (if --output not set)')
parser.add_argument('-r','--resolution',default='300',type=int,help='resolution as in -r option of pdftoppm')
args = parser.parse_args()
tex2pic(args.texequation,
outfname=args.output,
verbose=args.verbose,
fmt=args.format,
resolution=args.resolution)