Generating pdf-latex with python script
You can start by defining the template tex file as a string:
content = r'''\documentclass{article}
\begin{document}
...
\textbf{\huge %(school)s \\}
\vspace{1cm}
\textbf{\Large %(title)s \\}
...
\end{document}
'''
Next, use argparse
to accept values for the course, title, name and school: parser = argparse.ArgumentParser()
parser.add_argument('-c', '--course')
parser.add_argument('-t', '--title')
parser.add_argument('-n', '--name',)
parser.add_argument('-s', '--school', default='My U')
A bit of string formatting is all it takes to stick the args into content
:args = parser.parse_args()
content%args.__dict__
After writing the content out to a file, cover.tex, with open('cover.tex','w') as f:
f.write(content%args.__dict__)
you could use subprocess
to call pdflatex cover.tex
.proc = subprocess.Popen(['pdflatex', 'cover.tex'])
proc.communicate()
You could add an lpr
command here too to add printing to the workflow.Remove unneeded files:
os.unlink('cover.tex')
os.unlink('cover.log')
The script could then be called like this:make_cover.py -c "Hardest Class Ever" -t "Theoretical Theory" -n Me
Putting it all together,
import argparse
import os
import subprocess
content = r'''\documentclass{article}
\begin{document}
... P \& B
\textbf{\huge %(school)s \\}
\vspace{1cm}
\textbf{\Large %(title)s \\}
...
\end{document}
'''
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--course')
parser.add_argument('-t', '--title')
parser.add_argument('-n', '--name',)
parser.add_argument('-s', '--school', default='My U')
args = parser.parse_args()
with open('cover.tex','w') as f:
f.write(content%args.__dict__)
cmd = ['pdflatex', '-interaction', 'nonstopmode', 'cover.tex']
proc = subprocess.Popen(cmd)
proc.communicate()
retcode = proc.returncode
if not retcode == 0:
os.unlink('cover.pdf')
raise ValueError('Error {} executing command: {}'.format(retcode, ' '.join(cmd)))
os.unlink('cover.tex')
os.unlink('cover.log')
Pdf-latex with python script, custom python variables into latex output
As explained in this video, I think a better approach would be to export the variables from Python and save them into a .dat
file using the following function.
def save_var_latex(key, value):
import csv
import os
dict_var = {}
file_path = os.path.join(os.getcwd(), "mydata.dat")
try:
with open(file_path, newline="") as file:
reader = csv.reader(file)
for row in reader:
dict_var[row[0]] = row[1]
except FileNotFoundError:
pass
dict_var[key] = value
with open(file_path, "w") as f:
for key in dict_var.keys():
f.write(f"{key},{dict_var[key]}\n")
Then you can call the above function and save all the variables into mydata.dat
. For example, in Python, you could save a variable and call it document_version
using the following line of code:save_var_latex("document_version", 21)
In LaTeX (in the preamble of your main file), you just have to import the following packages:
% package to open file containing variables
\usepackage{datatool, filecontents}
\DTLsetseparator{,}% Set the separator between the columns.
% import data
\DTLloaddb[noheader, keys={thekey,thevalue}]{mydata}{../mydata.dat}
% Loads mydata.dat with column headers 'thekey' and 'thevalue'
\newcommand{\var}[1]{\DTLfetch{mydata}{thekey}{#1}{thevalue}}
Then in the body of your document just use the \var{}
command to import the variable, as follows:This is document version: \var{document_version}
Compile Latex file using a python script
Try this out.
import os
os.system("pdflatex mylatex.tex")
Compile Latex document by python
You need to actually run some kind of command that makes the pdf. In my case I
might use pdflatex
, although you should know that compiling LaTeX isn't always
as easy as running latex once.
import subprocess
with open("filename.tex", "w") as tex_file:
tex_file.write(r"""
\documentclass{article}
\begin{document}
Hello World
\end{document}
""")
subprocess.call(["pdflatex", "filename.tex"])
Related Topics
Django/Python Beginner: Error When Executing Python Manage.Py Syncdb - Psycopg2 Not Found
Recursive List Comprehension in Python
Rotating a Two-Dimensional Array in Python
How May I Override the Compiler (Gcc) Flags That Setup.Py Uses by Default
Filling a Queue and Managing Multiprocessing in Python
How to Extract a Subset of a Colormap as a New Colormap in Matplotlib
Selenium Using Python: Enter/Provide Http Proxy Password for Firefox
Django: How to Manage Development and Production Settings
How to Find the Min/Max Value of a Common Key in a List of Dicts
Continuing in Python's Unittest When an Assertion Fails
Append Dataframe to Excel with Pandas
Why How to Not Create a Wheel in Python
Memoization Library for Python 2.7
Regex for Existence of Some Words Whose Order Doesn't Matter