Example usage for com.lowagie.text.pdf PdfPTable setWidthPercentage

List of usage examples for com.lowagie.text.pdf PdfPTable setWidthPercentage

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfPTable setWidthPercentage.

Prototype

public void setWidthPercentage(float widthPercentage) 

Source Link

Document

Sets the width percentage that the table will occupy in the page.

Usage

From source file:pruebareportes.rptTardC.java

public PdfPTable crearTabla(List<String> dnis, Date fechaInicio, Date fechaFin) throws DocumentException {
    /**/*from w  ww.  j  av  a 2  s .c o  m*/
     * Procesamiento para info para generar tablas
     */
    List<RegistroAsistencia> registros = rg.buscarXEmpleadoXFecha1(dnis, fechaInicio, fechaFin);
    Calendar fechaInicioC = Calendar.getInstance();
    Calendar fechaFinC = Calendar.getInstance();
    fechaInicioC.setTime(fechaInicio);
    fechaFinC.setTime(fechaFin);

    int diaMesInicio, diaMesFin;
    diaMesInicio = fechaInicioC.get(Calendar.DAY_OF_MONTH);
    diaMesFin = fechaFinC.get(Calendar.DAY_OF_MONTH);
    //Definir numero de columnas de dias
    ArrayList<Integer> listaInt = new ArrayList<Integer>();
    Calendar fechaRegistro = Calendar.getInstance();
    for (RegistroAsistencia registro : registros) {
        fechaRegistro.setTime(registro.getFecha());
        Integer diaRegistro = fechaRegistro.get(Calendar.DAY_OF_MONTH);
        if (listaInt.contains(diaRegistro) != true) {
            if (diaRegistro >= diaMesInicio && diaRegistro <= diaMesFin) {
                listaInt.add(diaRegistro);
            }
        }
    }
    //Ordenamos arraylist
    int indice, menor, aux;
    for (int i = 0; i < listaInt.size(); i++) {
        menor = listaInt.get(i);
        indice = i;
        aux = 0;
        for (int j = i + 1; j < listaInt.size(); j++) {
            aux = listaInt.get(j);
            indice = aux < menor ? j : indice;
            menor = aux < menor ? aux : menor;
        }
        listaInt.set(indice, listaInt.get(i));
        listaInt.set(i, menor);
    }
    /**
     * Procesamiento para elaborar tabla con datos
     */
    int nroColumnas = listaInt.size() + 2;
    PdfPTable tabla = new PdfPTable(nroColumnas);
    tabla.setWidthPercentage(100);
    //Asignamos los tamaos a las columnas
    int[] widthColumna = new int[nroColumnas];
    for (int i = 0; i < nroColumnas; i++) {
        if (i == 0) {
            widthColumna[i] = 6;
        } else if (i == (nroColumnas - 1)) {
            widthColumna[i] = 2;
        } else {
            widthColumna[i] = 1;
        }
    }
    tabla.setWidths(widthColumna);
    //Definimos celdas iniciales
    Font fontCabecera = new Font(Font.TIMES_ROMAN, 10, Font.BOLD);
    Font fontCelda = new Font(Font.TIMES_ROMAN, 9);
    PdfPCell h1 = new PdfPCell(new Phrase("Nombre del empleado", fontCabecera));
    h1.setHorizontalAlignment(3);
    h1.setGrayFill(0.7f);
    h1.setRowspan(2);
    h1.setColspan(1);
    tabla.addCell(h1);

    PdfPCell h2 = new PdfPCell(new Phrase("Das Hbiles", fontCabecera));
    h2.setHorizontalAlignment(1);
    h2.setGrayFill(0.7f);
    h2.setColspan(nroColumnas - 2);
    tabla.addCell(h2);

    PdfPCell h3 = new PdfPCell(new Phrase("Total (minutos)", fontCabecera));
    h3.setHorizontalAlignment(3);
    h3.setGrayFill(0.7f);
    h3.setColspan(1);
    h3.setRowspan(2);
    tabla.addCell(h3);

    PdfPCell diaColumna = new PdfPCell();
    for (int i = 0; i < (nroColumnas - 2); i++) {
        String celda = (listaInt.get(i).toString());
        diaColumna.setPhrase(new Phrase(celda, fontCabecera));
        diaColumna.setHorizontalAlignment(1);
        tabla.addCell(diaColumna);
    }
    Calendar cal = Calendar.getInstance();
    List<Integer> conteoDias = new ArrayList<Integer>();

    for (int i = 0; i < dnis.size(); i++) {

        List<Empleado> listaEmpleado = new ArrayList<Empleado>();
        listaEmpleado = em.buscarXPatron(dnis.get(i));
        Empleado empleado = new Empleado();
        empleado = listaEmpleado.get(0);
        BigDecimal totalTardanza = new BigDecimal(0.00);
        PdfPCell celdaNombre = new PdfPCell(new Phrase(empleado.getApellidoPaterno() + " "
                + empleado.getApellidoMaterno() + " " + empleado.getNombre(), fontCelda));
        celdaNombre.setHorizontalAlignment(0);
        tabla.addCell(celdaNombre);
        List<RegistroAsistencia> registrosDni = rg.buscarXEmpleadoXFecha2(dnis.get(i), fechaInicio, fechaFin);
        System.out.println("Numero de registros: " + registrosDni.size());
        if (!registrosDni.isEmpty()) {
        }
        for (RegistroAsistencia registro : registrosDni) {
            cal.setTime(registro.getFecha());
            for (int j = 0; j < listaInt.size(); j++) {
                if (cal.get(Calendar.DAY_OF_MONTH) == listaInt.get(j)) {
                    if (registro.getMinTardanza() != null) {
                        int numero = registro.getMinTardanza().intValue();
                        String celda = "" + numero;
                        celdaNombre.setPhrase(new Phrase(celda, fontCelda));
                        celdaNombre.setHorizontalAlignment(1);
                        tabla.addCell(celdaNombre);
                        totalTardanza = totalTardanza.add(registro.getMinTardanza());
                    } else {
                        String celda = "0.0";
                        celdaNombre.setPhrase(new Phrase(celda, fontCelda));
                        celdaNombre.setHorizontalAlignment(1);
                        tabla.addCell(celdaNombre);
                    }
                    conteoDias.add(listaInt.get(j));
                    break;
                } else {
                    if (conteoDias.contains(listaInt.get(j))) {

                    } else {
                        String celda = "n.r";
                        celdaNombre.setPhrase(new Phrase(celda, fontCelda));
                        celdaNombre.setHorizontalAlignment(1);
                        tabla.addCell(celdaNombre);
                        conteoDias.add(listaInt.get(j));
                    }
                }
            }
        }
        if (registrosDni.size() < (nroColumnas - 2)) {
            int dfNumRegistros = (nroColumnas - 2) - registrosDni.size();
            for (int j = 0; j < dfNumRegistros; j++) {
                String celda = "n.r";
                celdaNombre.setPhrase(new Phrase(celda, fontCelda));
                celdaNombre.setHorizontalAlignment(1);
                tabla.addCell(celdaNombre);
            }
        }

        System.out.println("ConteoDias: " + conteoDias.size());
        System.out.println("Total tardanzas: " + totalTardanza);
        conteoDias.clear();
        String tardanzaTotal = totalTardanza.toString();
        celdaNombre.setPhrase(new Phrase(tardanzaTotal, fontCelda));
        celdaNombre.setHorizontalAlignment(1);
        tabla.addCell(celdaNombre);
    }
    return tabla;
}

