Skip to content

Instantly share code, notes, and snippets.

@sergei-mironov
Created September 3, 2021 14:48
Show Gist options
  • Save sergei-mironov/13ba26a5d7cc51a39f8619bf382fba3d to your computer and use it in GitHub Desktop.
Save sergei-mironov/13ba26a5d7cc51a39f8619bf382fba3d to your computer and use it in GitHub Desktop.
latex2pdf
def latex2pdf(expr:str,
out_pdf:Filepath,
font:str='normalsize',
font_white:bool=False,
texname:str='latex'
)->None:
makedirs('_tex',exist_ok=True)
tex=f'_tex/{texname}.tex'
pdf=f'_tex/{texname}.pdf'
with open(tex, 'w') as f:
f.write(('\\documentclass{standalone}\n'
'\\usepackage{varwidth}\n\\usepackage{amsmath}\n'
'\\usepackage{xcolor}\n' +
('\\color[rgb]{0.77,0.77,0.77}\n' if font_white else '') +
'\\begin{document}\n'
'\\begin{varwidth}{\\linewidth}\n'
'\\strut{\\'+font+'{\n$$\n'+expr.strip()+'\n$$\n}}\n'
'\\end{varwidth}\n\\end{document}'))
with open('_tex/latex2pnf_stdout_stderr.txt','w') as f:
ret=call(['pdflatex', f'{texname}.tex'],cwd='_tex', stdout=f, stderr=f)
assert ret==0, f"pdflatex returned {ret}"
ret=call(['mv', pdf, out_pdf])
assert ret==0, f"cp returned {ret}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment