# How can I use LaTeX from Python.

I need to generate documents from a web application and would like to do this using the Python language and LaTeX, are there any tools that will help me?

Edit
This Application will be hosted on Linux, we can run any external commands using popen, there is currently no defined input document format, nor any storage format, but output to the end user should be PDF.

Edit 2
These documents will have complex tables, graphs, and require typeset equations - hence the reason to use LaTeX. We would also prefer not to use intermediate files such as xml->html->pdf

Ideally I would like something like pyTeX or plasTeX that could render directly to PDF.

• Could you be a bit more specific about your requirements? In particular, what format will the documents be written in? What format would you like the output to be? Can you call external commands from your web application? Aug 3, 2010 at 12:31
• (responding to edit): So can you say: input format should be LaTeX and then call pdflatex on the documents; somewhat in the spirit of what the arXiv does? Aug 3, 2010 at 12:58
• I would only go for LaTeX if you want more text (or math) than graphics. I say that, having done custom PDF output (tables, images, some text) for a desktop application. Aug 3, 2010 at 15:24
• Do you really want python to do the conversion? What are the disadvantages, in your view, of simply calling pdflatex as an external command? Aug 6, 2010 at 12:25
• If LaTeX and python are not strict requirements, you can look at ConTeXt lua documents which allows you to write directly compile lua programs to pdf (using luatex and the ConTeXt format). Jun 27, 2011 at 22:24

Recently I've written a library exactly for this purpose. It supports tables, plots, matrices and more. https://github.com/JelteF/PyLaTeX

This question should be closed because it actually has nothing to do with LaTeX and is more suited for StackOverflow. In any case the answer is that just like with HTML the best way is to use a templating system like Jinja2 and just output a LaTeX file. Once you have a LaTeX file simply use the subprocess module to run pdflatex (obviously you need it installed on your server). Don't forget to use the "-interaction nonstopmode" flag. I could go into technical details but again it's really more suited for a different site.

• I appreciate why you think that. But as a third party observer, I can tell you that I just searched for python and latex and found this. I was happy about that! Jul 3, 2012 at 19:53
• I think this is perfectly suited to the Tex stack. Sep 16, 2013 at 20:54
• Great answer, I would just add a note that some chars should be escaped. Sep 12, 2014 at 6:07
• I think the question is well suited here.
– vy32
Sep 13, 2018 at 11:08
• " I could go into technical details but again it's really more suited for a different site." There is not enough space contained on this TeX answer to give a full proof. Dec 5, 2020 at 17:15

PyTeX is an Open Source project allowing to use TeX from within Python.

• A little out of date as the last download available is 2005! :) Aug 3, 2010 at 12:49

Bit late for an answer, but would like to share my experience. I had a similar problem. Basically needed to get output from Python application in pdf form. Had a look at various alternatives

1. Jinja2
2. Reportlab
3. Pollyreports
4. As well as the options listed above

Eventually I settled on using Latex. Basically just wrote a small class that assembled my elements into a tex file and then ran pdflatex on the generated tex file. Other options had a lot of control, but tex already has great formatting predefined and I just needed a professional container for my figures and tables.

Is this what you're asking about? ( I used TeX to save code-space, but LaTeX is the same). If it is the what you're asking about, and you cut and paste this example, make sure the indents are correct after the paste.

#!/usr/bin/env python
import sys, os, os.path
filename = sys.argv[1]
opfile = sys.argv[1] + '.tex'
outfile = open(opfile, 'w')
pageAry = []
def a_tex_file(title):
global pageAry
pageAry.append('\\vskip2em\n\\font\\titlefont=cmr12 at 14.4pt\n\\font\\default=cmr12\n')
pageAry.append('\\def\\today{January 21, 2011}\n')
pageAry.append('\\centerline{\\titlefont ' + title + '}\n\\vskip5pt\n\\vskip5pt\\centerline{\\default blahblahblah}\n')
pageAry.append('\n\\bye')
return 1

a_tex_file("blunk")

