Advertisement
Guest User

Untitled

a guest
Dec 17th, 2018
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 54.17 KB | None | 0 0
  1. package ReportGeneratorPDF;
  2. import Modelos.*;
  3. import Persistencia.ReportManager;
  4. import com.itextpdf.html2pdf.HtmlConverter;
  5. import com.itextpdf.io.image.ImageData;
  6. import com.itextpdf.io.image.ImageDataFactory;
  7. import com.itextpdf.kernel.colors.*;
  8. import com.itextpdf.kernel.font.PdfFont;
  9. import com.itextpdf.kernel.font.PdfFontFactory;
  10. import com.itextpdf.kernel.geom.PageSize;
  11. import com.itextpdf.kernel.geom.Rectangle;
  12. import com.itextpdf.kernel.pdf.PdfDocument;
  13. import com.itextpdf.kernel.pdf.PdfPage;
  14. import com.itextpdf.kernel.pdf.PdfWriter;
  15. import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
  16. import com.itextpdf.kernel.pdf.xobject.PdfXObject;
  17. import com.itextpdf.layout.Canvas;
  18. import com.itextpdf.layout.Document;
  19. import com.itextpdf.layout.element.*;
  20. import com.itextpdf.layout.element.Image;
  21. import com.itextpdf.layout.layout.LayoutArea;
  22. import com.itextpdf.layout.layout.LayoutContext;
  23. import com.itextpdf.layout.layout.LayoutResult;
  24. import com.itextpdf.layout.property.TextAlignment;
  25. import com.itextpdf.layout.property.UnitValue;
  26. import com.itextpdf.layout.property.VerticalAlignment;
  27. import sun.reflect.generics.reflectiveObjects.NotImplementedException;
  28.  
  29. import javax.servlet.Servlet;
  30. import javax.servlet.ServletContext;
  31. import javax.servlet.ServletOutputStream;
  32. import java.nio.file.Paths;
  33. import java.util.HashMap;
  34. import java.util.LinkedList;
  35. import java.util.List;
  36. import java.util.Queue;
  37.  
  38. public class ReportGenerator {
  39.  
  40.     /* Constant definitions */
  41.  
  42.     private static final String imagePath = "/img/pdf_resources";
  43.     private final DeviceRgb C_HEADER_LIGHT_GRAY = new DeviceRgb(230,230,230);
  44.     private final DeviceRgb C_HEADER_LIGHT_BORDER = new DeviceRgb(170,170,170);
  45.     private final DeviceRgb CORPORATIVE_COLOR = new DeviceRgb(170,34,24);
  46.     private final String HEADER_TEXT = "KDNA Genomics";
  47.     private HashMap<Integer, PdfXObject> HashedPdfXObjectCache = null;
  48.  
  49.  
  50.     /* Function to check if set of IBlockElement is empty or not */
  51.  
  52.     protected boolean CheckIfStringEmpty(String str)
  53.     {
  54.         Boolean result = str.replace("\u00A0","")
  55.             .replace("\u2007","")
  56.             .replace("\u202F","")
  57.             .trim().isEmpty();
  58.         return result;
  59.     }
  60.  
  61.     protected boolean CheckIfBlockEmpty(IElement e) {
  62.         /* Get all the text */
  63.         if (e instanceof Text) return CheckIfStringEmpty(((Text) e).getText());
  64.         else
  65.         {
  66.             BlockElement blk = (BlockElement) e;
  67.             Queue<IElement> elements = new LinkedList<>();
  68.             elements.addAll(blk.getChildren());
  69.             while (!elements.isEmpty())
  70.             {
  71.                 IElement el = elements.poll();
  72.                 if (el instanceof Text)
  73.                 {
  74.                     if (!CheckIfStringEmpty(((Text) el).getText()))
  75.                         return false;
  76.                 }
  77.                 else
  78.                 {
  79.                     blk = (BlockElement) el;
  80.                     elements.addAll(blk.getChildren());
  81.                 }
  82.             }
  83.         }
  84.         return true;
  85.     }
  86.  
  87.  
  88.     protected boolean CheckIfBlocksEmpty(List<IBlockElement> elements)
  89.     {
  90.         for (IElement e : elements) {
  91.             if (!CheckIfBlockEmpty(e)) return false;
  92.         }
  93.         return true;
  94.     }
  95.  
  96.     /*
  97.         Function to sanitize category string
  98.      */
  99.  
  100.     protected String Util_SanitizeString(String categoryString){
  101.         if (categoryString.contains(":")){
  102.             return categoryString.substring(0,categoryString.indexOf(":"));
  103.         }else if (categoryString.contains("(")){
  104.             return categoryString.substring(0,categoryString.indexOf("("));
  105.         }else{
  106.             return categoryString;
  107.         }
  108.     }
  109.  
  110.     /*
  111.         Generic function for drawing a list item with/out icon
  112.      */
  113.  
  114.     private void DrawGeneric_ListIcon(Canvas canvas, ServletContext context, String title, String iconPath, float x, float y){
  115.         try {
  116.  
  117.             float width = canvas.getRootArea().getWidth();
  118.             float height = canvas.getRootArea().getHeight();
  119.  
  120.             PdfCanvas pCanvas = canvas.getPdfCanvas();
  121.  
  122.             if (iconPath != null)
  123.                 AddImageCaching(pCanvas,ImageDataFactory.createPng(context.getResource(imagePath + "/" + iconPath)), x, y, 45, false); // Background
  124.  
  125.             int fontSize = 20;
  126.  
  127.             // Text of the item
  128.             PdfFont font = PdfFontFactory.createFont();
  129.             Paragraph paragraph = new Paragraph(title.substring(0,1));
  130.             paragraph.setFontColor(ColorConstants.BLACK);
  131.             paragraph.setFont(font);
  132.             paragraph.setFontSize(fontSize);
  133.             paragraph.setFixedPosition(x + 70, y, width);
  134.             paragraph.setWidth(font.getWidth(title.substring(0,1),fontSize)+1);
  135.             paragraph.setHeight(45);
  136.             paragraph.setVerticalAlignment(VerticalAlignment.MIDDLE);
  137.             paragraph.setTextAlignment(TextAlignment.LEFT);
  138.             paragraph.setBold();
  139.             canvas.add(paragraph);
  140.  
  141.             Paragraph oldP = paragraph;
  142.             paragraph = new Paragraph(title.substring(1).toUpperCase());
  143.             paragraph.setFontColor(ColorConstants.BLACK);
  144.             paragraph.setFontSize(fontSize-5);
  145.             paragraph.setFixedPosition(x + 70 + oldP.getWidth().getValue(), y-2, width);
  146.             paragraph.setHeight(45);
  147.             paragraph.setVerticalAlignment(VerticalAlignment.MIDDLE);
  148.             paragraph.setTextAlignment(TextAlignment.LEFT);
  149.             canvas.add(paragraph);
  150.  
  151.             pCanvas.rectangle(x, y - 10, 500, 1).setColor(C_HEADER_LIGHT_GRAY, true).fill(); // Header red stroke
  152.         }catch (Exception e){
  153.  
  154.         }
  155.     }
  156.  
  157.     /*
  158.         Generic function for a Content-Page
  159.      */
  160.  
  161.     private void DrawGeneric_ContentPage(Canvas canvas, ServletContext context, String title, String pageNumber, Boolean drawTopBar){
  162.         try {
  163.             float xMidOfPage = canvas.getRootArea().getWidth()/2;
  164.             float width = canvas.getRootArea().getWidth();
  165.             float height = canvas.getRootArea().getHeight();
  166.  
  167.  
  168.             /* Page decoration */
  169.             PdfCanvas pCanvas = canvas.getPdfCanvas();
  170.             pCanvas.rectangle(0,0, 60, height).setColor(C_HEADER_LIGHT_GRAY, true).fill();
  171.  
  172.             if (drawTopBar) {
  173.                 pCanvas.roundRectangle(-100, height - 130, width + 50, 50, 10).setColor(C_HEADER_LIGHT_BORDER, true).fill();
  174.                 pCanvas.roundRectangle(-101, height - 129, width + 50, 48, 10).setColor(C_HEADER_LIGHT_GRAY, true).fill();
  175.             }
  176.             pCanvas.rectangle(0, height-75, canvas.getRootArea().getWidth(), 8).setColor(CORPORATIVE_COLOR,true).fill(); // Header red stroke
  177.             AddImageCaching(pCanvas,ImageDataFactory.createPng(context.getResource(imagePath+"/image17.png")), 70, height-60, 40, false); // Background
  178.  
  179.             /* Header watermark*/
  180.             Paragraph paragraph = new Paragraph(HEADER_TEXT);
  181.             paragraph.setFontColor(ColorConstants.BLACK);
  182.             paragraph.setFontSize(13);
  183.             paragraph.setFixedPosition(width-140, height-60, 140);
  184.             paragraph.setTextAlignment(TextAlignment.CENTER);
  185.             canvas.add(paragraph);
  186.  
  187.             /* Page title */
  188.             if (drawTopBar) {
  189.                 Paragraph tParagraph = new Paragraph(title);
  190.                 tParagraph.setFontColor(new DeviceRgb(64, 91, 195));
  191.                 tParagraph.setBold();
  192.                 tParagraph.setFontSize(25);
  193.                 tParagraph.setFixedPosition(0, height - 125, width - 50);
  194.                 tParagraph.setTextAlignment(TextAlignment.CENTER);
  195.                 canvas.add(tParagraph);
  196.             }
  197.  
  198.             /* Separation line */
  199.             pCanvas.rectangle(70,40, width-100, 1).setColor(C_HEADER_LIGHT_GRAY,true).fill(); // Header red stroke
  200.  
  201.             /* Page number */
  202.             Paragraph nParagraph = new Paragraph("Página | " + pageNumber);
  203.             nParagraph.setFontColor(ColorConstants.DARK_GRAY);
  204.             nParagraph.setFontSize(11);
  205.             nParagraph.setFixedPosition(width-100, 15, 100);
  206.             nParagraph.setTextAlignment(TextAlignment.CENTER);
  207.             canvas.add(nParagraph);
  208.  
  209.         }catch (Exception e){
  210.             e.printStackTrace();
  211.         }
  212.     }
  213.  
  214.     private void DrawGeneric_ContentPage(Canvas canvas, ServletContext context, String title, String pageNumber){
  215.         DrawGeneric_ContentPage(canvas, context, title, pageNumber, true);
  216.     }
  217.  
  218.     /* Ad-hoc code to draw pages*/
  219.  
  220.     /*
  221.         Function to draw the header page
  222.      */
  223.  
  224.     private void Draw_HeaderPage(Canvas canvas, Informe report, ServletContext context){
  225.         try {
  226.             float xMidOfPage = canvas.getRootArea().getWidth()/2;
  227.             float width = canvas.getRootArea().getWidth();
  228.             float height = canvas.getRootArea().getHeight();
  229.  
  230.             PdfCanvas pCanvas = canvas.getPdfCanvas();
  231.  
  232.             pCanvas.rectangle(0, 670-150, canvas.getRootArea().getWidth(), 200).setColor(ColorConstants.LIGHT_GRAY,true).fill(); // Gray rect
  233.  
  234.             pCanvas.circle(xMidOfPage, 730, 90).setColor(ColorConstants.WHITE,true).fill(); // Circle to protect the logo
  235.  
  236.             canvas.add(new Image(ImageDataFactory.createJpeg(context.getResource(imagePath+"/image4.jpeg")))); // Header image
  237.  
  238.             pCanvas.rectangle(0, height-10, canvas.getRootArea().getWidth(), 10).setColor(CORPORATIVE_COLOR,true).fill(); // Header red stroke
  239.  
  240.             AddImageCaching(pCanvas,ImageDataFactory.createPng(context.getResource(imagePath+"/image6.png")), xMidOfPage-65, 670, 130, false); // Logo
  241.  
  242.             pCanvas.rectangle(0, 670-130, canvas.getRootArea().getWidth(), 40).setColor(ColorConstants.WHITE,true).fill(); // Gray rect
  243.  
  244.             // Text header of the very first page
  245.             Paragraph paragraph = new Paragraph("ANÁLISIS GENÉTICO");
  246.             paragraph.setFontColor(ColorConstants.BLACK);
  247.             paragraph.setFontSize(25);
  248.             paragraph.setFixedPosition(0, 670-130, width);
  249.             paragraph.setTextAlignment(TextAlignment.CENTER);
  250.             canvas.add(paragraph);
  251.  
  252.             PdfXObject footer = AddImageCaching(pCanvas,ImageDataFactory.createJpeg(context.getResource(imagePath+"/image1.jpeg")), 0, 0, width, false); // Footer
  253.             AddImageCaching(pCanvas,ImageDataFactory.createPng(context.getResource(imagePath+"/background.png")), 0, 100, width, false); // Background
  254.             // Feature image in the header
  255.             AddImageCaching(pCanvas,ImageDataFactory.createPng(context.getResource(imagePath+"/image3.png")), xMidOfPage-150, 100, 300, false); // Background
  256.  
  257.  
  258.  
  259.         }catch (Exception e){
  260.             e.printStackTrace();
  261.         }
  262.     }
  263.  
  264.     /*
  265.         Function to draw the last page
  266.      */
  267.  
  268.     private void Draw_BackPage(Canvas canvas, Informe report, ServletContext context){
  269.         try {
  270.             float xMidOfPage = canvas.getRootArea().getWidth()/2;
  271.             float width = canvas.getRootArea().getWidth();
  272.             float height = canvas.getRootArea().getHeight();
  273.  
  274.             PdfCanvas pCanvas = canvas.getPdfCanvas();
  275.  
  276.             pCanvas.rectangle(0, 670-150, canvas.getRootArea().getWidth(), 200).setColor(ColorConstants.LIGHT_GRAY,true).fill(); // Gray rect
  277.  
  278.             pCanvas.circle(xMidOfPage, 730, 90).setColor(ColorConstants.WHITE,true).fill(); // Circle to protect the logo
  279.  
  280.             canvas.add(new Image(ImageDataFactory.createJpeg(context.getResource(imagePath+"/image4.jpeg")))); // Header image
  281.  
  282.             pCanvas.rectangle(0, height-10, canvas.getRootArea().getWidth(), 10).setColor(CORPORATIVE_COLOR,true).fill(); // Header red stroke
  283.  
  284.             AddImageCaching(pCanvas,ImageDataFactory.createPng(context.getResource(imagePath+"/image6.png")), xMidOfPage-65, 670, 130, false); // Logo
  285.  
  286.             PdfXObject footer = AddImageCaching(pCanvas,ImageDataFactory.createJpeg(context.getResource(imagePath+"/image1.jpeg")), 0, 0, width, false); // Footer
  287.             // Feature image in the header
  288.             AddImageCaching(pCanvas,ImageDataFactory.createPng(context.getResource(imagePath+"/image3.png")), xMidOfPage-150, 115, 300, false);
  289.  
  290.             /* Text A */
  291.             pCanvas.roundRectangle(xMidOfPage-250, height-265,500, 50, 10).setColor(C_HEADER_LIGHT_BORDER, true).fill();
  292.             pCanvas.roundRectangle(xMidOfPage-250, height-264,500, 48, 10).setColor(C_HEADER_LIGHT_GRAY, true).fill();
  293.  
  294.             Paragraph paragraph = new Paragraph();
  295.             Text txA_1 = new Text("LOS");
  296.             Text txA_2 = new Text(" AVANCES CIENTÍFICOS");
  297.             txA_2.setFontColor(CORPORATIVE_COLOR);
  298.             Text txA_3 = new Text("  SON CRÍTICOS PARA MEJORAR TU RENDIMIENTO");
  299.  
  300.             paragraph.add(txA_1);
  301.             paragraph.add(txA_2);
  302.             paragraph.add(txA_3);
  303.             paragraph.setFontColor(ColorConstants.BLACK);
  304.             paragraph.setFontSize(12);
  305.             paragraph.setFixedPosition(0, height-265, width);
  306.             paragraph.setHeight(50);
  307.             paragraph.setVerticalAlignment(VerticalAlignment.MIDDLE);
  308.             paragraph.setTextAlignment(TextAlignment.CENTER);
  309.             canvas.add(paragraph);
  310.  
  311.             /* Text B */
  312.             pCanvas.roundRectangle(xMidOfPage-(450/2), height-330,450, 50, 10).setColor(C_HEADER_LIGHT_BORDER, true).fill();
  313.             pCanvas.roundRectangle(xMidOfPage-(450/2), height-329,450, 48, 10).setColor(C_HEADER_LIGHT_GRAY, true).fill();
  314.  
  315.  
  316.             paragraph = new Paragraph();
  317.             Text txB_1 = new Text("CONOCER");
  318.             paragraph.add(txB_1);
  319.             Text txB_2 = new Text(" TU GENÉTICA");
  320.             paragraph.add(txB_2);
  321.             txB_2.setFontColor(CORPORATIVE_COLOR);
  322.             Text txB_3 = new Text("  ES ESENCIAL PARA PERSONALIZAR\n TU ENTRENAMIENTO Y TU NUTRICIÓN");
  323.             paragraph.add(txB_3);
  324.  
  325.             paragraph.setFontColor(ColorConstants.BLACK);
  326.             paragraph.setFontSize(12);
  327.             paragraph.setFixedPosition(0, height-325, width);
  328.             paragraph.setTextAlignment(TextAlignment.CENTER);
  329.             canvas.add(paragraph);
  330.  
  331.  
  332.  
  333.         }catch (Exception e){
  334.             e.printStackTrace();
  335.         }
  336.     }
  337.  
  338.     /*
  339.        Draw index page
  340.      */
  341.  
  342.     private void Draw_IndexPage(Canvas canvas, java.util.List<Categoria> categories, ServletContext context, int pn) {
  343.         try {
  344.             float xMidOfPage = canvas.getRootArea().getWidth() / 2;
  345.             float width = canvas.getRootArea().getWidth();
  346.             float height = canvas.getRootArea().getHeight();
  347.             DrawGeneric_ContentPage(canvas, context, "CONTENIDO", Integer.toString(pn));
  348.             PdfCanvas pCanvas = canvas.getPdfCanvas();
  349.  
  350.             float x = 100;
  351.             float y = height-210;
  352.  
  353.             DrawGeneric_ListIcon(canvas, context, "Introducción","image7.png",x,y);
  354.             y-=60;
  355.             DrawGeneric_ListIcon(canvas, context, "Resumen","image8.png",x,y);
  356.             y-=60;
  357.  
  358.             if (categories.size() > 8){
  359.                 throw new Exception("This page is not prepared for more than 8 categories");
  360.             }
  361.  
  362.             for (Categoria category: categories) {
  363.                 DrawGeneric_ListIcon(canvas, context, Util_SanitizeString(category.getNombre()), null, x, y);
  364.                 y-=60;
  365.             }
  366.  
  367.         } catch (Exception e) {
  368.             e.printStackTrace();
  369.         }
  370.     }
  371.  
  372.  
  373.  
  374.     /*
  375.         Draw intro page
  376.      */
  377.  
  378.     private void Draw_IntroPage(Canvas canvas, ServletContext context, int pn) {
  379.         try {
  380.             float xMidOfPage = canvas.getRootArea().getWidth() / 2;
  381.             float width = canvas.getRootArea().getWidth();
  382.             float height = canvas.getRootArea().getHeight();
  383.             PdfCanvas pCanvas = canvas.getPdfCanvas();
  384.             ImageData data = ImageDataFactory.createPng(context.getResource(imagePath+"/background_intro.png"));
  385.             AddImageCaching(pCanvas,data, -50, 0, width+300, false); // Background
  386.             DrawGeneric_ContentPage(canvas, context, "INTRODUCCIÓN", Integer.toString(pn));
  387.  
  388.             // Paragraph 1
  389.             Paragraph paragraph = new Paragraph("El informe incluye el resultado de tu análisis genético para cada fenotipo o característica estudiada, de forma sencilla y accesible.\n");
  390.  
  391.             paragraph.setFontColor(ColorConstants.BLACK);
  392.             paragraph.setFontSize(18);
  393.             paragraph.setFixedPosition(65, height-200, width-65);
  394.             paragraph.setTextAlignment(TextAlignment.LEFT);
  395.             canvas.add(paragraph);
  396.  
  397.             float rect_width = 500;
  398.             float rect_height = 300;
  399.  
  400.             float rect_x = ((width-rect_width)/2)+30;
  401.             float rect_y = (height-rect_height)/2;
  402.  
  403.             // Text protection in center
  404.             pCanvas.roundRectangle(rect_x-1,rect_y-1,rect_width+2,rect_height+2, 3).setColor(C_HEADER_LIGHT_BORDER,true).fill();
  405.             pCanvas.roundRectangle(rect_x,rect_y,rect_width,rect_height, 3).setColor(C_HEADER_LIGHT_GRAY,true).fill();
  406.  
  407.             // Warning
  408.             paragraph = new Paragraph("AVISO IMPORTANTE:");
  409.  
  410.             paragraph.setFontColor(ColorConstants.BLACK);
  411.             paragraph.setFontColor(ColorConstants.RED);
  412.             paragraph.setFontSize(15);
  413.             paragraph.setUnderline();
  414.             paragraph.setFixedPosition(rect_x+10, rect_y+rect_height-35, rect_width-10);
  415.             paragraph.setTextAlignment(TextAlignment.LEFT);
  416.             canvas.add(paragraph);
  417.  
  418.             // Paragraph 1
  419.             paragraph = new Paragraph(
  420.                     "Las \"tendencias individuales\" reportadas se basan en los resultados de cientos de estudios científicos realizados en condiciones específicas en cuanto a origen étnico, edad, sexo y estado de forma de los participantes.\n\n" +
  421.                     "Así mismo, los fenotipos o características analizadas, además de por la composición genética de cada individuo, están influidas por un complejo grupo de factores no genéticos. Por lo tanto, el presente resultado ha de interpretarse en términos probabilísticos (comparación con la población en general, con el resto de la población y percentil), en ningún caso en términos deterministas.");
  422.  
  423.             paragraph.setFontColor(ColorConstants.BLACK);
  424.             paragraph.setFontSize(15);
  425.             paragraph.setFixedPosition(rect_x+10, rect_y, rect_width-10);
  426.             paragraph.setHeight(rect_height-50);
  427.             paragraph.setTextAlignment(TextAlignment.LEFT);
  428.             canvas.add(paragraph);
  429.  
  430.         } catch (Exception e) {
  431.             e.printStackTrace();
  432.         }
  433.     }
  434.  
  435.     /*
  436.         Draw category page
  437.      */
  438.  
  439.     private int Draw_CategoryPage(PdfDocument pdfReport, Canvas canvas, java.util.List<Categoria> categories, Categoria category, java.util.List<ValorInforme> viFenotypes, ReportManager manager, ServletContext context, int pn) {
  440.         try {
  441.             float width = canvas.getRootArea().getWidth();
  442.             float height = canvas.getRootArea().getHeight();
  443.             float xMidOfPage=((width+60)/2);
  444.             final DeviceRgb circleColor = new DeviceRgb(71,155,223);
  445.             Paragraph tParagraph;
  446.             PdfCanvas pCanvas = canvas.getPdfCanvas();
  447.             DrawGeneric_ContentPage(canvas, context, "ANÁLISIS: " + Util_SanitizeString(category.getNombre()), Integer.toString(pn));
  448.  
  449.             /* Image for the category */
  450.  
  451.             String url = Paths.get(context.getRealPath("/profile"), category.getUrlFoto().trim()).normalize().toString();
  452.             ImageData data = ImageDataFactory.create(url);
  453.             PdfXObject obj = AddImageCaching(pCanvas,data, xMidOfPage-150, height-340, 300, false);
  454.  
  455.             /* Draw rectangle for every fenotype */
  456.             float x = xMidOfPage-350/2;
  457.             float y = height-425;
  458.             int numOfFenotypes = 0;
  459.             int numOfRows = 0;
  460.             // Draw rounded rectangle
  461.             float rectWidth = categories.size()*50;
  462.             float xcatRect = xMidOfPage-(rectWidth/2);
  463.             float ycatRect = height-370;
  464.  
  465.             pCanvas.roundRectangle(xcatRect, ycatRect, rectWidth, 20, 3).setColor(C_HEADER_LIGHT_BORDER, true).fill();
  466.             tParagraph = new Paragraph(category.getNombre());
  467.             tParagraph.setFontColor(ColorConstants.WHITE);
  468.             tParagraph.setBold();
  469.             tParagraph.setFontSize(10);
  470.             tParagraph.setFixedPosition(xcatRect, ycatRect, rectWidth);
  471.             tParagraph.setHeight(20);
  472.             tParagraph.setTextAlignment(TextAlignment.CENTER);
  473.             tParagraph.setVerticalAlignment(VerticalAlignment.MIDDLE);
  474.             canvas.add(tParagraph);
  475.  
  476.             float xrect = xcatRect;
  477.             xrect = drawCategories(canvas, categories, category, pCanvas, ycatRect, xrect);
  478.  
  479.             for (ValorInforme vi : viFenotypes){
  480.                     if (numOfFenotypes > 6){
  481.                         // Break the list
  482.                         java.util.List<ValorInforme> subPhenotypes = viFenotypes.subList(numOfRows,viFenotypes.size());
  483.                         if (subPhenotypes.size() == 0) break;
  484.                         if (subPhenotypes.stream().allMatch(e -> e.getBarraPoblacion() == null)) break;
  485.                         // Split into another page, break this for
  486.                         Canvas catPage = CreateCanvasFromDocument(pdfReport);
  487.                         return Draw_CategoryPage(pdfReport, catPage,categories, category, subPhenotypes, manager, context,pn+1);
  488.                     }
  489.                     numOfRows++;
  490.                     if (vi.getBarraUsuario() == null) continue;
  491.                     DeviceRgb rectColor = null;
  492.                     switch (vi.getSemResumen()){
  493.                         case 0: // Green
  494.                             rectColor = new DeviceRgb(76,175,80);
  495.                             break;
  496.  
  497.                         case 1: // Orange
  498.                             rectColor = new DeviceRgb(255,152,0);
  499.                             break;
  500.  
  501.                         case 2: // Red
  502.                             rectColor = new DeviceRgb(244,67,54);
  503.                             break;
  504.                     }
  505.                     y-=50;
  506.                     if (rectColor != null) {
  507.                         // Text bar
  508.                         pCanvas.roundRectangle(xMidOfPage - 260, y, 350, 40, 3).setColor(rectColor, true).fill();
  509.  
  510.                         // Text
  511.                         tParagraph = new Paragraph(vi.getFenotipo().getNombre().replace("\n", "").replace("\r", ""));
  512.                         tParagraph.setFontColor(ColorConstants.WHITE);
  513.                         tParagraph.setBold();
  514.                         tParagraph.setFontSize(10);
  515.                         tParagraph.setFixedPosition(xMidOfPage - 252.5f, y, 335);
  516.                         tParagraph.setHeight(40);
  517.                         tParagraph.setTextAlignment(TextAlignment.CENTER);
  518.                         //tParagraph.setBackgroundColor(ColorConstants.BLUE);
  519.                         tParagraph.setVerticalAlignment(VerticalAlignment.MIDDLE);
  520.                         canvas.add(tParagraph);
  521.  
  522.                         // Percentage gradient bar
  523.                         ImageData rb_data = ImageDataFactory.createPng(context.getResource(imagePath+"/bar_resource.png"));
  524.                         AddImageCaching(pCanvas,rb_data, width-173, y+7, 100, false);
  525.  
  526.                         // User icon
  527.                         ImageData uicon = ImageDataFactory.createPng(context.getResource(imagePath+"/user.png"));
  528.                         AddImageCaching(pCanvas,uicon, width-173 + (vi.getBarraUsuario()), y+7, 10, false);
  529.  
  530.                         // Rest of users icon
  531.                         ImageData ruicon = ImageDataFactory.createPng(context.getResource(imagePath+"/restUsers.png"));
  532.                         AddImageCaching(pCanvas,ruicon, width-173 + (vi.getBarraPoblacion()), y+7, 10, false);
  533.  
  534.                         // Circular progress bar
  535.                         float xarg = width-60;
  536.                         float widtharg = 40;
  537.  
  538.                         // Draw the internal circle
  539.                         pCanvas.circle(xarg+widtharg/2, y+widtharg/2, (widtharg/2)).setColor(ColorConstants.BLACK,false).stroke();
  540.                         pCanvas.circle(xarg+widtharg/2, y+widtharg/2, (widtharg/2)-(widtharg*0.1)).setColor(ColorConstants.BLACK,false).stroke();
  541.  
  542.                         pCanvas.arc(xarg+2, y+2, xarg+widtharg-2,y+widtharg-2, 90, vi.getPercentil()*(-3.6)).setLineWidth(widtharg*0.1f).setStrokeColor(circleColor).stroke();
  543.                         pCanvas.setLineWidth(1);
  544.  
  545.                         // Draw the text for the percentage
  546.                         tParagraph = new Paragraph(vi.getPercentil().toString()+"%");
  547.                         tParagraph.setFontColor(ColorConstants.BLACK);
  548.                         tParagraph.setBold();
  549.                         tParagraph.setFontSize(10);
  550.                         tParagraph.setFixedPosition(xarg+1, y+2, widtharg);
  551.                         tParagraph.setHeight(34);
  552.                         tParagraph.setTextAlignment(TextAlignment.CENTER);
  553.                         tParagraph.setVerticalAlignment(VerticalAlignment.MIDDLE);
  554.                         canvas.add(tParagraph);
  555.  
  556.  
  557.  
  558.                     }
  559.                     numOfFenotypes++;
  560.                 }
  561.  
  562.  
  563.         } catch (Exception e) {
  564.             e.printStackTrace();
  565.         }
  566.         return pn;
  567.     }
  568.  
  569.     /*
  570.         Draw intro page 2
  571.      */
  572.  
  573.     private void Draw_IntroPage2(Canvas canvas, ServletContext context, int pn) {
  574.         try {
  575.             float width = canvas.getRootArea().getWidth();
  576.             float height = canvas.getRootArea().getHeight();
  577.             PdfCanvas pCanvas = canvas.getPdfCanvas();
  578.             DrawGeneric_ContentPage(canvas, context, "INTRODUCCIÓN", Integer.toString(pn));
  579.  
  580.             // Logo at start
  581.             AddImageCaching(pCanvas,ImageDataFactory.createPng(context.getResource(imagePath+"/image11.png")), 80, height-190, 100, false); // Background
  582.  
  583.             // Zone to protect text
  584.             pCanvas.rectangle(80, height-230,430,30).setColor(ColorConstants.LIGHT_GRAY,true).fill();
  585.  
  586.             // Text of the header
  587.             Paragraph paragraph = new Paragraph("MI GENÉTICA");
  588.             paragraph.setFontColor(ColorConstants.BLACK);
  589.             paragraph.setBold();
  590.             paragraph.setFontSize(18);
  591.             paragraph.setFixedPosition(90, height-230, 400);
  592.             paragraph.setTextAlignment(TextAlignment.LEFT);
  593.             canvas.add(paragraph);
  594.  
  595.             /*
  596.                 A-Part
  597.              */
  598.  
  599.             AddImageCaching(pCanvas,ImageDataFactory.createJpeg(context.getResource(imagePath+"/image12.jpeg")), 92, height-336, 130, false); // Background
  600.  
  601.             paragraph = new Paragraph();
  602.  
  603.             Text fPart = new Text("Indica el");
  604.             paragraph.add(fPart);
  605.  
  606.             fPart = new Text(" tamaño del efecto ");
  607.             fPart.setBold();
  608.             paragraph.add(fPart);
  609.  
  610.             fPart = new Text("de la influencia genética del usuario en comparación con la registrada para la población en general. \n" +
  611.                                   "\nEsto es, en qué grado la influencia genética del usuario ejerce un efecto mayor o menor que el registrado para la población en general.");
  612.             paragraph.add(fPart);
  613.             paragraph.setFontColor(ColorConstants.BLACK);
  614.             paragraph.setFontSize(12);
  615.             paragraph.setFixedPosition(240, height-350, width-250);
  616.             paragraph.setTextAlignment(TextAlignment.JUSTIFIED);
  617.             canvas.add(paragraph);
  618.  
  619.             pCanvas.rectangle(70, height-375, width-70, 1).setColor(C_HEADER_LIGHT_GRAY, true).fill(); // Header red stroke
  620.  
  621.             /*
  622.                 B-Part
  623.              */
  624.             paragraph = new Paragraph();
  625.  
  626.             AddImageCaching(pCanvas,ImageDataFactory.createPng(context.getResource(imagePath+"/bars.png")), 92, height-536, 130, false); // Background
  627.  
  628.             fPart = new Text("Indica un ");
  629.             paragraph.add(fPart);
  630.  
  631.             fPart = new Text("resumen ");
  632.             fPart.setBold();
  633.             paragraph.add(fPart);
  634.  
  635.             fPart = new Text("del tamaño del efecto de la influencia genética del usuario en comparación con la población en general. \n\n" +
  636.                     "Así mismo, en aquellos fenotipos en los que el estado de la Investigación en Genética de la Nutrición y el Deporte lo permiten, se representa también el dato numérico que indica ");
  637.             paragraph.add(fPart);
  638.  
  639.             fPart = new Text("el tamaño del efecto");
  640.             fPart.setBold();
  641.             paragraph.add(fPart);
  642.  
  643.             fPart = new Text(" de la influencia genética del usuario.");
  644.             paragraph.add(fPart);
  645.  
  646.             paragraph.setFontColor(ColorConstants.BLACK);
  647.             paragraph.setFontSize(12);
  648.             paragraph.setFixedPosition(240, height-550, width-250);
  649.             paragraph.setTextAlignment(TextAlignment.JUSTIFIED);
  650.             canvas.add(paragraph);
  651.  
  652.             pCanvas.rectangle(70, height-580, width-70, 1).setColor(C_HEADER_LIGHT_GRAY, true).fill(); // Header red stroke
  653.  
  654.             /*
  655.                 C-Part
  656.              */
  657.             paragraph = new Paragraph();
  658.  
  659.             AddImageCaching(pCanvas,ImageDataFactory.createPng(context.getResource(imagePath+"/image13.png")), 92, height-736, 130, false); // Background
  660.  
  661.             fPart = new Text("El percentil representa la valoración de la influencia genética del usuario para este fenotipo, en comparación con la del resto de individuos de la población, ");
  662.             paragraph.add(fPart);
  663.  
  664.             fPart = new Text("ordenada de menor a mayor.");
  665.             fPart.setBold();
  666.             paragraph.add(fPart);
  667.  
  668.             fPart = new Text("Esto es, ");
  669.             paragraph.add(fPart);
  670.  
  671.             fPart = new Text("indica que porcentaje de la población presenta una mayor o una menor influencia genética ");
  672.             fPart.setBold();
  673.             paragraph.add(fPart);
  674.  
  675.             fPart = new Text("para el fenotipo analizado.\n\n" +
  676.                     "Por ejemplo, el percentil 20 indica que el valor de la influencia genética del usuario es superior al registrado por el 20 por ciento de la población e inferior al registrado por el 80 por ciento de la población.");
  677.             paragraph.add(fPart);
  678.  
  679.             paragraph.setFontColor(ColorConstants.BLACK);
  680.             paragraph.setFontSize(12);
  681.             paragraph.setFixedPosition(240, height-780, width-250);
  682.             paragraph.setTextAlignment(TextAlignment.JUSTIFIED);
  683.             canvas.add(paragraph);
  684.  
  685.             pCanvas.rectangle(70, height-580, width-70, 1).setColor(C_HEADER_LIGHT_GRAY, true).fill(); // Header red stroke
  686.  
  687.  
  688.         } catch (Exception e) {
  689.             e.printStackTrace();
  690.         }
  691.     }
  692.  
  693.     /*
  694.         Draw summary intro page
  695.      */
  696.  
  697.     private void Draw_AnalysisIntro(Canvas canvas, ServletContext context, int pn) {
  698.         try {
  699.             float xMidOfPage = canvas.getRootArea().getWidth()/2;
  700.             float width = canvas.getRootArea().getWidth();
  701.             float height = canvas.getRootArea().getHeight();
  702.  
  703.  
  704.             /* Page decoration */
  705.             PdfCanvas pCanvas = canvas.getPdfCanvas();
  706.             pCanvas.rectangle(0,0, 60, height).setColor(C_HEADER_LIGHT_GRAY, true).fill();
  707.             pCanvas.roundRectangle(-100, (height/2)-25,width+50, 50, 10).setColor(new DeviceRgb(65,97,142), true).fill();
  708.             pCanvas.roundRectangle(-101, (height/2)-24,width+50, 48, 10).setColor(new DeviceRgb(35,67,112), true).fill();
  709.             pCanvas.rectangle(0, height-75, canvas.getRootArea().getWidth(), 8).setColor(CORPORATIVE_COLOR,true).fill(); // Header red stroke
  710.             AddImageCaching(pCanvas,ImageDataFactory.createPng(context.getResource(imagePath+"/image17.png")), 70, height-60, 40, false); // Background
  711.  
  712.             /* Header watermark*/
  713.             Paragraph paragraph = new Paragraph(HEADER_TEXT);
  714.             paragraph.setFontColor(ColorConstants.BLACK);
  715.             paragraph.setFontSize(13);
  716.             paragraph.setFixedPosition(width-140, height-60, 140);
  717.             paragraph.setTextAlignment(TextAlignment.CENTER);
  718.             canvas.add(paragraph);
  719.  
  720.             /* Page title */
  721.             Paragraph tParagraph = new Paragraph("ANÁLISIS: RESUMEN");
  722.             tParagraph.setFontColor(ColorConstants.WHITE);
  723.             tParagraph.setBold();
  724.             tParagraph.setFontSize(25);
  725.             tParagraph.setFixedPosition(0, (height/2)-20, width-50);
  726.             tParagraph.setTextAlignment(TextAlignment.CENTER);
  727.             canvas.add(tParagraph);
  728.  
  729.             /* Separation line */
  730.             pCanvas.rectangle(70,40, width-100, 1).setColor(C_HEADER_LIGHT_GRAY,true).fill(); // Header red stroke
  731.  
  732.             /* Page number */
  733.             Paragraph nParagraph = new Paragraph("Página | " + pn);
  734.             nParagraph.setFontColor(ColorConstants.DARK_GRAY);
  735.             nParagraph.setFontSize(11);
  736.             nParagraph.setFixedPosition(width-100, 15, 100);
  737.             nParagraph.setTextAlignment(TextAlignment.CENTER);
  738.             canvas.add(nParagraph);
  739.  
  740.         }catch (Exception e){
  741.             e.printStackTrace();
  742.         }
  743.     }
  744.  
  745.         /*
  746.         Draw detail intro page
  747.      */
  748.  
  749.     private void Draw_AnalysisIntroDetail(Canvas canvas, ServletContext context, int pn) {
  750.         try {
  751.             float xMidOfPage = canvas.getRootArea().getWidth()/2;
  752.             float width = canvas.getRootArea().getWidth();
  753.             float height = canvas.getRootArea().getHeight();
  754.  
  755.  
  756.             /* Page decoration */
  757.             PdfCanvas pCanvas = canvas.getPdfCanvas();
  758.             pCanvas.rectangle(0,0, 60, height).setColor(C_HEADER_LIGHT_GRAY, true).fill();
  759.             pCanvas.roundRectangle(-100, (height/2)-25,width+50, 50, 10).setColor(new DeviceRgb(65,97,142), true).fill();
  760.             pCanvas.roundRectangle(-101, (height/2)-24,width+50, 48, 10).setColor(new DeviceRgb(35,67,112), true).fill();
  761.             pCanvas.rectangle(0, height-75, canvas.getRootArea().getWidth(), 8).setColor(CORPORATIVE_COLOR,true).fill(); // Header red stroke
  762.             AddImageCaching(pCanvas,ImageDataFactory.createPng(context.getResource(imagePath+"/image17.png")), 70, height-60, 40, false); // Background
  763.  
  764.             /* Header watermark*/
  765.             Paragraph paragraph = new Paragraph(HEADER_TEXT);
  766.             paragraph.setFontColor(ColorConstants.BLACK);
  767.             paragraph.setFontSize(13);
  768.             paragraph.setFixedPosition(width-140, height-60, 140);
  769.             paragraph.setTextAlignment(TextAlignment.CENTER);
  770.             canvas.add(paragraph);
  771.  
  772.             /* Page title */
  773.             Paragraph tParagraph = new Paragraph("ANÁLISIS: DETALLE");
  774.             tParagraph.setFontColor(ColorConstants.WHITE);
  775.             tParagraph.setBold();
  776.             tParagraph.setFontSize(25);
  777.             tParagraph.setFixedPosition(0, (height/2)-20, width-50);
  778.             tParagraph.setTextAlignment(TextAlignment.CENTER);
  779.             canvas.add(tParagraph);
  780.  
  781.             /* Separation line */
  782.             pCanvas.rectangle(70,40, width-100, 1).setColor(C_HEADER_LIGHT_GRAY,true).fill(); // Header red stroke
  783.  
  784.             /* Page number */
  785.             Paragraph nParagraph = new Paragraph("Página | " + pn);
  786.             nParagraph.setFontColor(ColorConstants.DARK_GRAY);
  787.             nParagraph.setFontSize(11);
  788.             nParagraph.setFixedPosition(width-100, 15, 100);
  789.             nParagraph.setTextAlignment(TextAlignment.CENTER);
  790.             canvas.add(nParagraph);
  791.  
  792.         }catch (Exception e){
  793.             e.printStackTrace();
  794.         }
  795.     }
  796.  
  797.  
  798.     /*
  799.         Draw detail page 1
  800.      */
  801.  
  802.     private int Draw_DetailPage1(Canvas canvas, List<IBlockElement> htmlElements, java.util.List<Categoria> categories, Categoria category, ValorInforme phenotype, ServletContext context, int pn) {
  803.         try {
  804.             float width = canvas.getRootArea().getWidth();
  805.             float height = canvas.getRootArea().getHeight();
  806.             float xMidOfPage=((width+60)/2);
  807.             final DeviceRgb circleColor = new DeviceRgb(71,155,223);
  808.             Paragraph tParagraph;
  809.             PdfCanvas pCanvas = canvas.getPdfCanvas();
  810.             DrawGeneric_ContentPage(canvas, context, "", Integer.toString(pn), false);
  811.  
  812.             /* Image for the category */
  813.             Fenotipo rPhenotype = phenotype.getFenotipo();
  814.  
  815.             String url = Paths.get(context.getRealPath("/profile"), rPhenotype.getUrlFoto()).normalize().toString().trim().replace("\n","").replace("\r","").replace("\t","");
  816.             ImageData data = ImageDataFactory.create(url);
  817.             AddImageCaching(pCanvas,data, xMidOfPage-150, height-280, 300, false);
  818.  
  819.             /* Draw rectangle for every fenotype */
  820.             float y = height-405;
  821.             // Draw rounded rectangle
  822.             float rectWidth = categories.size()*50;
  823.             float xcatRect = xMidOfPage-(rectWidth/2);
  824.             float ycatRect = height-305;
  825.  
  826.             pCanvas.roundRectangle(xcatRect, ycatRect, rectWidth, 20, 3).setColor(C_HEADER_LIGHT_BORDER, true).fill();
  827.             tParagraph = new Paragraph(category.getNombre());
  828.             tParagraph.setFontColor(ColorConstants.WHITE);
  829.             tParagraph.setBold();
  830.             tParagraph.setFontSize(10);
  831.             tParagraph.setFixedPosition(xcatRect, ycatRect, rectWidth);
  832.             tParagraph.setHeight(20);
  833.             tParagraph.setTextAlignment(TextAlignment.CENTER);
  834.             tParagraph.setVerticalAlignment(VerticalAlignment.MIDDLE);
  835.             canvas.add(tParagraph);
  836.  
  837.             xcatRect = drawCategories(canvas, categories, category, pCanvas, ycatRect, xcatRect);
  838.  
  839.             DeviceRgb rectColor = null;
  840.             String text = "";
  841.             switch (phenotype.getSemResumen()){
  842.                 case 0: // Green
  843.                     rectColor = new DeviceRgb(76,175,80);
  844.                     text = "Favorable";
  845.                     break;
  846.  
  847.                 case 1: // Orange
  848.                     rectColor = new DeviceRgb(255,152,0);
  849.                     text = "Normal";
  850.                     break;
  851.  
  852.                 case 2: // Red
  853.                     rectColor = new DeviceRgb(244,67,54);
  854.                     text = "Desfavorable";
  855.                     break;
  856.             }
  857.  
  858.             if (rectColor != null) {
  859.                 // Text bar
  860.                 pCanvas.roundRectangle(xcatRect-(categories.size()*50), y, (categories.size()*50), 40, 3).setColor(rectColor, true).fill();
  861.  
  862.                 // Text
  863.                 tParagraph = new Paragraph(phenotype.getFenotipo().getNombre().replace("\n", "").replace("\r", ""));
  864.                 tParagraph.setFontColor(ColorConstants.WHITE);
  865.                 tParagraph.setBold();
  866.                 tParagraph.setFontSize(10);
  867.                 tParagraph.setFixedPosition(xcatRect-(categories.size()*50), y, (categories.size()*50));
  868.                 tParagraph.setHeight(40);
  869.                 tParagraph.setTextAlignment(TextAlignment.CENTER);
  870.                 //tParagraph.setBackgroundColor(ColorConstants.BLUE);
  871.                 tParagraph.setVerticalAlignment(VerticalAlignment.MIDDLE);
  872.                 canvas.add(tParagraph);
  873.  
  874.                 // Percentage gradient bar
  875.                 ImageData rb_data = ImageDataFactory.createPng(context.getResource(imagePath+"/bar_resource.png"));
  876.                 AddImageCaching(pCanvas,rb_data, 120, y-50, 150, false);
  877.  
  878.                 // User icon
  879.                 ImageData uicon = ImageDataFactory.createPng(context.getResource(imagePath+"/user.png"));
  880.                 AddImageCaching(pCanvas,uicon, 120 + (phenotype.getBarraUsuario()*1.5f), y-50, 15, false);
  881.  
  882.                 // Rest of users icon
  883.                 ImageData ruicon = ImageDataFactory.createPng(context.getResource(imagePath+"/restUsers.png"));
  884.                 AddImageCaching(pCanvas,ruicon, 120 + (phenotype.getBarraPoblacion()*1.5f), y-50, 15, false);
  885.  
  886.                 pCanvas.roundRectangle(120, y-90, 150, 30, 15).setColor(rectColor, true).fill();
  887.  
  888.                 tParagraph = new Paragraph(text);
  889.                 tParagraph.setFontColor(ColorConstants.WHITE);
  890.                 tParagraph.setBold();
  891.                 tParagraph.setFontSize(16);
  892.                 tParagraph.setFixedPosition(120, y-90, 150);
  893.                 tParagraph.setHeight(30);
  894.                 tParagraph.setTextAlignment(TextAlignment.CENTER);
  895.                 //tParagraph.setBackgroundColor(ColorConstants.BLUE);
  896.                 tParagraph.setVerticalAlignment(VerticalAlignment.MIDDLE);
  897.                 canvas.add(tParagraph);
  898.  
  899.                 // Circular progress bar
  900.                 y-=100;
  901.                 float xarg = width-160;
  902.                 float widtharg = 80;
  903.  
  904.                 // Draw the internal circle
  905.                 pCanvas.circle(xarg+widtharg/2, y+widtharg/2, (widtharg/2)).setColor(ColorConstants.BLACK,false).stroke();
  906.                 pCanvas.circle(xarg+widtharg/2, y+widtharg/2, (widtharg/2)-(widtharg*0.1)).setColor(ColorConstants.BLACK,false).stroke();
  907.  
  908.                 pCanvas.arc(xarg+(widtharg*0.1f)/2, y+(widtharg*0.1f)/2, xarg+widtharg-(widtharg*0.1)/2,y+widtharg-(widtharg*0.1)/2, 90, phenotype.getPercentil()*(-3.6)).setLineWidth(widtharg*0.1f).setStrokeColor(circleColor).stroke();
  909.                 pCanvas.setLineWidth(1);
  910.  
  911.                 // Draw the text for the percentage
  912.                 tParagraph = new Paragraph(phenotype.getPercentil().toString()+"%");
  913.                 tParagraph.setFontColor(ColorConstants.BLACK);
  914.                 tParagraph.setBold();
  915.                 tParagraph.setFontSize(20);
  916.                 tParagraph.setFixedPosition(xarg+1, y+2, widtharg);
  917.                 tParagraph.setHeight(widtharg);
  918.                 tParagraph.setTextAlignment(TextAlignment.CENTER);
  919.                 tParagraph.setVerticalAlignment(VerticalAlignment.MIDDLE);
  920.                 canvas.add(tParagraph);
  921.  
  922.                 Integer separatorNdx = GetSectionSeparatorIndex(htmlElements);
  923.                 Integer ndx = DrawHtmlElements(canvas, htmlElements, width-20, height, 80, height-550, separatorNdx);
  924.                 if (ndx != null) return ndx;
  925.  
  926.             }
  927.  
  928.  
  929.         } catch (Exception e) {
  930.             e.printStackTrace();
  931.         }
  932.         return -1;
  933.     }
  934.  
  935.     protected void DrawGenRow(Canvas cv, float x, float y, DeviceRgb color, float percentage){
  936.         // Not necessary for the time being
  937.         throw new NotImplementedException();
  938.     }
  939.  
  940.     protected Integer DrawHtmlElements(Canvas canvas, List<IBlockElement> htmlElements, float width, float height, float leftMargin, float y) {
  941.         return DrawHtmlElements(canvas, htmlElements, width, height, leftMargin, y, -1);
  942.     }
  943.  
  944.     protected Integer DrawHtmlElements(Canvas canvas, List<IBlockElement> htmlElements, float width, float height, float leftMargin, float y, int breakOnNdx) {
  945.         int ndx = 0;
  946.         float lastY = y;
  947.         canvas.setFontColor(ColorConstants.BLACK, 1);
  948.         for (IBlockElement block : htmlElements)
  949.         {
  950.             BlockElement par = ((BlockElement) block);
  951.             par.setRelativePosition(leftMargin, height-lastY-40, width - leftMargin, 0);
  952.             par.setWidth(width-leftMargin);
  953.             CorrectBulletPointDrift(width, leftMargin, block);
  954.             LayoutResult result = block.createRendererSubTree()
  955.                     .setParent(canvas.getRenderer()).layout(new LayoutContext(new LayoutArea(1, new Rectangle(100, 1000))));
  956.             if (ndx > 0 && (y-result.getOccupiedArea().getBBox().getHeight() < 0 || ndx == breakOnNdx)) // This makes that if a block is bigger than a page, inserts without breaking into another one
  957.             {
  958.                 return ndx;
  959.             }
  960.             if (!CheckIfBlockEmpty(par)) {
  961.                 y -= result.getOccupiedArea().getBBox().getHeight();
  962.                 if (block instanceof GenPdfRow) // Render a gen
  963.                 {
  964.                     GenPdfRow row =  ((GenPdfRow)block);
  965.                     DrawGenRow(canvas,width-30, y+(result.getOccupiedArea().getBBox().getHeight()), row.getGenColor(), row.getPercentage());
  966.                 }
  967.                 canvas.add(par);
  968.             }
  969.             ndx++;
  970.         }
  971.         return ndx;
  972.     }
  973.  
  974.     protected void CorrectBulletPointDrift(float width, float margin, IElement e) {
  975.         if (e instanceof Paragraph && ((Paragraph) e).getChildren().size() > 0)
  976.         {
  977.             Object posText = ((Paragraph) e).getChildren().get(0);
  978.             if (posText instanceof Text){
  979.                 if (((Text) posText).getText().equals("•") || ((Text) posText).getText().equals("·")){
  980.                     UnitValue correction = ((Paragraph) e).getProperty(44);
  981.                     ((Paragraph)e).setWidth(width-margin-((int)correction.getValue()));
  982.                 }
  983.             }
  984.         }
  985.     }
  986.  
  987.     protected List<IBlockElement> getDetailPhenotypeElements(List<IBlockElement> elements, ValorInforme phenotype)
  988.     {
  989.         try {
  990.             Fenotipo rPhenotype = phenotype.getFenotipo();
  991.             if (2 - phenotype.getSemResumen() >= 0) {
  992.                 java.util.List<IElement> elementList = HtmlConverter.convertToElements(getPhenotypeDescription(phenotype, rPhenotype));
  993.                 for (IElement e : elementList)
  994.                     if (e instanceof IBlockElement) {
  995.                         if (e instanceof Paragraph ||
  996.                                 e instanceof Div    ) {
  997.                             elements.add((IBlockElement) e);
  998.                         }
  999.                     }
  1000.  
  1001.             }
  1002.             return elements;
  1003.         } catch (Exception e) {
  1004.             return null;
  1005.         }
  1006.     }
  1007.  
  1008.     protected String getPhenotypeDescription(ValorInforme phenotype, Fenotipo rPhenotype) {
  1009.         String description = "";
  1010.         if (rPhenotype.getDifDescVerde() != null && rPhenotype.getDifDescAmarillo() != null){
  1011.             Float difference = phenotype.getBarraUsuario()-phenotype.getBarraPoblacion();
  1012.             if (difference < rPhenotype.getDifDescVerde()) description = rPhenotype.getDescVerde();
  1013.             else if (difference < rPhenotype.getDifDescAmarillo()) description = rPhenotype.getDescAmarillo();
  1014.             else description = rPhenotype.getDescRojo();
  1015.         }
  1016.         return description;
  1017.     }
  1018.  
  1019.     /*
  1020.         Draw detail page 2
  1021.      */
  1022.  
  1023.     private int Draw_DetailPage2(Canvas canvas, java.util.List<Categoria> categories, Categoria category, List<IBlockElement> htmlElements, ServletContext context, int pn) {
  1024.         try {
  1025.             float width = canvas.getRootArea().getWidth();
  1026.             float height = canvas.getRootArea().getHeight();
  1027.             float xMidOfPage=((width+60)/2);
  1028.             Paragraph tParagraph;
  1029.             PdfCanvas pCanvas = canvas.getPdfCanvas();
  1030.             DrawGeneric_ContentPage(canvas, context, "", Integer.toString(pn), false);
  1031.  
  1032.             // Draw rounded rectangle
  1033.             float rectWidth = categories.size()*50;
  1034.             float xcatRect = xMidOfPage-(rectWidth/2);
  1035.             float ycatRect = height-110;
  1036.  
  1037.             pCanvas.roundRectangle(xcatRect, ycatRect, rectWidth, 20, 3).setColor(C_HEADER_LIGHT_BORDER, true).fill();
  1038.             tParagraph = new Paragraph(category.getNombre());
  1039.             tParagraph.setFontColor(ColorConstants.WHITE);
  1040.             tParagraph.setBold();
  1041.             tParagraph.setFontSize(10);
  1042.             tParagraph.setFixedPosition(xcatRect, ycatRect, rectWidth);
  1043.             tParagraph.setHeight(20);
  1044.             tParagraph.setTextAlignment(TextAlignment.CENTER);
  1045.             tParagraph.setVerticalAlignment(VerticalAlignment.MIDDLE);
  1046.             canvas.add(tParagraph);
  1047.  
  1048.             drawCategories(canvas, categories, category, pCanvas, ycatRect, xcatRect);
  1049.  
  1050.             Integer ndx = DrawHtmlElements(canvas, htmlElements, width-20, height, 80, height-200);
  1051.             return ndx;
  1052.  
  1053.         } catch (Exception e) {
  1054.             e.printStackTrace();
  1055.         }
  1056.         return -1;
  1057.     }
  1058.  
  1059.     private float drawCategories(Canvas canvas, List<Categoria> categories, Categoria category, PdfCanvas pCanvas, float ycatRect, float xrect) {
  1060.         Paragraph tParagraph;
  1061.         for (Categoria ct : categories) {
  1062.             pCanvas.roundRectangle(xrect, ycatRect - (ct == category ? 45 : 48), 50, 50, 3).setColor(ct == category ? C_HEADER_LIGHT_BORDER : C_HEADER_LIGHT_GRAY, true).fill();
  1063.             tParagraph = new Paragraph(ct.getNombre().substring(0, 1).toUpperCase());
  1064.             tParagraph.setFontColor(ColorConstants.BLACK);
  1065.             tParagraph.setBold();
  1066.             tParagraph.setFontSize(25);
  1067.             tParagraph.setFixedPosition(xrect, ycatRect - (ct == category ? 45 : 48), 50);
  1068.             tParagraph.setHeight(50);
  1069.             tParagraph.setTextAlignment(TextAlignment.CENTER);
  1070.             tParagraph.setVerticalAlignment(VerticalAlignment.MIDDLE);
  1071.             canvas.add(tParagraph);
  1072.             xrect += 50;
  1073.         }
  1074.         return xrect;
  1075.     }
  1076.  
  1077.  
  1078.  
  1079.     /* Utils */
  1080.  
  1081.     protected Canvas CreateCanvasFromDocument(PdfDocument document){
  1082.         PdfPage page = document.addNewPage();
  1083.         PdfCanvas pdfCanvas = new PdfCanvas(page);
  1084.         return new Canvas(pdfCanvas, document, page.getPageSize());
  1085.     }
  1086.  
  1087.     private Integer GetSectionSeparatorIndex(List<IBlockElement> e)
  1088.     {
  1089.         Integer ndx = 0;
  1090.         for (IBlockElement bl : e)
  1091.         {
  1092.             if (bl instanceof Paragraph)
  1093.             {
  1094.                 if (((Paragraph) bl).getChildren().size() > 0) {
  1095.                     Text tx = (Text) ((Paragraph) bl).getChildren().get(0);
  1096.                     String txChars = tx.getText().trim();
  1097.                     if (txChars.startsWith("¿POR QUÉ") || txChars.startsWith("WHY")) {
  1098.                         return ndx;
  1099.                     }
  1100.                 }
  1101.             }
  1102.             ndx++;
  1103.         }
  1104.         return -1;
  1105.     }
  1106.  
  1107.     /* Wrapper helping iText caching the images */
  1108.  
  1109.     protected PdfXObject AddImageCaching(PdfCanvas canvas, ImageData image, float x, float y, float width, boolean asInline)
  1110.     {
  1111.         if (HashedPdfXObjectCache == null)
  1112.         {
  1113.             HashedPdfXObjectCache = new HashMap<>();
  1114.         }
  1115.  
  1116.         PdfXObject img = HashedPdfXObjectCache.get(image.hashCode());
  1117.         if (img == null)
  1118.         {
  1119.             img = canvas.addImage(image, x, y, width, asInline);
  1120.             HashedPdfXObjectCache.put(image.hashCode(), img);
  1121.         }
  1122.         else // Ignore asInLine
  1123.         {
  1124.             canvas.addXObject(img, x, y, width);
  1125.         }
  1126.         return img;
  1127.     }
  1128.  
  1129.     public void GeneratorReportFromReportId(ServletOutputStream byteArrayOutputStream, Servlet servlet, ServletContext context, Long reportId){
  1130.  
  1131.         /* Configure the report */
  1132.  
  1133.         ReportManager manager = new ReportManager(servlet);
  1134.         Informe report = manager.getReportbyId(reportId);
  1135.         java.util.List<Categoria> categories = manager.getReportCategories(report.getIdInforme());
  1136.         PdfWriter writer = new PdfWriter(byteArrayOutputStream);
  1137.         PdfDocument pdfReport = new PdfDocument(writer);
  1138.         Document doc = new Document(pdfReport);
  1139.         pdfReport.setDefaultPageSize(PageSize.A4);
  1140.  
  1141.         /* Start with the pages */
  1142.  
  1143.         int pageNumber = 1;
  1144.  
  1145.         // Header
  1146.         Canvas headerPage = CreateCanvasFromDocument(pdfReport);
  1147.         Draw_HeaderPage(headerPage, report, context);
  1148.  
  1149.         // Index
  1150.         Canvas indexPage = CreateCanvasFromDocument(pdfReport);
  1151.         Draw_IndexPage(indexPage, categories, context,++pageNumber);
  1152.  
  1153.         // Intro Page 1
  1154.         Canvas introPage = CreateCanvasFromDocument(pdfReport);
  1155.         Draw_IntroPage(introPage, context,++pageNumber);
  1156.  
  1157.  
  1158.         // Intro Page 2
  1159.         Canvas introPage2 = CreateCanvasFromDocument(pdfReport);
  1160.         Draw_IntroPage2(introPage2, context,++pageNumber);
  1161.  
  1162.         // Analysis intro page
  1163.         Canvas analysisIntro = CreateCanvasFromDocument(pdfReport);
  1164.         Draw_AnalysisIntro(analysisIntro,context, ++pageNumber);
  1165.  
  1166.  
  1167.         /* DYNAMIC CONTENT STARTS HERE */
  1168.  
  1169.         // Use this list for caching the 'ValorInforme' query
  1170.         java.util.Map<Categoria, java.util.List<ValorInforme>> valorInformes = new java.util.HashMap<>();
  1171.  
  1172.         for (Categoria category: categories){
  1173.             Canvas catPage = CreateCanvasFromDocument(pdfReport);
  1174.             java.util.List<ValorInforme> vI = manager.getValoresInformeCategoryReport(report.getIdInforme(), category.getId());
  1175.             valorInformes.put(category, vI);
  1176.             pageNumber = Draw_CategoryPage(pdfReport, catPage, categories, category, vI, manager, context, ++pageNumber);
  1177.         }
  1178.  
  1179.         // Analysis intro page
  1180.         Canvas analysisDetailIntro = CreateCanvasFromDocument(pdfReport);
  1181.         Draw_AnalysisIntroDetail(analysisDetailIntro,context, ++pageNumber);
  1182.  
  1183.         List<IBlockElement> htmlElements = new LinkedList<>();
  1184.         for (Categoria category: categories){
  1185.             java.util.List<ValorInforme> vInforme = valorInformes.get(category);
  1186.             for (ValorInforme vi : vInforme){
  1187.                 if (vi.getBarraUsuario() == null) continue;
  1188.                 Canvas dtlPage1 = CreateCanvasFromDocument(pdfReport);
  1189.  
  1190.                 getDetailPhenotypeElements(htmlElements, vi);
  1191.                 int restNdx = 0;
  1192.                 restNdx = Draw_DetailPage1(dtlPage1,htmlElements, categories, category, vi, context, pageNumber);
  1193.                 while (restNdx >= 0)
  1194.                 {
  1195.                     htmlElements = htmlElements.subList(restNdx, htmlElements.size());
  1196.                     if (!CheckIfBlocksEmpty(htmlElements)) {
  1197.                         Canvas dtlPage2 = CreateCanvasFromDocument(pdfReport);
  1198.                         restNdx = Draw_DetailPage2(dtlPage2, categories, category, htmlElements, context, ++pageNumber);
  1199.                     }
  1200.                     else
  1201.                     {
  1202.                         restNdx = -1;
  1203.                     }
  1204.                 }
  1205.                 htmlElements.clear();
  1206.             }
  1207.         }
  1208.  
  1209.         /* DYNAMIC CONTENT ENDS HERE */
  1210.  
  1211.         // Last page
  1212.         Canvas backPage = CreateCanvasFromDocument(pdfReport);
  1213.         Draw_BackPage(backPage, report, context);
  1214.  
  1215.         pdfReport.close();
  1216.  
  1217.         try {
  1218.             byteArrayOutputStream.flush();
  1219.         }catch (Exception e){
  1220.             e.printStackTrace();
  1221.         }
  1222.     }
  1223. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement