From d75004f8e5658d77565dda3ae17c0ff2a0728790 Mon Sep 17 00:00:00 2001
From: Renaud Le Gac <legac@cppm.in2p3.fr>
Date: Tue, 9 Sep 2014 16:45:29 +0200
Subject: [PATCH] First tentative to implement the latex to pdf conversion. The
 current version is not yet working as it should.

---
 controllers/plugin_dbui.py                   |  40 ++++++
 static/plugin_dbui/src/grid/plugin/Export.js | 137 +++++++++++++++----
 views/plugin_dbui/latex2pdf.html             |  10 ++
 3 files changed, 162 insertions(+), 25 deletions(-)
 create mode 100644 views/plugin_dbui/latex2pdf.html

diff --git a/controllers/plugin_dbui.py b/controllers/plugin_dbui.py
index e022f930..0adcd8d0 100644
--- a/controllers/plugin_dbui.py
+++ b/controllers/plugin_dbui.py
@@ -359,6 +359,46 @@ def index():
     return dict(plugin=plugin)
 
 
+def latex2pdf():
+    """Convert a LaTeX file into PDF.
+    
+    """
+    from subprocess import call
+    from tempfile import TemporaryFile
+    from uuid import uuid4
+
+    latex = request.vars.latex
+# 
+#     # create the latex file in  the private directory
+#     cwd = os.getcwd()
+#     os.chdir(os.path.join(request.folder, 'private'))
+#     
+#     fn = str(uuid4())
+#     fi = open('%s.tex' % fn, 'wb')
+#     fi.write(latex)
+#     fi.close()
+#     
+#     # convert the latex file into pdf
+#     cmd = ['pdflatex', '-interaction', 'nonstopmode', '%s.tex' % fn] 
+#     call(cmd, stdout=TemporaryFile())
+#     
+#     # copy the pdf in a string
+#     fi = open('%s.pdf' % fn, 'rb')
+#     s_pdf = fi.read()
+#     fi.close()
+#     
+#     # clean latex processing
+#     for ext in ('aux', 'log', 'pdf', 'tex'):
+#         f = '%s.%s' % (fn, ext)
+#         if os.path.exists(f):
+#             os.remove(f)
+#     
+#     # go back to the web2py main directory
+#     os.chdir(cwd)
+    s_pdf = latex
+    return dict(data=s_pdf)
+
+
 def status():
     return dict(request=request, response=response, session=session)
 
