index.odt 2.12 KB
Newer Older
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
{{include 'lists/index.html'}}
{{
    import base64
    import cStringIO
    import os


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

    #
    # go to the build directory
    #
    cwd = os.getcwd()
    wd = os.path.join(request.folder, 'tmp_build')
    if not os.path.exists(wd):
        os.chdir(request.folder)
        os.mkdir('tmp_build')
        os.chdir('tmp_build')
    else:
        os.chdir(wd)
    pass

    #
    # create the HTML file
    #
    shtml = '<head></head><body>%s</body>' % response.body.getvalue()

    froot = str(uuid4())
    fhtml = '%s.html' % froot

    fi = open(fhtml, 'wb')
    fi.write(shtml)
    fi.close()

    #
LE GAC Renaud's avatar
LE GAC Renaud committed
38
    # convert the HTML in ODT file using libreoffice
39
    #
40
    fi_tmp = TemporaryFile()
41

LE GAC Renaud's avatar
LE GAC Renaud committed
42
    # create the virtual X11 environment on the server
43 44 45 46 47 48 49
    if os.path.exists('/usr/bin/Xvfb'):
        cmd = "Xvbf :1 -screen 0 800x600x8 & "
        cmd += "libreoffice --nologo --headless --invisible --display :1.0 --convert-to odt "
        cmd += fhtml

        call(cmd, stdout=fi_tmp, shell=True)

LE GAC Renaud's avatar
LE GAC Renaud committed
50
    # development area in which X11 is running
51 52 53
    else:
        cmd = ["libreoffice", "--headless", "--convert-to", "odt", fhtml]
        call(cmd, stdout=fi_tmp)
54

LE GAC Renaud's avatar
LE GAC Renaud committed
55 56
    pass

57 58
    fodt = '%s.odt' % froot

59 60 61 62
    if os.path.exists(fodt):
        fi = open(fodt, 'rb')
        sodt = fi.read()
        fi.close()
63

64 65 66 67 68 69 70 71 72 73 74
    else:
        call("rm -f %s.*" % froot, shell=True)
        os.chdir(cwd)

        fi_tmp.seek(0)
        msg = T("The generation of the ODT file failed:<br><br>")
        msg += fi_tmp.read()
        fi_tmp.close()

        raise HTTP(500, msg)
    pass
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95

    #
    # clean
    #
    for ext in ('html', 'odt'):
        f = '%s.%s' % (froot, ext)
        if os.path.exists(f):
            os.remove(f)
         pass
    pass

    os.chdir(cwd)

    #
    # build the response
    #
    response.body = cStringIO.StringIO()

    response.headers['Content-Type']='application/vnd.oasis.opendocument.text'
    response.headers['Content-Disposition'] = 'attachment;filename="list.odt"'

96
    s64 = base64.b64encode(sodt)
97 98
    response.write(s64, escape=False)
}}