0

Hola comunidad gracias por su apoyo de antemano, estoy implementando itext7 para generar documentación, añadí un constructor con mis métodos Setters y Getters. Cuando almaceno mis argumentos dentro del objeto lo mando a agrego en un ArrayList para imprimirlo dentro de mi documento PDF o consola, el problema es que solo almacena el ultimo objeto dentro de mi ArrayList y este al ejecutarse en mi for me imprime una y otra vez el mismo en vez de añadir la secuencia de objetos, alguien sabra si es por el tipo de Arraylist o lo estoy usando mal ya que mi ciclo for no es el problema

public class Pdf {
    public static final String path = ".Documentation/Evidence.pdf";
    public static final String QA = "./QA.jpg";
    public static java.util.List<ArchivoTexto> listaPdf = new ArrayList<>();

    public static void main(String[] args) throws Exception {
        
        File file = new File(path);
        file.getParentFile().mkdirs();

        java.util.List<ArchivoTexto> listaPdf = new ArrayList<ArchivoTexto>();

        ArchivoTexto caso1 = new ArchivoTexto("Prueba 1 de app", "1DWwv bgf");
        listaPdf.add(caso1);

        ArchivoTexto caso2 = new ArchivoTexto("Execucion 2 de app", "2");
        listaPdf.add(caso2);

        Documentation(path);
    }

    public static void Documentation(String dest) throws Exception {


        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
        Document document = new Document(pdfDoc);

        //Static name tableHeader
        float[] columnWidths = {1, 5, 2};
        Table table = new Table(UnitValue.createPercentArray(columnWidths));

        for (int i = 1; i <= 2; i++) {
            table.addCell(new Cell().setTextAlignment(TextAlignment.CENTER).add(new Paragraph(String.valueOf(i))));
            table.addCell(new Cell().setTextAlignment(TextAlignment.CENTER).add(new Paragraph(String.valueOf(ArchivoTexto.getDescription()))));
            table.addCell(new Cell().setTextAlignment(TextAlignment.CENTER).add(new Paragraph(String.valueOf(ArchivoTexto.getExpected()))));
        }

        //Number of pages
        int numberOfPages = pdfDoc.getNumberOfPages();
        for (int i = 1; i <= numberOfPages; i++) {

        document.add(table);

        document.close();
    }
}

public class ArchivoTexto {

    private static String description;
    private static String expected;

    public ArchivoTexto(String description, String expected){
        this.description = description;
        this.expected = expected;
    }

    public static String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public static String getExpected() {
        return expected;
    }

    public void setExpected(String expected) {
        this.expected = expected;
    }
}

Consola PDF

2 respuestas 2

0

En las siguientes líneas, estás accediendo a los atributos del objeto ArchivoTexto directamente.

Si quieres acceder a los valores del array, debes pasar el array como parámetro en tu método "Documentation"

public static void Documentation(String dest, List<ArchivoTexto> listaPdf)

Y en el for donde mapeas la información debes iterar el array y acceder a los atributos del objeto, utilizando sus respectivos métodos de acceso:

for (int i = 0; i< listaPdf.size(); i++) {
    table.addCell(new Cell().setTextAlignment(TextAlignment.CENTER).add(new Paragraph(String.valueOf(i+1))));
    table.addCell(new Cell().setTextAlignment(TextAlignment.CENTER).add(new Paragraph(String.valueOf(listaPdf.get(i).getDescription()))));
    table.addCell(new Cell().setTextAlignment(TextAlignment.CENTER).add(new Paragraph(String.valueOf(listaPdf.get(i).getExpected()))));
}

En el main, debes invocar el método Documentation de la siguiente forma