diff --git a/static/plugin_dbui/src/grid/plugin/Export.js b/static/plugin_dbui/src/grid/plugin/Export.js
index 992c5d2a..5cbc3cd8 100644
--- a/static/plugin_dbui/src/grid/plugin/Export.js
+++ b/static/plugin_dbui/src/grid/plugin/Export.js
@@ -14,13 +14,13 @@ Ext.define('App.grid.plugin.Export', {
 
     /**
      * @cfg {String}
-     * The CSV delimiter for stirng.
+     * The CSV delimiter for string.
      */
     delimiter: '"',
 
     /**
      * @cfg {String}
-     * The new line separator used in the CSV file.
+     * The new line separator used in the CSV / LaTeX file.
      */
     newLine: '\n',
 
@@ -112,10 +112,9 @@ Ext.define('App.grid.plugin.Export', {
     },
 
     /**
-     * Download the data using URI embedded into an HTML link.
-     * The URI is build from the first three arguments.
-     * In addition, the data are HTML encoded to preserve special
-     * character like /, ?, ...
+     * Download the data as a file using an URI.
+     * The URI is built from the arguments and the data are HTML
+     * encoded to preserve special character like quote, /, ?, ...
      *
      * @param {String}
      * The mine type of the return file, e.g "text/csv".
@@ -123,32 +122,30 @@ Ext.define('App.grid.plugin.Export', {
      * @param {String}
      * The data encoding, e.g. "utf-8".
      *
-     * @param {String[]}
+     * @param {String/String[]}
      * The content of the file, one string per line.
      *
-     * @param {String}
-     * The file name with its extension.
-     *
      */
-    download: function (minetype, encoding, data, filename) {
+    downloadViaURI: function (minetype, encoding, data) {
 
         "use strict";
 
-        var uri = "data:" + minetype + ";charset=" + encoding +",",
-            link;
+        var uri;
 
-        // special character like quote, / , ? are HTML encoded
-        uri += encodeURIComponent(data.join(this.newLine));
+        // build the data string in which special
+        // character like quote, / , ? are HTML encoded
+        if (Ext.isArray(data)) {
+            data = data.join(this.newLine);
+        }
+        data = encodeURIComponent(data);
 
-        // download the file by simulating a click on a link
-        link = Ext.getBody().createChild({
-            tag: "a",
-            href: uri,
-            download: filename
-        });
+        // build the URI
+        uri = "data:" + minetype + ";";
+        uri += "charset=" + encoding +",";
+        uri += data;
 
-        link.dom.click();
-        link.destroy();
+        // stimulate the browser to mimic the field download
+        window.location.href = uri;
     },
 
     /**
@@ -367,7 +364,7 @@ Ext.define('App.grid.plugin.Export', {
         "use strict";
 
         var data = this.getCSV();
-        this.download("text/csv", "utf-8", data, "my_data.csv");
+        this.downloadViaURI("text/csv", "utf-8", data);
     },
 
     /**
@@ -413,16 +410,106 @@ Ext.define('App.grid.plugin.Export', {
         "use strict";
 
         var data = this.getLaTeX();
-        this.download("application/x-latex", "utf-8", data, "my_data.tex");
+        this.downloadViaURI("application/x-latex", "utf-8", data);
     },
 
     /**
      * Export the content of the grid as a PDF file.
      *
      */
+    downloadViaIFRAME: function (panel, url) {
+
+        "use strict";
+
+        var frameId = 'mainPanelIframe',
+            iframe;
+
+        // destroy IFRAME previously embedded in the panel
+        iframe = Ext.getBody().getById(frameId);
+        if (iframe) {
+            Ext.destroy(iframe);
+        }
+
+        // launch a progress bar
+        Ext.MessageBox.show({
+            msg: 'Preparing your file, please wait...',
+            progressText: 'Saving...',
+            width: 300,
+            wait: true
+        });
+
+        // append the IFRAME to the panel therefore
+        // the browser will launch the downloading.
+        //
+        // NOTE: the IFRAME cover almost the full space.
+        // this is useful when the PDF is embedded in the panel.
+        //
+        // NOTE: keep the background colour to white
+        //
+        iframe = Ext.getBody().createChild({
+            tag: 'iframe',
+            id: frameId,
+            frameborder: 0,
+            width: '100%',
+            height: '99%',
+            style: 'background: #00FF00;',
+            src: url
+        });
+
+        // when the download is finish hide message box
+        iframe.on('load', function () {
+            Ext.MessageBox.hide();
+        }, this, {single: true});
+    },
+
     onPdfExport: function () {
 
        "use strict";
 
+        /*
+        var data,
+            form,
+            url;
+
+        data = this.getLaTeX().join(this.newLine);
+        url = '/plugin_dbui/plugin_dbui/latex2pdf.html';
+
+        form = Ext.create('Ext.form.Panel', {
+            items: [{
+                name: 'latex',
+                value: data,
+                xtype:'textfield'
+            }],
+            standardSubmit: true,
+            url: url
+        });
+
+        console.log(form);
+        form.getForm().submit();
+        */
+
+        var url,
+            vars = {latex: undefined};
+
+        // build the url
+        vars.latex = this.getLaTeX().join(this.newLine);
+
+        url = '/plugin_dbui/plugin_dbui/latex2pdf.html' + '?' + Ext.Object.toQueryString(vars);
+
+        this.downloadViaIFRAME(this.getCmp(), url);
+
+        /*
+        // trigger the latex to pdf conversion on the server side
+        Ext.Ajax.request({
+            url: '/plugin_dbui/plugin_dbui/latex2pdf.html',
+            params: {latex: data},
+            scope: this,
+            success: function (response) {
+                console.log(response.responseText);
+                this.download("application/pdf", "utf-8", response.responseText, "my_data.pdf");
+            }
+        }); */
+
+
     }
 });
\ No newline at end of file
diff --git a/views/plugin_dbui/latex2pdf.html b/views/plugin_dbui/latex2pdf.html
new file mode 100644
index 00000000..ec25db31
--- /dev/null
+++ b/views/plugin_dbui/latex2pdf.html
@@ -0,0 +1,10 @@
+{{
+    
+    try:
+        response.headers['Content-Type']='application/pdf'
+        response.write(data, escape=False)
+  
+    except:
+        raise HTML(405, T('LaTeX to PDF conversion failed.'))
+    
+}}
\ No newline at end of file
-- 
GitLab