LaTeX and Python
Recently, I’ve been working a project that needs some report generation. I decided to have Python write to a LaTeX file and then let LaTeX handle all of the formatting goodness — like it does so well — of making a PDF.
To do this, I have a template TEX file will all of the necessary preamble. Whenever a script needs to generate a report, it copies the template like so:
shutil.copy(template_location, report_location)
Then, I write all of the text I need (from a list of line) like so (example of placing a subsection title included here).
with open( report_location , 'a') as report: report.writelines("\n\\subsubsection*{"+section_name_variable+"}") report.writelines("%s\n" % line for line in lines_to_write)
If I want to include a figure, that does get a little more complicated, so I wrote a function for preparing the lines for a figure (which could then be the “lines to write” in the last snippet.
def prepare_figure_lines(caption, path_to_graphic): lines = ['\\begin{figure}[H]' , '\\centering' , '\\includegraphics[width=\\textwidth]{'+outpath+'}' , '\\caption{\\label{fig} '+ caption + '}' , '\\end{figure}' ] return lines
And when you’ve gotten everything in your latex file, you have to end the document like this.
with open(report_location, 'a') as report: report.writelines("\n \\end{document}")