Last active
June 2, 2018 21:38
-
-
Save ahwillia/ce9a842f122757518c65d0bd545f28c1 to your computer and use it in GitHub Desktop.
Export a sequence of LaTeX equations to individual image files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
% quad % | |
\[ x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a} \] | |
% optimization % | |
\usepackage{amsmath} | |
\begin{equation*} | |
\begin{aligned} | |
& \underset{x}{\text{minimize}} | |
& & f_0(x) \\ | |
& \text{subject to} | |
& & f_i(x) \leq b_i, \; i = 1, \ldots, m. | |
\end{aligned} | |
\end{equation*} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
import re | |
import sys | |
import tempfile | |
import subprocess | |
import os | |
def export_equations(filename,dest='./',dpi=300): | |
with open(filename,'r') as f: | |
s = f.read() | |
names = [ dest+re.sub('[\W_]','',n) for n in re.findall('%.{,}%\n',s) ] | |
eqns = re.split('%.{,}%\n',s)[1:] | |
tmp_name = '.tempfile_latex_to_png' | |
for outfile,eq in zip(names,eqns): | |
# make temporary file | |
temp = open(tmp_name+'.tex','w') | |
packages,body = [],[] | |
for eqline in eq.split('\n'): | |
if eqline.startswith('\usepackage'): | |
packages.append(eqline) | |
else: | |
body.append(eqline) | |
# write equation | |
temp.write('\documentclass[preview]{standalone}\n') | |
[ temp.write(pkg+'\n') for pkg in packages ] | |
temp.write('\\begin{document}\n') | |
temp.write('\pagestyle{empty}\n') | |
[ temp.write(line+'\n') for line in body ] | |
temp.write('\end{document}\n') | |
# compile latex | |
temp.close() | |
subprocess.call(['pdflatex','-interaction=nonstopmode',tmp_name]) | |
# crop pdf, convert to png | |
subprocess.call('pdfcrop %s.pdf %s.pdf'%(tmp_name,outfile),shell=True) | |
subprocess.call('convert -density %i %s.pdf %s.png'%(dpi,outfile,outfile),shell=True) | |
# delete all temporary files | |
subprocess.call(['rm', tmp_name+'.tex']) | |
subprocess.call(['rm', tmp_name+'.pdf']) | |
subprocess.call(['rm', tmp_name+'.log']) | |
subprocess.call(['rm', tmp_name+'.aux']) | |
if __name__=="__main__": | |
fn = 'main.tex' if len(sys.argv)<2 else sys.argv[1] | |
df = './' if len(sys.argv)<3 else sys.argv[2] | |
dpi = 300 if len(sys.argv)<4 else sys.argv[3] | |
export_equations(fn,df,dpi) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Running
$ ./scrap_latex.py
from the command line should produce two files:quad.pdf
optimization.pdf