From source file:pruebareportes.rptTardCx.java

public PdfPTable crearTabla(List<String> dnis, Date fechaInicio, Date fechaFin) throws DocumentException {
    /**/*www .j a  v  a 2  s  .c  o m*/
     * Procesamiento para info para generar tablas
     */
    //List<RegistroAsistencia> registros = rg.buscarXEmpleadoXFecha1(dnis, fechaInicio, fechaFin);
    Calendar fechaInicioC = Calendar.getInstance();
    Calendar fechaFinC = Calendar.getInstance();
    fechaInicioC.setTime(fechaInicio);
    fechaFinC.setTime(fechaFin);

    int diaMesInicio, diaMesFin;
    diaMesInicio = fechaInicioC.get(Calendar.DAY_OF_MONTH);
    diaMesFin = fechaFinC.get(Calendar.DAY_OF_MONTH);

    // Dias contados desde un inicio y fin fecha
    ArrayList<Integer> listaInt = new ArrayList<>();
    for (int i = diaMesInicio; i <= diaMesFin; i++) {
        listaInt.add(i);
    }
    //Ordenamos arraylist
    int indice, menor, aux;
    for (int i = 0; i < listaInt.size(); i++) {
        menor = listaInt.get(i);
        indice = i;
        aux = 0;
        for (int j = i + 1; j < listaInt.size(); j++) {
            aux = listaInt.get(j);
            indice = aux < menor ? j : indice;
            menor = aux < menor ? aux : menor;
        }
        listaInt.set(indice, listaInt.get(i));
        listaInt.set(i, menor);
    }
    /**
     * Procesamiento para elaborar tabla con datos
     */
    //agrege una columna mas (Descuento sin goce)
    int nroColumnas = listaInt.size() + 3;
    PdfPTable tabla = new PdfPTable(nroColumnas);
    tabla.setWidthPercentage(100);
    //Asignamos los tamaos a las columnas 
    //MOdifique para tomar en cuenta la nueva columna de dewscuento
    int[] widthColumna = new int[nroColumnas];
    for (int i = 0; i < nroColumnas; i++) {
        if (i == 0) {
            widthColumna[i] = 6;
        } else if (i == (nroColumnas - 1) || i == (nroColumnas - 2)) {
            widthColumna[i] = 2;
        } else {
            widthColumna[i] = 1;
        }
    }
    tabla.setWidths(widthColumna);
    //Definimos celdas iniciales
    Font fontCabecera = new Font(Font.TIMES_ROMAN, 10, Font.BOLD);
    Font fontCelda = new Font(Font.TIMES_ROMAN, 9);
    PdfPCell h1 = new PdfPCell(new Phrase("Nombre del empleado", fontCabecera));
    h1.setHorizontalAlignment(3);
    h1.setGrayFill(0.7f);
    h1.setRowspan(2);
    h1.setColspan(1);
    tabla.addCell(h1);

    PdfPCell h2 = new PdfPCell(new Phrase("Das Hbiles", fontCabecera));
    h2.setHorizontalAlignment(1);
    h2.setGrayFill(0.7f);
    h2.setColspan(nroColumnas - 3);
    tabla.addCell(h2);

    PdfPCell h3 = new PdfPCell(new Phrase("Total (minutos)", fontCabecera));
    h3.setHorizontalAlignment(3);
    h3.setGrayFill(0.7f);
    h3.setColspan(1);
    h3.setRowspan(2);
    tabla.addCell(h3);

    //Agregado de columna de descuento sin goce
    PdfPCell h4 = new PdfPCell(new Phrase("Descuento S/G", fontCabecera));
    h4.setHorizontalAlignment(3);
    h4.setGrayFill(0.7f);
    h4.setColspan(1);
    h4.setRowspan(2);
    tabla.addCell(h4);

    PdfPCell diaColumna = new PdfPCell();
    for (int i = 0; i < (nroColumnas - 3); i++) {
        String celda = (listaInt.get(i).toString());
        diaColumna.setPhrase(new Phrase(celda, fontCabecera));
        diaColumna.setHorizontalAlignment(1);
        tabla.addCell(diaColumna);
    }
    Calendar cal = Calendar.getInstance();
    List<Integer> conteoDias = new ArrayList<>();
    int diasDescuento = 0;
    double minDescuento = 0;

    for (int i = 0; i < dnis.size(); i++) {

        List<Empleado> listaEmpleado = new ArrayList<>();
        listaEmpleado = em.buscarXPatron(dnis.get(i));
        Empleado empleado;
        empleado = listaEmpleado.get(0);
        BigDecimal totalTardanza = new BigDecimal(0.00);
        PdfPCell celdaNombre = new PdfPCell(new Phrase(empleado.getApellidoPaterno() + " "
                + empleado.getApellidoMaterno() + " " + empleado.getNombre(), fontCelda));
        celdaNombre.setHorizontalAlignment(0);
        tabla.addCell(celdaNombre);
        List<RegistroAsistencia> registrosDni = rg.buscarXEmpleadoXFecha2(dnis.get(i), fechaInicio, fechaFin);
        System.out.println(
                "Numero de registros: " + registrosDni.size() + " Empleado: " + empleado.getApellidoPaterno()
                        + " " + empleado.getApellidoPaterno() + " " + empleado.getNombre());
        List<Integer> listaPermisos = new ArrayList<>();
        if (!registrosDni.isEmpty()) {
            for (RegistroAsistencia registro : registrosDni) {
                //========================DESCUENTOS LICENCIAS=================================================
                AsignacionPermiso asignaciones = asp.buscarXDia(empleado.getNroDocumento(),
                        registro.getFecha());
                if (asignaciones != null) {
                    System.out.println("Asignacion: " + asignaciones.getPermiso().toString());
                    Permiso permisoProcesar = asignaciones.getPermiso();
                    System.out.println("Tiene un permiso" + permisoProcesar.getMotivo());
                    if (permisoProcesar.getTipoPermiso().getTipoDescuento() == 'S') {
                        if (permisoProcesar.getOpcion() == 'F') {
                            if (!listaPermisos.contains(permisoProcesar.getId().intValue())) {
                                Date fechaInicio1 = permisoProcesar.getFechaInicio();
                                Date fechaFin1 = permisoProcesar.getFechaFin();
                                if (fechaInicio1.compareTo(fechaFin1) < 0) {
                                    cal.setTime(fechaInicio1);
                                    int diaInicio = cal.get(Calendar.DAY_OF_MONTH);
                                    cal.setTime(fechaFin1);
                                    int diaFin = cal.get(Calendar.DAY_OF_MONTH);
                                    diasDescuento += diaFin - diaInicio + 1;
                                } else if (fechaInicio1.compareTo(fechaFin1) == 0) {
                                    diasDescuento = 1;
                                }
                                listaPermisos.add(permisoProcesar.getId().intValue());
                            }
                        } else {
                            if (permisoProcesar.getOpcion() == 'H') {
                                Date horaInicio1 = permisoProcesar.getHoraInicio();
                                Date horaFin1 = permisoProcesar.getHoraFin();
                                if (horaInicio1.compareTo(horaFin1) < 0) {
                                    minDescuento = permisoProcesar.getHoraFin().getTime()
                                            - permisoProcesar.getHoraInicio().getTime();
                                }
                            }

                        }
                    }
                } else {
                    System.out.println("No hay registros");
                }
                //========================DESCUENTOS LICENCIAS=================================================
                cal.setTime(registro.getFecha());
                for (int j = 0; j < listaInt.size(); j++) {
                    if (cal.get(Calendar.DAY_OF_MONTH) == listaInt.get(j)) {
                        if (registro.getMinTardanza() != null) {
                            int numero = registro.getMinTardanza().intValue();
                            String celda = "" + numero;
                            celdaNombre.setPhrase(new Phrase(celda, fontCelda));
                            celdaNombre.setHorizontalAlignment(1);
                            tabla.addCell(celdaNombre);
                            totalTardanza = totalTardanza.add(registro.getMinTardanza());
                        } else {
                            String celda = "0.0";
                            celdaNombre.setPhrase(new Phrase(celda, fontCelda));
                            celdaNombre.setHorizontalAlignment(1);
                            tabla.addCell(celdaNombre);
                        }
                        conteoDias.add(listaInt.get(j));
                        break;
                    } else {
                        if (conteoDias.contains(listaInt.get(j))) {

                        } else {
                            String celda = "n.r";
                            celdaNombre.setPhrase(new Phrase(celda, fontCelda));
                            celdaNombre.setHorizontalAlignment(1);
                            tabla.addCell(celdaNombre);
                            conteoDias.add(listaInt.get(j));
                        }
                    }
                }
            }
        } else {
            for (Integer dia : listaInt) {
                String celda = "n.r";
                celdaNombre.setPhrase(new Phrase(celda, fontCelda));
                celdaNombre.setHorizontalAlignment(1);
                tabla.addCell(celdaNombre);
            }
        }

        System.out.println("ConteoDias: " + conteoDias.size());
        System.out.println("Total tardanzas: " + totalTardanza);
        conteoDias.clear();
        //String tardanzaTotal = totalTardanza.toString();
        String hora1 = "";
        if (totalTardanza.intValue() < 60) {
            hora1 = totalTardanza.intValue() + " min";
        } else if (totalTardanza.intValue() >= 60 && totalTardanza.intValue() < 480) {
            int resto = totalTardanza.intValue() % 60;
            int totalH = (totalTardanza.intValue() - resto) / 60;
            hora1 = totalH + " h " + resto + " min";
        } else if (totalTardanza.intValue() >= 480) {
            int restoHoras = totalTardanza.intValue() % 480;
            int totalD = (totalTardanza.intValue() - restoHoras) / 480;
            int restoMinutos = restoHoras % 60;
            int totalH = (restoHoras - restoMinutos) / 60;
            hora1 = totalD + " d " + totalH + " h " + restoMinutos + " m";
        }
        celdaNombre.setPhrase(new Phrase(hora1, fontCelda));
        celdaNombre.setHorizontalAlignment(1);
        tabla.addCell(celdaNombre);
        //Descuento
        int minutosT = diasDescuento * 480;
        int minutosTotal = (int) (minutosT + minDescuento);
        String hora = "";
        if (minutosTotal < 60) {
            hora = minutosTotal + " min";
        } else if (minutosTotal >= 60 && minutosTotal < 480) {
            int resto = minutosTotal % 60;
            int totalH = (minutosTotal - resto) / 60;
            hora = totalH + " h " + resto + " min";
        } else if (minutosTotal >= 480) {
            int restoHoras = minutosTotal % 480;
            int totalD = (minutosTotal - restoHoras) / 480;
            int restoMinutos = restoHoras % 60;
            int totalH = (restoHoras - restoMinutos) / 60;
            hora = totalD + " d " + totalH + " h " + restoMinutos + " m";
        }
        celdaNombre.setPhrase(new Phrase(hora, fontCelda));
        celdaNombre.setHorizontalAlignment(1);
        tabla.addCell(celdaNombre);
    }
    return tabla;
}

