Friday, April 24, 2015

Grails and Pdf creation

In my businness application, I needed to print report in a pdf file.Before Grails 2.5.0, I used export-plugin with success.I tried to use with Grails 2.5.0 but I obtained compilation errors.That's why I looked for other solutions.
I found rendering plugin but I had an error when rendering ( see http://stackoverflow.com/questions/29694796/null-pointer-exception-with-grails-rendering-plugin ).
Finaly, I decided to do it myself with apache pdfbox

In my BuildConfig.groovy, I added the dependency :

   dependency {  
     ...  
     compile "org.apache.pdfbox:pdfbox:1.8.9"  
     ...  
   }  

And here is the code in my controller :

 class AppRetailController {  
   ...  
   def renderFormPDF(){  
     List<App> apps = new ArrayList<>()  
     String title = ""  
     String param = params.get("serverSelect")  
     ...  
     Fill the list apps  
     ...  
           title= "Liste de toutes les applications sur " + param  
           title += " (" + apps.size() + ")"  
           // Create all needed for Pdf document  
     PDDocument document = new PDDocument();  
     PDPage page = new PDPage();  
     PDPageContentStream contentStream;  
           // Here I want 30 rows by page  
     int pageNumber = apps.size()/30 + 1  
     log.info("Page number :" + pageNumber)  
     int countApp = 0  
           // for each page I draw table with datas  
     for (int i=1; i<=pageNumber; i++) {  
       log.info("countApp :" + countApp)  
       page = new PDPage();  
       contentStream = new PDPageContentStream(document, page);  
       int max = countApp + 30  
       if (max > apps.size()) {  
         max = apps.size() - 1  
       }  
       drawTable(page, contentStream, 700, 100, apps[countApp..max], title);  
       countApp = countApp + 30 + 1  
       contentStream.close();  
       document.addPage(page);  
     }  
     document.save("report.pdf");  
     document.close();  
     render( file:new File("report.pdf"), fileName: "report.pdf")  
   }  
   /**  
    * @param page  
    * @param contentStream  
    * @param y the y-coordinate of the first row  
    * @param margin the padding on left and right of table  
    * @param content a 2d array containing the table data  
    * @throws IOException  
    */  
   def drawTable(PDPage page, PDPageContentStream contentStream,  
                  float y, float margin,  
                  List<App> apps, String title) throws IOException {  
     final int rows = apps.size() + 1;  
     final int cols = 3;  
     final float rowHeight = 20f;  
     final float tableWidth = page.findMediaBox().getWidth()-(2*margin);  
     final float tableHeight = rowHeight * rows;  
     final float colWidth = tableWidth/(float)cols;  
     final float cellMargin=5f;  
     //draw the rows  
     float nexty = y ;  
     for (int i = 0; i <= rows; i++) {  
       contentStream.drawLine(margin,nexty,(float)(margin+tableWidth),nexty);  
       nexty-= rowHeight;  
     }  
     //draw the columns  
     float nextx = margin;  
     for (int i = 0; i <= cols; i++) {  
       contentStream.drawLine(nextx,y,nextx,(float)(y-tableHeight));  
       nextx += colWidth;  
     }  
     //now add the text  
     contentStream.setFont(PDType1Font.HELVETICA_BOLD,14);  
     contentStream.beginText();  
     contentStream.moveTextPositionByAmount((float)margin+cellMargin+10,(float)(y+20));  
     contentStream.drawString(title);  
     contentStream.endText();  
     contentStream.setFont(PDType1Font.HELVETICA_BOLD,12);  
     float textx = margin+cellMargin;  
     float texty = y-15;  
     //Define colunm title  
     contentStream.beginText();  
     contentStream.moveTextPositionByAmount(textx,texty);  
     contentStream.drawString("Nom");  
     contentStream.endText();  
     textx += colWidth;  
     contentStream.beginText();  
     contentStream.moveTextPositionByAmount(textx,texty);  
     contentStream.drawString("Description");  
     contentStream.endText();  
     textx += colWidth;  
     contentStream.beginText();  
     contentStream.moveTextPositionByAmount(textx,texty);  
     contentStream.drawString("Chemin dans ARENA");  
     contentStream.endText();  
     textx += colWidth;  
     texty-=rowHeight;  
     textx = margin+cellMargin;  
     contentStream.setFont(PDType1Font.HELVETICA,11);  
     apps.each {  
       contentStream.beginText();  
       contentStream.moveTextPositionByAmount(textx,texty);  
       contentStream.drawString(it.name);  
       contentStream.endText();  
       textx += colWidth;  
       contentStream.beginText();  
       contentStream.moveTextPositionByAmount(textx,texty);  
       String desc = it.description  
       if (desc.equals("EMPTY")) {  
         desc = ""  
       }  
       contentStream.drawString(desc);  
       contentStream.endText();  
       textx += colWidth;  
       contentStream.beginText();  
       contentStream.moveTextPositionByAmount(textx,texty);  
       String path = it.arenaPath  
       if (path == null) {  
         path = ""  
       }  
       contentStream.drawString(path);  
       contentStream.endText();  
       textx += colWidth;  
       texty-=rowHeight;  
       textx = margin+cellMargin;  
     }  
   }  
 }  


So, this is not the best solution.I would have preferred something like rendering plugin but it's works and I needed it immediately.A big thanks to this blog for the use of pdf library : http://fahdshariff.blogspot.fr/2010/10/creating-tables-with-pdfbox.html 

Hope this help,

See also : http://grails.github.io/grails-doc/2.5.x/ref/Controllers/render.html

Friday, April 3, 2015

Grails : an example of remoteFunction with two parameters


In my businness web application, I wanted to use a selectbox which call a controller method to check mail address stores in ldap. On change of selectbox, it will automaticaly check if the mail exists in ldap.In this paper, we will talk about the use of remoteFunction with 2 parameters.I wrote it because I had difficulties with this ( especially the syntax ) and I hope it could help someone !

The gsp


In my gsp, I had an input text and a select box.The remoteFunction calls the action of the controller ajaxCheckMailInLDAP. Parameters are passed in params. ( Be carefull at the syntax ).Once achieved, the javascript method checkLdapMail(data) called.

example

// Show the result
 <div id="create_status_ok" class="alert alert-success" role="alert" style="display: none">
        <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
        <span class="sr-only">Info:</span>
        Vérification dans le LDAP OK ! vous pouvez créer cette adresse.
 </div> 
 ...
 
// form that use remoteFunction 
<form>
   <input type="text" class="form-control" id="rne" name="rne" placeholder="....087XXX" value="">  
   ...  
   <g:select noSelection="['0':'Choisir un type de boîte']" optionKey="id" optionValue="fullNameType" name="shortNameType" id="selecttype" from="${toolprod.MailType.list()}"
    onchange="
    cleanMsg();
    ${remoteFunction(
       controller:'tools',
       action:'ajaxCheckMailInLDAP',
       params:'\'id=\' + this.value + \'&rne=\' + document.getElementById(\'rne\').value',
       onSuccess:'checkLdapMail(data)')}"
    ></g:select> 
 </form>  


The controller's action


Here is my controller wich render an array as JSON.Note that the name of data variable is important !

 class ToolsController {  
 ...  
   def ajaxCheckMailInLDAP = {  
        log.info("ajaxCheckMailInLDAP()")
 
       String mail = params.rne + "@.."

        // Init JSON data
        def data = [:]
        data.put("id", "1")
        if (checkMail(mail)) {// just return a boolean
            data.put("text", "KO")
        } else {
            data.put("text", "OK")
        } 
        data.put("mail", mail)
        log.info("ajaxCheckMailInLDAP() END" + mail)
        render data as JSON 
   }  
 ....  
 }  

To finish, below is the javascript method :

    /**
     * Show result stored in data on html page
     * @param data JSON data send by ajaxCheckMailInLDAP in controller.
     */
    function checkLdapMail(data) {
        console.log("checkLdapMail()");

        document.getElementById('selecttype').value=0;
        document.getElementById('create_status_ko').style.display='none';
        document.getElementById('create_status_ok').style.display='none';
        document.getElementById('create_status_info').style.display='block';

        if (data.text == "KO") {
            document.getElementById('create_status_info').style.display='none';
            document.getElementById('create_status_ko').style.display='block';
            document.getElementById('create_status_ko').textContent= data.mail.toString() + " existe deja dans le LDAP !";
        }
        if (data.text == "OK") {
            document.getElementById('create_status_info').style.display='none';
            document.getElementById('create_status_ok').style.display='block';
            document.getElementById('btnSubmit').disabled = false;
        }

        if (data.text == "EMPTY") {
            document.getElementById('create_status_info').style.display='none';
            document.getElementById('create_status_ko').style.display='block';
            document.getElementById('create_status_ko').textContent= "le rne est vide !";

        }
        console.log("checkLdapMail() : end");
    }

To make it works, I use the parameter name data.An other important things, I used Grails 2.4.4 to make this example.
I hope it will help you in your developpement.