for i in pageAry:
outfile.writelines(i)
outfile.close()
os.system('tex '+ opfile)
os.system('xdvi ' + filename + '.dvi & ')

• Do you really need a global variable here? Nov 24, 2012 at 17:48
• LOL. No, guess not. Don't know what I was thinking. Thanks for pointing that out.
– bev
Nov 24, 2012 at 23:46

Depending on what you want to do, Sphinx may suit you. I think its the best Python-based tool for technical documentation, and it supports restructured text.

Depending on exactly what you want to do, you may want to take a look at plasTeX. It's a python version of the TeX engine. It's not a true LaTeX interpreter, but if you have control over the input format of the documents then it could be possible to write them in such a manner that plasTeX can render them. At present, it renders the document to XHTML.

So if you wanted web-viewable copies, you could have it so that your documents were sufficiently simple that plasTeX can read them, then use plasTeX for XHTML-rendering and call pdflatex externally for PDF.

While I love LaTeX, you probably don't want or need TeX to solve your problem. Check out ReportLab Toolkit

PyX is a useful package if you want graphs and charts.

If you want to convert a web page into a pdf, maybe the better way is using the python-pisa package, perform a direct conversion, I used it in a django projects for this purpose.

check latexmake. It allows easily to create your pdf files with python.

Where does the data for the PDF you want to generate come from? A database?

I ask because (despite being a big Python fan) I once used PHP to generate a latex file with data populated from a database (this was for a very small conference proceedings). It's a bit messy, but works reasonably well; you can easily intermingle PHP code which pulls from the database with latex source, in the same way that you can mix PHP with HTML. Then just compile the resulting latex file to get a PDF.

A very good programming guideline is separation of logic from presentation.

This is done in professional Web development (see e.g. Django). If you think not about html pages, but pdf, the answer is the same.

The more you mix your code logic with presentation, the more difficult it is to support and modify that. Are you planning to re-launch all your computations if you want to change a caption of one table? Are you going to reprocess all rendering when you want to change some internal implementation of a function?

That's why I think that calling Python from LaTeX or creating LaTeX strings from Python is in general not a very good idea. It is possible though when you store logic in one place (Python files) and presentation in another place (LaTeX templates), and join them in the third place (aka Model-Template-View or Model-View-Controller architecture).

Unfortunately, it is not straightforward to just take Jinja2 (as @user573 proposed) and render LaTeX templates with that: you have to define the template language for LaTeX (which is not so hard). Then you have to run pdflatex (or other command) via Python's subprocess module. I also run pdftoppm to generate png images from pdfs (those are easier to slide and can be used in Web, if one needs that). I don't copy the exact code here (see yourself the link below), because it would lead to further questions.

I created a data analysis framework in Python, which allows to easily generate many figures with LaTeX quality, while keeping your data, logic and presentation separate. It can be used outside data analysis, because it is a general architectural framework (you can render figures, or tables, or any text - there are no artificial limitations for that). It follows functional programming style (and in some places object-oriented approach). You can check examples and the approach in the first part of Lena tutorial. If an "architectural framework" sounds frightening, I should add that the 1st part would already be enough to create many plots.

UPD: I forgot to mention that Lena doesn't recreate already produced plots if they were not changed (neither the data, nor the template). This is a useful optimization when creating many figures (and adding new ones).

For folks interested in a newer solution, I also ran into this problem and coded up a workaround. Repo has more information: (py2tex)

Basically, you surround your Python code with 🐍 tags. Anything you print inside these tags is inserted into your final tex file! For example:

\documentclass{article}
\begin{document}

🐍
print('Python \\textrightarrow \\LaTeX!')
🐍

\end{document}


becomes:

\documentclass{article}
\begin{document}

Python \textrightarrow \LaTeX!

\end{document}


All you need to do is run the py2tex.py utility from the linked GitHub repo. Alternatively, you can hook into it from latexmk using a custom dependency (instruction for this also in the git repo).

This tool saved me a lot of time and heartache. I hope you like it!