From source file:questions.ocg.StatusBars1.java

public void createPdf() {
    try {//from   w w  w  . j  a  va  2 s.com
        Document document = new Document(PageSize.A4, 10, 10, 10, 10);
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));

        document.open();

        //define Layers

        PdfLayer colorLayer = PdfLayer.createTitle("Color", writer);
        colorLayerColored = new PdfLayer("Colored", writer);
        colorLayerColored.setOn(true);
        colorLayer.addChild(colorLayerColored);
        colorLayerGreyed = new PdfLayer("Greyed", writer);
        colorLayerGreyed.setOn(false);
        colorLayer.addChild(colorLayerGreyed);
        ArrayList<PdfLayer> radio = new ArrayList<PdfLayer>();
        radio.add(colorLayerColored);
        radio.add(colorLayerGreyed);
        writer.addOCGRadioGroup(radio);

        PdfPTable table = new PdfPTable(2);
        table.setWidthPercentage(100);
        PdfPCell cell;
        for (int i = 0; i <= 100; i++) {
            cell = new PdfPCell(new Phrase("percentage: " + i));
            table.addCell(cell);
            cell = new PdfPCell(getImage(writer.getDirectContent(), i));
            table.addCell(cell);
        }
        document.add(table);
        document.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}

From source file:questions.ocg.StatusBars2.java

