Convert LaTeX templates to various output formats

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
from subprocess import call, PIPE
from os import remove, rename
from os.path import dirname
from tempfile import NamedTemporaryFile
from django.template import loader, Context

def process_latex(template, context={}, type='pdf', outfile=None):
    """
    Processes a template as a LaTeX source file.
    Output is either being returned or stored in outfile.
    At the moment only pdf output is supported.
    """

    t = loader.get_template(template)
    c = Context(context)
    r = t.render(c)

    tex = NamedTemporaryFile()
    tex.write(r)
    tex.flush()
    base = tex.name
    items = "log aux pdf dvi png".split()
    names = dict((x, '%s.%s' % (base, x)) for x in items)
    output = names[type]

    if type == 'pdf' or type == 'dvi':
        pdflatex(base, type)
    elif type == 'png':
        pdflatex(base, 'dvi')
        call(['dvipng', '-bg', '-transparent',
              names['dvi'], '-o', names['png']],
              cwd=dirname(base), stdout=PIPE, stderr=PIPE)

    remove(names['log'])
    remove(names['aux'])

    if not outfile:
        o = file(output).read()
        remove(output)
        return o
    else:
        rename(output, outfile)

def pdflatex(file, type='pdf'):
    call(['pdflatex', '-interaction=nonstopmode',
                      '-output-format', type, file],
         cwd=dirname(file), stdout=PIPE, stderr=PIPE)

More like this

  1. Renderer decorator by GaretJax 5 years, 6 months ago
  2. render_to by asolovyov 4 years, 12 months ago
  3. pyText2Pdf - Python script to convert plain text into PDF file. Modified to work with streams. by vsergeyev 3 years, 7 months ago
  4. dict to ul by franciscosilvera 10 months, 3 weeks ago
  5. Multi-level (tree-ish) navigation by jpic 4 years, 8 months ago

Comments

(Forgotten your password?)