  public static void main(String[] args) throws Exception {
        
        File file = new File(path);
        file.getParentFile().mkdirs();

        java.util.List<ArchivoTexto> listaPdf = new ArrayList<ArchivoTexto>();

        ArchivoTexto caso1 = new ArchivoTexto("Prueba 1 de app", "1DWwv bgf");
        listaPdf.add(caso1);

        ArchivoTexto caso2 = new ArchivoTexto("Execucion 2 de app", "2");
        listaPdf.add(caso2);

        Documentation(path, listaPdf);
    }

Como recomendación, trabaja un poco mejor el principio de encapsulamiento:

Principio de encapsulamiento

Quita el label static a los atributos y métodos de la clase ArchivoTexto.

Espero te haya servido de ayuda.

2
  • Hola a lo que mencionas lo intente pero se genera un conflicto con el dentro des mis atributos ya que el la linea del main Documentation(path); //genera un error en los atributos, en este caso "dest" es String y "list" es un Array, y me pide cambiar "path" como Array. He solucionado el problema de almacenamiento dejándolo sin Static en las el variables, constructor y métodos de encapsulamiento puedo hacer impresión de los argumentos desde la consola pero el problema es de ITEXT 7 ya que no añade el array dentro de las celdas el 3 nov. 2020 a las 21:57
  • @IsraelSanz He modificado la respuesta para que te guíes un poco. El problema de como lo estás implementando y que solo te trae el último registro, se debe a que estás llamando directamente a la clase ArchivoTexto y estás accediendo directamente a sus atributos, por ende solo traerá el último valor asignado, que corresponde al que declaras al hacer un new ArchivoTexto el 3 nov. 2020 a las 22:21
0

Listo he solucionado mi conflicto eliminando de las variables y métodos getters el "static", dentro de mi main aumentar un objeto sin argumento para que en el for comenzara a partir del 1 y menos que mi ArrayList.

 public class Pdf {
        public static final String path = ".Documentation/Evidence.pdf";
    
        public static java.util.List<ArchivoTexto> listaPdf = new ArrayList<>();
    
        public static void main(String[] args) throws Exception {
    
            File file = new File(path);
            file.getParentFile().mkdirs();
    
            ArchivoTexto caso1 = new ArchivoTexto("Prueba 1 de app", "1DWwv bgf");
            listaPdf.add(caso1);
    
            ArchivoTexto caso2 = new ArchivoTexto("Execucion 2 de app", "2");
            listaPdf.add(caso2);
    
            ArchivoTexto caso3 = new ArchivoTexto("Execucion 3 de app", "2ref45rtcf");
            listaPdf.add(caso3);
    
            ArchivoTexto caso4 = new ArchivoTexto("Execucion 4 de app", "2cadfv ");
            listaPdf.add(caso4);
    
            ArchivoTexto caso5 = new ArchivoTexto("Execucion 5 de app", "22315rtfcq3 ");
            listaPdf.add(caso5);

/*
Utilizo la siguientes lineas para que me imprima el valor de mi Array llamándolo desde el ArrayList
*/

            //Getting Iterator
            Iterator itr=listaPdf.iterator();
            //traversing elements of ArrayList object
            while(((Iterator<?>) itr).hasNext()){
                ArchivoTexto st=(ArchivoTexto) ((Iterator<?>) itr).next();
                System.out.println(st.getDescription()+" "+st.getExpected());
            }
    
            System.out.println("Hay " + listaPdf.size() + " renglones");
    
            Documentation(path);
        }
         public static void Documentation(String dest) throws Exception {
    
    
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
            Document document = new Document(pdfDoc);
    
            //Static name tableHeader
            float[] columnWidths = {1, 5, 2};
            Table table = new Table(UnitValue.createPercentArray(columnWidths));
    
            for (int i = 1; i < listaPdf.size(); i++) {
                table.addCell(new Cell().setTextAlignment(TextAlignment.CENTER).add(new Paragraph(String.valueOf(i))));
                table.addCell(new Cell().setTextAlignment(TextAlignment.CENTER).add(new Paragraph(String.valueOf(listaPdf.get(i).getDescription()))));
                table.addCell(new Cell().setTextAlignment(TextAlignment.CENTER).add(new Paragraph(String.valueOf(listaPdf.get(i).getExpected()))));
             }

            document.add(table);
    
            document.close();
        }
    }
            package Documentation;
    
    public class ArchivoTexto {
    
        private String description;
        private String expected;
    
        public ArchivoTexto(String description, String expected){
            this.description = description;
            this.expected = expected;
        }
    
        public String getDescription() {
            return this.description;
        }
    
        public void setDescription(String description) {
            this.description = description;
        }
    
        public String getExpected() {
            return this.expected;
        }
    
        public void setExpected(String expected) {
            this.expected = expected;
        }
    }

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.