public void createPdf() {
    try {//from   w  w  w  .j  a v a 2  s  .co  m
        Document document = new Document(PageSize.A4, 10, 10, 10, 10);
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));

        document.open();

        //define Layers

        PdfLayer colorLayer = PdfLayer.createTitle("Color", writer);
        colorLayerColored = new PdfLayer("Colored", writer);
        colorLayerColored.setOn(true);
        colorLayer.addChild(colorLayerColored);
        colorLayerGreyed = new PdfLayer("Greyed", writer);
        colorLayerGreyed.setOn(false);
        colorLayer.addChild(colorLayerGreyed);
        ArrayList<PdfLayer> radio = new ArrayList<PdfLayer>();
        radio.add(colorLayerColored);
        radio.add(colorLayerGreyed);
        writer.addOCGRadioGroup(radio);

        PdfPTable table = new PdfPTable(2);
        table.setWidthPercentage(100);
        PdfPCell cell;
        for (int i = 0; i <= 100; i++) {
            cell = new PdfPCell(new Phrase("percentage: " + i));
            table.addCell(cell);
            cell = new PdfPCell();
            cell.setCellEvent(new StatusBar(i));
            table.addCell(cell);
        }
        document.add(table);
        document.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}

From source file:questions.tables.RotatedCells.java

