Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save anemochore/a5782d7111d4b40e41d1886d72bbeba9 to your computer and use it in GitHub Desktop.
Save anemochore/a5782d7111d4b40e41d1886d72bbeba9 to your computer and use it in GitHub Desktop.
py script that converts a txt file containing a tex per line to multiple pdf files
import subprocess
import os
# sample of input_file:
# $\mathbf{x}\in \mathbb{R}^d$
# $x_i\in \mathbb{R}$
# $D=\{\mathbf{x}^{(1)},\mathbf{x}^{(2)},\ldots, \mathbf{x}^{(N)}\}$
# ...
# consts
input_file = 'inlines_e.txt'
fontsize = '12pt'
engine = 'pdflatex'
delete_aux = True
delete_log = True
delete_tex = True
# additional macros if needed
input_preamble = '\\input{macros.tex} \n' if os.path.isfile('macros.tex') else ''
# from LaTeX2InD (https://gomezrj.github.io/projects.html)
tex_preamble = "\\documentclass[varwidth=true,border={1pt 1pt 1pt 2pt}]{standalone} \n\\usepackage{amsmath,amssymb,amsfonts} \n\\usepackage[fontsize="+fontsize+"]{fontsize} \n" +input_preamble+ "\\pagestyle{empty} \n \\begin{document} \n"
tex_closing = "\n \\end{document}"
# Open and read the lines from the text file and ...
number = 0
with open(input_file, 'r') as file:
for tex_command in file:
if tex_command.strip():
number = number + 1
temp_tex_filename = str(number)+'.tex'
if not(os.path.isfile(temp_tex_filename)):
with open(temp_tex_filename, 'w') as temp_file:
temp_file.write(tex_preamble + tex_command + tex_closing)
temp_pdf_filename = str(number)+'.pdf'
if not(os.path.isfile(temp_pdf_filename)):
pdflatex_command = [engine, temp_tex_filename]
subprocess.run(pdflatex_command)
if delete_tex: os.remove(temp_tex_filename)
if delete_log: os.remove(str(number)+'.log')
if delete_aux: os.remove(str(number)+'.aux')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment