tex2pdf.html 1.35 KB
Newer Older
1 2 3
{{
    #--------------------------------------------------------------------------
    #
4
    # Convert latex file into pdf
5 6
    #
    #--------------------------------------------------------------------------
7
    import base64
LE GAC Renaud's avatar
LE GAC Renaud committed
8
    import io
9 10
    import os

11
    from subprocess import call, check_output
12 13 14
    from uuid import uuid4

    #
15
    # file names
16
    #
17 18 19
    froot = str(uuid4())
    ftex = '%s.tex' % froot
    fpdf = '%s.pdf' % froot
20 21

    #
22
    # Create latex file in /tmp
23 24
    #
    cwd = os.getcwd()
25
    os.chdir('/tmp')
26

27 28 29
    with open(ftex, 'bw') as fi:
        fi.write(response.body.getvalue().encode())
    pass
30 31

    #
32
    # convert the latex file into pdf
33
    #
34 35 36
    try:
        cmd = ['pdflatex', '-interaction', 'nonstopmode', ftex]
        call(cmd)
37

38 39 40 41
        if os.path.exists(fpdf):
            fi = open(fpdf, 'rb')
            spdf = fi.read()
            fi.close()
42

43 44 45
        else:
            msg = "The generation of the PDF file failed.<br>"
            msg += "Please, check the LaTeX file."
46

47
            raise HTTP(500, T(msg))
48

49
        pass
50

51 52 53
    finally:
        call("rm -f %s.*" % froot, shell=True)
        os.chdir(cwd)
54 55 56 57

    pass

    #
58
    # Prepare the response
59
    #
60
    response.headers['Content-Type']='application/pdf'
LE GAC Renaud's avatar
LE GAC Renaud committed
61
    response.body = io.StringIO()
62

LE GAC Renaud's avatar
LE GAC Renaud committed
63
    s64 = base64.b64encode(spdf).decode("utf-8")
64
    response.write(s64, escape=False)
65
}}