public static void main(String[] args) {
    Document document = new Document();
    try {//from  w  w  w  .j  av a 2 s . com
        PdfWriter.getInstance(document, new FileOutputStream(RESULT));
        document.open();

        float[] widths = { 1, 4 };
        PdfPTable table = new PdfPTable(widths);
        table.setWidthPercentage(40);
        PdfPCell cell;
        cell = new PdfPCell(new Paragraph("test 1"));
        cell.setPadding(4);
        cell.setBackgroundColor(Color.YELLOW);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell);
        table.addCell("Cell without any rotation.");

        cell = new PdfPCell(new Paragraph("test 2"));
        cell.setPadding(4);
        cell.setBackgroundColor(Color.YELLOW);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setRotation(90);
        table.addCell(cell);
        table.addCell("Cell rotated 90 degrees.");

        cell = new PdfPCell(new Paragraph("test 3"));
        cell.setPadding(4);
        cell.setBackgroundColor(Color.YELLOW);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setRotation(180);
        table.addCell(cell);
        table.addCell("Cell upside down.");

        cell = new PdfPCell(new Paragraph("test 4"));
        cell.setPadding(4);
        cell.setBackgroundColor(Color.YELLOW);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setRotation(270);
        table.addCell(cell);
        table.addCell("Cell rotated 270 degrees.");
        document.add(table);
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }

    // step 5: we close the document
    document.close();
}

From source file:questions.tables.TableColumns.java

