Can I run pdflatex on an in-memory file?
<p>I am to generate a series of pdf files whose contents is to be generated in Python (2.7). A regular solution is to save the .tex contents at some directory, call pdflatex on the file, read in the pdf-file afterwards in order to finally place the file somewhere relevant. This is shown below:</p>

<pre><code>import os

texFile = \
"""\\documentclass[11pt,a4paper,final]{article}
\\begin{document}
Hello, world!
\\end{document}
""" # Clearly will a more awesome file be generated here!

with open('hello.tex', 'w') as f:
    f.write(texFile)
os.system('pdflatex hello.tex')
pdfFile = open('hello.pdf', 'rb').read()
# Now place the file somewhere relevant ...
</code></pre>

<p>I desire the same procedures but comitted on an in-memory basis, for increasing speed and avoiding file leakage into some folder. So my question is, how to run pdflatex on an in-memory basis and extracting the resulting pdf back into Python?</p>

<p>Have a look at <a href="https://pypi.python.org/pypi/tex" rel="nofollow">tex</a>. It provides an in-memory API to the TeX command line tools. For example:</p>

<pre><code>&gt;&gt;&gt; from tex import latex2pdf
&gt;&gt;&gt; document = ur"""
... \documentclass{article}
... \begin{document}
... Hello, World!
... \end{document}
... """
&gt;&gt;&gt; pdf = latex2pdf(document)

&gt;&gt;&gt; type(pdf)
&lt;type 'str'&gt;
&gt;&gt;&gt; print "PDF size: %.1f KB" % (len(pdf) / 1024.0)
PDF size: 5.6 KB
&gt;&gt;&gt; pdf[:5]
'%PDF-'
&gt;&gt;&gt; pdf[-6:]
'%%EOF\n'
</code></pre>

<p>You can install it by simply running <code>pip install tex</code>. Also note that for the string blocks you can simply prepend <code>r</code> to make it a raw string. That way you don't have to escape all the backslashes.</p>

python pdflatex