Login

Convert LaTeX templates to various output formats

Author:
blizz
Posted:
March 11, 2007
Language:
Python
Version:
Pre .96
Tags:
pdflatex latex dvi django pdf png template
Score:
2 (after 2 ratings)

The code is a bit messy and may include bugs ;-) Anyway, I want to clean it up and add features (see below).

The process_latex() function will read the given template, render it with a custom context and convert it into the desired output format by running it through pdflatex.

Depending on the outfile parameter, the output will either be returned (for a response object) or written to the path specified in outfile (useful for save() in models which generate static, unique files).

TODO

  • Error handling in case pdflatex breaks (non-zero return value)
  • Optionally returning a HttpResponse with the correct mimetype and Content-Disposition set to attachement and an appropriate filename
  • RequestContext instead of Context (passing the Context object instead of a dict)

CREDITS

Credits also go to ronny for the names dict :-P

 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. Admob Ad Insertion Snippet by johnboxall 7 years, 1 month ago
  2. Inspect object debugging tag by dballanc 8 years, 1 month ago
  3. render_to by asolovyov 7 years, 2 months ago
  4. Format transition middleware by limodou 8 years, 6 months ago
  5. JSON encode ISO UTC datetime by japerk 6 years, 4 months ago

Comments

Please login first before commenting.