public static void main(String[] args) {
    Document document = new Document(PageSize.A4.rotate());
    try {/*from   w ww .j a  v  a  2 s  .co m*/
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));

        document.open();

        // the content of the columns
        ColumnText content = new ColumnText(writer.getDirectContent());
        PdfPTable items = new PdfPTable(2);
        items.setWidthPercentage(100);
        for (int i = 0; i < 100; ++i) {
            items.addCell("item " + i);
            items.addCell("some item");
        }
        content.addElement(items);

        // adding the stuff to the document
        int column = 0;
        float height = 0;
        float[][] x = { { document.left(), document.left() + 380 },
                { document.right() - 380, document.right() } };
        int status = ColumnText.START_COLUMN;
        while (ColumnText.hasMoreText(status)) {
            if (column == 0) {
                PdfPTable table = new PdfPTable(1);
                table.setWidthPercentage(100);
                table.addCell("EmployeeSheets");
                table.addCell("Page " + writer.getPageNumber());
                document.add(table);
                height = table.getTotalHeight();
            }
            content.setSimpleColumn(x[column][0], document.bottom(), x[column][1],
                    document.top() - height - 10);
            status = content.go();
            if (++column >= x.length) {
                column = 0;
                document.newPage();
            }
        }
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }
    document.close();
}

From source file:questions.tables.TableHeaderAlternateBackground.java

public static void main(String[] args) {
    // step 1: creation of a document-object
    Document document = new Document(PageSize.A4.rotate());
    try {/* ww w. j  av a 2s  . c  o  m*/
        // step 2:
        // we create a writer
        PdfWriter.getInstance(
                // that listens to the document
                document,
                // and directs a PDF-stream to a file
                new FileOutputStream(RESULT));
        // step 3: we open the document
        document.open();
        // step 4: we add a table to the document
        PdfPTable datatable = new PdfPTable(10);
        datatable.setTableEvent(new AlternateBackground());
        int headerwidths[] = { 10, 24, 12, 12, 7, 7, 7, 7, 7, 7 };
        datatable.setWidths(headerwidths);
        datatable.setWidthPercentage(100);
        datatable.getDefaultCell().setPadding(5);

        // The header starts with a cell that spans 10 columns
        PdfPCell cell = new PdfPCell(new Phrase("Administration - System Users Report",
                FontFactory.getFont(FontFactory.HELVETICA, 24, Font.BOLD)));
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setBorderWidth(2);
        cell.setColspan(10);
        cell.setBackgroundColor(Color.YELLOW);
        cell.setUseDescender(true);
        datatable.addCell(cell);
        // We need 4 cells with rowspan 2
        datatable.getDefaultCell().setBorderWidth(2);
        datatable.getDefaultCell().setBackgroundColor(Color.YELLOW);
        datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        datatable.addCell("User Id");
        datatable.addCell("Name\nAddress");
        datatable.addCell("Company");
        datatable.addCell("Department");
        datatable.getDefaultCell().setBackgroundColor(null);
        // we use a nested table to fake this
        PdfPTable permissions = new PdfPTable(6);
        permissions.getDefaultCell().setBackgroundColor(Color.YELLOW);
        permissions.getDefaultCell().setBorderWidth(2);
        permissions.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        permissions.getDefaultCell().setColspan(6);
        permissions.addCell("Permissions");
        permissions.getDefaultCell().setColspan(1);
        permissions.addCell("Admin");
        permissions.addCell("Data");
        permissions.addCell("Expl");
        permissions.addCell("Prod");
        permissions.addCell("Proj");
        permissions.addCell("Online");
        PdfPCell permission = new PdfPCell(permissions);
        permission.setColspan(6);
        datatable.addCell(permission);
        // this is the end of the table header
        // as far as PdfPTable is concerned there are 2 rows in the header
        datatable.setHeaderRows(2);

        // we add the data to the table
        datatable.getDefaultCell().setBorderWidth(1);
        for (int i = 1; i < 50; i++) {
            datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
            datatable.addCell("myUserId");
            datatable.addCell("Person " + i);
            datatable.addCell("No Name Company");
            datatable.addCell("D" + i);
            datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
            for (int j = 0; j < 6; j++)
                datatable.addCell(Math.random() > .5 ? "Yes" : "No");
        }
        document.add(datatable);
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }

    // step 5: we close the document
    document.close();
}

From source file:questions.tables.TablesWriteSelected.java

