tex2pdf.html 1.82 KB
Newer Older
1 2 3 4 5 6
{{
    #--------------------------------------------------------------------------
    #
    # Converte to transform a tex file generate by a view as a pdf file
    #
    #--------------------------------------------------------------------------
7
    import base64
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
    import cStringIO
    import os

    from subprocess import call
    from tempfile import TemporaryFile
    from uuid import uuid4

    #
    # Get the latex string generate by the latex view
    # and remove it from the response object
    #
    latex = response.body.getvalue()
    response.body = cStringIO.StringIO()

    #
    # go to the private directory and create a latex file
    #
    cwd = os.getcwd()
26
    wd = os.path.join(request.folder, 'tmp_build')
LE GAC Renaud's avatar
LE GAC Renaud committed
27 28
    if not os.path.exists(wd):
        os.chdir(request.folder)
29 30
        os.mkdir('tmp_build')
        os.chdir('tmp_build')
LE GAC Renaud's avatar
LE GAC Renaud committed
31 32 33
    else:
        os.chdir(wd)
    pass
34 35 36 37 38 39 40 41 42 43 44 45 46

    fn = str(uuid4())
    fi = open('%s.tex' % fn, 'wb')
    fi.write(latex)
    fi.close()

    #
    # Launch a subprocess to convert the latex file into pdf
    #
    cmd = ['pdflatex', '-interaction', 'nonstopmode', '%s.tex' % fn]
    call(cmd, stdout=TemporaryFile())

    #
47
    # copy the pdf into a base64 string
48
    #
49 50 51
    fn_pdf = '%s.pdf' % fn
    if os.path.exists(fn_pdf):
        fi = open(fn_pdf, 'rb')
52 53 54
        data = fi.read()
        fi.close()

55
    else:
56 57 58
        data = "\nThe generation of the PDF file failed."
        data += "\nPlease, check the LaTeX file."

59
    pass
60

61
    s64 = base64.b64encode(data)
62
    #
63
    # cleaning
64
    #
LE GAC Renaud's avatar
LE GAC Renaud committed
65
    for ext in ('aux', 'log', 'out', 'pdf', 'tex'):
66 67 68 69 70 71
        f = '%s.%s' % (fn, ext)
        if os.path.exists(f):
            os.remove(f)
         pass
    pass

72 73
    os.chdir(cwd)

74
    #
75
    # Prepare the response
76
    #
77 78
    response.headers['Content-Type']='application/pdf'
    response.write(s64, escape=False)
79
}}