public static void main(String[] args) {
    Document document = new Document(PageSize.A4.rotate());
    try {/*from  w  ww  . ja  v a  2 s  .c  o  m*/
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));

        document.open();

        // the content of the columns
        PdfPTable items = new PdfPTable(2);
        items.setTotalWidth(TOTAL_WIDTH);
        for (int i = 0; i < 100; ++i) {
            items.addCell("item " + i);
            items.addCell("some item");
        }
        int rows = items.size();

        // adding the stuff to the document
        int column = 0;
        int start;
        int end = 0;
        int row = 0;
        float available = 0;
        float[][] x = { { document.left(), document.left() + TOTAL_WIDTH },
                { document.right() - TOTAL_WIDTH, document.right() } };
        while (row < rows) {
            start = row;
            if (column == 0) {
                PdfPTable table = new PdfPTable(1);
                table.setWidthPercentage(100);
                table.addCell("EmployeeSheets");
                table.addCell("Page " + writer.getPageNumber());
                document.add(table);
                available = document.top() - table.getTotalHeight() - 10 - document.bottom();
            }
            float needed = items.getRowHeight(start);
            while (needed < available && row < rows) {
                needed += items.getRowHeight(++row);
                end = row;
            }
            items.writeSelectedRows(start, end, x[column][0], document.bottom() + available,
                    writer.getDirectContent());
            if (++column >= x.length) {
                column = 0;
                document.newPage();
            }
        }
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }
    document.close();
}

From source file:rollyroll.com.servlet.ModuloServlet.java

private void exportar_ModulosaPDF(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    try {/*  ww  w.  ja  va 2s  . c  o m*/
        //            String[] headers = new String[]{"CODIGO", "NOMBRE", "ACCION", "ORDEN", "ICONO", "ESTADO"};
        String[] headers = new String[] { "NOMBRE", "ACCION", "ICONO" };

        ArrayList<Modulo> lista = null;
        lista = moduloService.listar_Modulos();

        PdfPTable table = new PdfPTable(headers.length);
        table.setHorizontalAlignment(0);
        table.setWidthPercentage(95);
        float[] espaciocolumna = new float[] { 25f, 38f, 50f };
        table.setWidths(espaciocolumna);
        for (int i = 0; i < headers.length; i++) {
            String header = headers[i];
            PdfPCell cell = new PdfPCell();
            cell.setBackgroundColor(Color.YELLOW);
            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            cell.setPhrase(new Phrase(header.toUpperCase(), new Font(Font.HELVETICA, 10, Font.BOLD)));
            table.addCell(cell);
        }
        table.completeRow();
        PdfPCell cell;

        //            int codigomodulo = 0;
        String nombremodulo = "";
        String accionmodulo = "";
        //            int ordenmodulo = 0;
        String iconomodulo = "";
        //            int estadomodulo = 0;

        for (Modulo modulo : lista) {
            //                codigomodulo += Integer.parseInt(modulo.getCodigomodulo());
            nombremodulo += modulo.getNombremodulo();
            accionmodulo += modulo.getAccionmodulo();
            //                ordenmodulo += Integer.parseInt(modulo.getOrdenmoduloS());
            iconomodulo += modulo.getIconomodulo();
            //                estadomodulo += Byte.parseByte(modulo.getEstadomoduloS());

            //                cell = new PdfPCell();
            //                cell.setPhrase(new Phrase(modulo.getCodigomoduloS(), new Font(Font.HELVETICA, 10, Font.NORMAL)));
            //                cell.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
            //                table.addCell(cell);
            //                
            cell = new PdfPCell();
            cell.setPhrase(new Phrase(modulo.getNombremodulo(), new Font(Font.HELVETICA, 10, Font.NORMAL)));
            cell.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell();
            cell.setPhrase(new Phrase(modulo.getAccionmodulo(), new Font(Font.HELVETICA, 10, Font.NORMAL)));
            cell.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
            table.addCell(cell);

            //                cell = new PdfPCell();
            //                cell.setPhrase(new Phrase(modulo.getOrdenmoduloS(), new Font(Font.HELVETICA, 10, Font.NORMAL)));
            //                cell.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
            //                table.addCell(cell);
            cell = new PdfPCell();
            cell.setPhrase(new Phrase(modulo.getIconomodulo(), new Font(Font.HELVETICA, 10, Font.NORMAL)));
            cell.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
            table.addCell(cell);

            //                cell = new PdfPCell();
            //                cell.setPhrase(new Phrase(modulo.getEstadomoduloS(), new Font(Font.HELVETICA, 10, Font.NORMAL)));
            //                cell.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
            //                table.addCell(cell);
        }

        table.completeRow();

        //incia diseo de documento exportado
        Document document = new Document(PageSize.A4.rotate(), 20, 5, 5, 5);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter.getInstance(document, baos);
        document.open();

        document.addTitle("Reporte de Ventas Generales");
        document.add(
                new Paragraph("Reporte: Ventas Generales 2016", new Font(Font.HELVETICA, 16, Font.UNDERLINE)));
        document.add(new Paragraph("_"));
        document.add(table);
        document.add(Chunk.NEWLINE);
        document.add(new Paragraph(
                "Leyenda: AB: Inicio, BA: Retorno (Importante: No se consideran unidades sin GPS)"));
        document.addAuthor("Quispe Roque Alex Christian");

        table = new PdfPTable(4);
        table.setHorizontalAlignment(0);
        table.setWidthPercentage(40);
        espaciocolumna = new float[] { 10f, 40f, 20f, 20f };
        table.setWidths(espaciocolumna);

        cell = new PdfPCell();
        cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        cell.setPhrase(new Phrase("RESUMEN", new Font(Font.HELVETICA, 10, Font.BOLD)));
        cell.setColspan(7);
        table.addCell(cell);
        table.completeRow();

        //aqui iniciamos asignacion de datos
        //===================================================================
        //            cell = new PdfPCell();
        //            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        //            cell.setPhrase(new Phrase("", new Font(Font.HELVETICA, 10, Font.BOLD)));
        //            table.addCell(cell);
        //
        //            cell = new PdfPCell();
        //            cell.setBackgroundColor(Color.yellow);
        //            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        //            cell.setPhrase(new Phrase("FLOTA OPERATIVA", new Font(Font.HELVETICA, 10, Font.BOLD)));
        //            table.addCell(cell);
        //
        //            cell = new PdfPCell();
        //            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        //            cell.setPhrase(new Phrase(lista.size() + "", new Font(Font.HELVETICA, 10, Font.BOLD)));
        //            table.addCell(cell);
        //
        //            cell = new PdfPCell();
        //            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        //            cell.setPhrase(new Phrase("UNIDADES", new Font(Font.HELVETICA, 10, Font.BOLD)));
        //            table.addCell(cell);
        //            table.completeRow();
        //
        //            //==================================================================================
        //            cell = new PdfPCell();
        //            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        //            cell.setPhrase(new Phrase("2", new Font(Font.HELVETICA, 10, Font.BOLD)));
        //            table.addCell(cell);
        //
        //            cell = new PdfPCell();
        //            cell.setBackgroundColor(Color.yellow);
        //            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        //            cell.setPhrase(new Phrase("NRO DE VIAJES", new Font(Font.HELVETICA, 10, Font.BOLD)));
        //            table.addCell(cell);
        //
        //            cell = new PdfPCell();
        //            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        //            cell.setPhrase(new Phrase((totalAB + totalBA) + "", new Font(Font.HELVETICA, 10, Font.BOLD)));
        //            table.addCell(cell);
        //
        //            cell = new PdfPCell();
        //            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        //            cell.setPhrase(new Phrase("VIAJES", new Font(Font.HELVETICA, 10, Font.BOLD)));
        //            table.addCell(cell);
        //
        //            table.completeRow();
        //==================================================================================
        document.add(Chunk.NEWLINE);
        document.add(table);

        document.left(1);
        document.top(1);
        document.close();
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        //            response.setHeader("Content-Disposition", "attachment; filename=ReporteGeneraldeModulos.pdf");
        response.setHeader("Content-Disposition", "filename=ReporteGeneraldeModulos.pdf");
        response.setHeader("Pragma", "public");
        response.setContentType("application/pdf");
        response.setContentLength(baos.size());
        ServletOutputStream out = response.getOutputStream();
        baos.writeTo(out);
        out.flush();

    } catch (Exception e) {
        RequestDispatcher rd2;
        rd2 = request.getRequestDispatcher("vista/include/error_404.jsp");
        rd2.forward(request, response);
        System.out.println(
                "rollyroll.com.servlet.ModuloServlet.exportar_ModulosaPDF() => ERROR GRAVE AL GENERAR PDF");
        e.getMessage();
    }
}

From source file:test.itext.html.AimsPdf.java

License:Open Source License

public static void addTitle(Document doc, String text)
        throws IOException, BadElementException, DocumentException {
    float[] widths = { 62f, 164f, 62f };
    PdfPTable table = new PdfPTable(widths);
    table.setWidthPercentage(100);
    table.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.setSpacingAfter(10);//from   w w  w. j  av a  2 s. c o  m

    Image image = Image.getInstance("app_title.gif");
    image.scalePercent(70);
    PdfPCell cell = new PdfPCell(image);
    cell.setPadding(10);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    table.addCell(cell);

    Paragraph title = new Paragraph(text, FontFactory.getFont("arial", 12, Font.BOLD));
    cell = new PdfPCell(title);
    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(cell);

    image = Image.getInstance("title_shot.gif");
    image.scalePercent(70);
    cell = new PdfPCell(image);
    cell.setPadding(10);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    table.addCell(cell);

    doc.add(table);

    table = new PdfPTable(1);
    table.setWidthPercentage(100);
    cell = new PdfPCell();
    cell.setBackgroundColor(Color.BLACK);
    cell.setFixedHeight(1);
    table.addCell(cell);

    doc.add(table);
}