Example usage for com.itextpdf.text.pdf PdfPTable setHeaderRows

List of usage examples for com.itextpdf.text.pdf PdfPTable setHeaderRows

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf PdfPTable setHeaderRows.

Prototype

public void setHeaderRows(int headerRows) 

Source Link

Document

Sets the number of the top rows that constitute the header.

Usage

From source file:Compras.reportePedidos.java

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    // TODO add your handling code here:
    h = new Herramientas(usr, 0);
    h.session(sessionPrograma);//from www .  j a  va 2  s .co m
    if (t_datos.getRowCount() > 0) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        javax.swing.JFileChooser jF1 = new javax.swing.JFileChooser();
        jF1.setFileFilter(new ExtensionFileFilter("Excel document (*.pdf)", new String[] { "pdf" }));
        String ruta = null;
        if (jF1.showSaveDialog(null) == jF1.APPROVE_OPTION) {
            ruta = jF1.getSelectedFile().getAbsolutePath();
            if (ruta != null) {
                try {
                    DecimalFormat formatoPorcentaje = new DecimalFormat("#,##0.00");
                    formatoPorcentaje.setMinimumFractionDigits(2);
                    session.beginTransaction().begin();
                    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI,
                            BaseFont.NOT_EMBEDDED);
                    //Orden ord=buscaApertura();
                    PDF reporte = new PDF();
                    Date fecha = new Date();
                    DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyyHH-mm-ss");//YYYY-MM-DD HH:MM:SS
                    String valor = dateFormat.format(fecha);

                    reporte.Abrir2(PageSize.LETTER.rotate(), "Reporte", ruta + ".pdf");
                    Font font = new Font(Font.FontFamily.HELVETICA, 5, Font.BOLD);
                    BaseColor contenido = BaseColor.WHITE;
                    int centro = Element.ALIGN_CENTER;
                    int izquierda = Element.ALIGN_LEFT;
                    int derecha = Element.ALIGN_RIGHT;
                    float[] tam_pdf = new float[] { 10, 25, 13, 18, 10, 50, 50, 60, 18, 18, 15 };

                    PdfPTable tabla = reporte.crearTabla(tam_pdf.length, tam_pdf, 100, Element.ALIGN_LEFT);

                    cabecera(reporte, bf, tabla);
                    int ren = 0;
                    double dm = 0d, cam = 0d, min = 0d, med = 0d, max = 0d, pin = 0d, tot = 0d;
                    for (int i = 0; i < t_datos.getRowCount(); i++) {
                        for (int j = 0; j < t_datos.getColumnCount(); j++) {
                            if (t_datos.getColumnName(j).compareTo("Monto tot.") == 0) {
                                if (t_datos.getValueAt(i, j) != null)
                                    tabla.addCell(
                                            reporte.celda(formatoPorcentaje.format(t_datos.getValueAt(i, j)),
                                                    font, contenido, derecha, 0, 1, Rectangle.RECTANGLE));
                                else
                                    tabla.addCell(reporte.celda("0.00", font, contenido, derecha, 0, 1,
                                            Rectangle.RECTANGLE));
                            } else {
                                if (t_datos.getValueAt(i, j) != null)
                                    tabla.addCell(reporte.celda("" + t_datos.getValueAt(i, j), font, contenido,
                                            izquierda, 0, 1, Rectangle.RECTANGLE));
                                else
                                    tabla.addCell(reporte.celda("", font, contenido, izquierda, 0, 1,
                                            Rectangle.RECTANGLE));
                            }
                        }
                        /*if(ren==38)
                        {
                        reporte.agregaObjeto(tabla);
                        reporte.writer.newPage();
                        tabla=reporte.crearTabla(tam_pdf.length, tam_pdf, 100, Element.ALIGN_LEFT);
                        cabecera(reporte, bf, tabla);
                        ren=-1;
                        }
                        ren++;*/
                    }
                    tabla.setHeaderRows(1);
                    reporte.agregaObjeto(tabla);
                    reporte.cerrar();
                    reporte.visualizar2(ruta + ".pdf");
                } catch (Exception e) {
                    System.out.println(e);
                    e.printStackTrace();
                    JOptionPane.showMessageDialog(this,
                            "No se pudo realizar el reporte si el archivo esta abierto.");
                } finally {
                    if (session != null)
                        if (session.isOpen())
                            session.close();
                }
            }
        }
    }
}

From source file:Compras.reportePedidos.java

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
    // TODO add your handling code here:
    h = new Herramientas(usr, 0);
    h.session(sessionPrograma);//from   w w w  .  j a  va  2  s .c o m
    if (t_datos.getRowCount() > 0) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        javax.swing.JFileChooser jF1 = new javax.swing.JFileChooser();
        jF1.setFileFilter(new ExtensionFileFilter("Excel document (*.pdf)", new String[] { "pdf" }));
        String ruta = null;
        if (jF1.showSaveDialog(null) == jF1.APPROVE_OPTION) {
            ruta = jF1.getSelectedFile().getAbsolutePath();
            if (ruta != null) {
                try {
                    DecimalFormat formatoPorcentaje = new DecimalFormat("#,##0.00");
                    formatoPorcentaje.setMinimumFractionDigits(2);
                    session.beginTransaction().begin();
                    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI,
                            BaseFont.NOT_EMBEDDED);
                    PDF reporte = new PDF();
                    Date fecha = new Date();
                    DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyyHH-mm-ss");//YYYY-MM-DD HH:MM:SS
                    String valor = dateFormat.format(fecha);

                    reporte.Abrir2(PageSize.LETTER.rotate(), "Reporte", ruta + ".pdf");
                    Font font = new Font(Font.FontFamily.HELVETICA, 8, Font.NORMAL);
                    BaseColor contenido = BaseColor.WHITE;
                    int centro = Element.ALIGN_CENTER;
                    int izquierda = Element.ALIGN_LEFT;
                    int derecha = Element.ALIGN_RIGHT;
                    float[] tam_pdf = new float[] { 15, 40, 130, 20, 15, 30, 20, 15 };

                    PdfPTable tabla = reporte.crearTabla(tam_pdf.length, tam_pdf, 100, Element.ALIGN_LEFT);

                    cabeceraReporte(reporte, bf, tabla);
                    Object no[];
                    int ren[];
                    if (t_datos.getSelectedRows().length > 0) {
                        no = new Object[t_datos.getSelectedRows().length];
                        ren = t_datos.getSelectedRows();
                        for (int x = 0; x < t_datos.getSelectedRows().length; x++) {
                            no[x] = (int) t_datos.getValueAt(ren[x], 0);
                        }
                    } else {
                        no = new Object[t_datos.getRowCount()];
                        //ren =new int[t_datos.getRowCount()];
                        for (int x = 0; x < t_datos.getRowCount(); x++) {
                            no[x] = (int) t_datos.getValueAt(x, 0);
                        }
                    }
                    Pedido[] pedidos;
                    if (autorizado.isSelected() == true) {
                        pedidos = (Pedido[]) session.createCriteria(Pedido.class)
                                .add(Restrictions.and(
                                        Restrictions.and(Restrictions.isNotNull("usuarioByAutorizo"),
                                                Restrictions.isNotNull("usuarioByAutorizo2")),
                                        Restrictions.in("idPedido", no)))
                                .list().toArray(new Pedido[0]);
                    } else {
                        pedidos = (Pedido[]) session.createCriteria(Pedido.class)
                                .add(Restrictions.in("idPedido", no)).list().toArray(new Pedido[0]);
                    }
                    if (pedidos.length > 0) {
                        ArrayList ordena = new ArrayList();
                        for (int a = 0; a < pedidos.length; a++) {
                            Pedido aux = pedidos[a];
                            if (aux.getTipoPedido().compareTo("Interno") == 0) {
                                Partida[] par = (Partida[]) aux.getPartidas().toArray(new Partida[0]);
                                for (int b = 0; b < par.length; b++) {
                                    Partida ren1 = par[b];
                                    Renglon nuevo;
                                    if (ren1.getEjemplar() != null)
                                        nuevo = new Renglon("" + aux.getIdPedido(),
                                                ren1.getEjemplar().getIdParte(), ren1.getCatalogo().getNombre(),
                                                ren1.getCantPcp(), ren1.getMed(), ren1.getPcp(),
                                                "" + ren1.getOrdenByIdOrden().getIdOrden(),
                                                "" + ren1.getIdEvaluacion() + "-" + ren1.getSubPartida());
                                    else
                                        nuevo = new Renglon("" + aux.getIdPedido(), "",
                                                ren1.getCatalogo().getNombre(), ren1.getCantPcp(),
                                                ren1.getMed(), ren1.getPcp(),
                                                "" + ren1.getOrdenByIdOrden().getIdOrden(),
                                                "" + ren1.getIdEvaluacion() + "-" + ren1.getSubPartida());
                                    ordena.add(nuevo);
                                }
                            }

                            if (aux.getTipoPedido().compareTo("Externo") == 0) {
                                PartidaExterna[] par = (PartidaExterna[]) aux.getPartidaExternas()
                                        .toArray(new PartidaExterna[0]);
                                for (int b = 0; b < par.length; b++) {
                                    PartidaExterna ren2 = par[b];
                                    Renglon nuevo;
                                    nuevo = new Renglon("" + aux.getIdPedido(), ren2.getNoParte(),
                                            ren2.getDescripcion(), ren2.getCantidad(), ren2.getUnidad(),
                                            ren2.getCosto(), "", "" + "Ext");
                                    ordena.add(nuevo);
                                }
                            }

                            if (aux.getTipoPedido().compareTo("Adicional") == 0) {
                                PartidaExterna[] par = (PartidaExterna[]) aux.getPartidaExternas()
                                        .toArray(new PartidaExterna[0]);
                                for (int b = 0; b < par.length; b++) {
                                    PartidaExterna ren2 = par[b];
                                    Renglon nuevo;
                                    nuevo = new Renglon("" + aux.getIdPedido(), ren2.getNoParte(),
                                            ren2.getDescripcion(), ren2.getCantidad(), ren2.getUnidad(),
                                            ren2.getCosto(), "" + aux.getOrden().getIdOrden(), "ADI");
                                    ordena.add(nuevo);
                                }
                            }
                        }

                        Collections.sort(ordena, new Comparator() {
                            @Override
                            public int compare(Object o1, Object o2) {
                                Renglon p1 = (Renglon) o1;
                                Renglon p2 = (Renglon) o2;
                                return new String(p1.np + p1.descripcion)
                                        .compareTo(new String(p2.np + p2.descripcion));
                            }
                        });

                        for (int c = 0; c < ordena.size(); c++) {
                            Renglon r1 = (Renglon) ordena.get(c);
                            tabla.addCell(reporte.celda(r1.pedido, font, contenido, derecha, 0, 1,
                                    Rectangle.RECTANGLE));
                            tabla.addCell(
                                    reporte.celda(r1.np, font, contenido, derecha, 0, 1, Rectangle.RECTANGLE));
                            tabla.addCell(reporte.celda(r1.descripcion, font, contenido, izquierda, 0, 1,
                                    Rectangle.RECTANGLE));
                            tabla.addCell(reporte.celda(formatoPorcentaje.format(r1.cant), font, contenido,
                                    derecha, 0, 1, Rectangle.RECTANGLE));
                            tabla.addCell(
                                    reporte.celda(r1.med, font, contenido, derecha, 0, 1, Rectangle.RECTANGLE));
                            tabla.addCell(reporte.celda(formatoPorcentaje.format(r1.precio), font, contenido,
                                    derecha, 0, 1, Rectangle.RECTANGLE));
                            tabla.addCell(reporte.celda("" + r1.orden, font, contenido, centro, 0, 1,
                                    Rectangle.RECTANGLE));
                            tabla.addCell(reporte.celda(r1.partida, font, contenido, derecha, 0, 1,
                                    Rectangle.RECTANGLE));
                        }
                    }

                    tabla.setHeaderRows(2);
                    reporte.agregaObjeto(tabla);
                    reporte.cerrar();
                    reporte.visualizar2(ruta + ".pdf");
                } catch (Exception e) {
                    System.out.println(e);
                    e.printStackTrace();
                    JOptionPane.showMessageDialog(this,
                            "No se pudo realizar el reporte si el archivo esta abierto.");
                } finally {
                    if (session != null)
                        if (session.isOpen())
                            session.close();
                }
            }
        }
    }
}

From source file:Contabilidad.RCuentas.java

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
    // TODO add your handling code here:
    if (t_datos.getRowCount() > 0) {
        javax.swing.JFileChooser jF1 = new javax.swing.JFileChooser();
        jF1.setFileFilter(new ExtensionFileFilter("Excel document (*.pdf)", new String[] { "pdf" }));
        String ruta = null;/*from w w w .j a  v  a  2 s  .  c  om*/
        if (jF1.showSaveDialog(null) == jF1.APPROVE_OPTION) {
            ruta = jF1.getSelectedFile().getAbsolutePath();
            if (ruta != null) {
                Session session = HibernateUtil.getSessionFactory().openSession();
                try {
                    DecimalFormat formatoPorcentaje = new DecimalFormat("#,##0.00");
                    formatoPorcentaje.setMinimumFractionDigits(2);
                    session.beginTransaction().begin();
                    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI,
                            BaseFont.NOT_EMBEDDED);
                    //Orden ord=buscaApertura();
                    PDF reporte = new PDF();
                    Date fecha = new Date();
                    DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyyHH-mm-ss");//YYYY-MM-DD HH:MM:SS
                    String valor = dateFormat.format(fecha);

                    reporte.Abrir2(PageSize.LETTER.rotate(), "Reporte Contabilidad", ruta + ".pdf");
                    Font font = new Font(Font.FontFamily.HELVETICA, 7, Font.NORMAL);
                    BaseColor contenido = BaseColor.WHITE;
                    int centro = Element.ALIGN_CENTER;
                    int izquierda = Element.ALIGN_LEFT;
                    int derecha = Element.ALIGN_RIGHT;
                    float[] nuevos = new float[] { 36, 75, 95, 250, 145, 36, 47, 65, 90, 70, 140 };

                    PdfPTable tabla = reporte.crearTabla(nuevos.length, nuevos, 100, Element.ALIGN_LEFT);

                    cabecera(reporte, bf, tabla, "Reporte de Cuentas por Cobrar", 1);
                    for (int ren = 0; ren < t_datos.getRowCount(); ren++) {
                        for (int col = 0; col < t_datos.getColumnCount(); col++) {
                            try {
                                if (col == 1) {
                                    String[] vec = t_datos.getValueAt(ren, col).toString().split("T");
                                    if (vec.length > 0)
                                        tabla.addCell(reporte.celda(vec[0], font, contenido, derecha, 0, 1,
                                                Rectangle.RECTANGLE));
                                    else
                                        tabla.addCell(reporte.celda("", font, contenido, derecha, 0, 1,
                                                Rectangle.RECTANGLE));
                                } else {
                                    if (col == 7)
                                        tabla.addCell(reporte.celda(
                                                formatoPorcentaje.format(t_datos.getValueAt(ren, col)), font,
                                                contenido, derecha, 0, 1, Rectangle.RECTANGLE));
                                    else
                                        tabla.addCell(reporte.celda(t_datos.getValueAt(ren, col).toString(),
                                                font, contenido, izquierda, 0, 1, Rectangle.RECTANGLE));
                                }
                            } catch (Exception e) {
                                tabla.addCell(reporte.celda("", font, contenido, izquierda, 0, 1,
                                        Rectangle.RECTANGLE));
                            }
                        }
                    }
                    tabla.setHeaderRows(1);
                    reporte.agregaObjeto(tabla);
                    reporte.cerrar();
                    reporte.visualizar2(ruta + ".pdf");
                } catch (Exception e) {
                    System.out.println(e);
                    e.printStackTrace();
                    JOptionPane.showMessageDialog(this,
                            "No se pudo realizar el reporte si el archivo esta abierto.");
                }
                if (session != null)
                    if (session.isOpen())
                        session.close();
            }
        }
    }
}

From source file:Controller.CrearPDF.java

/**
 * We create a PDF document with iText using different elements to learn 
 * to use this library.//from  w  w  w .  j a va  2 s. c  o m
 * Creamos un documento PDF con iText usando diferentes elementos para aprender 
 * a usar esta librera.
 * @param pdfNewFile  <code>String</code> 
 *      pdf File we are going to write. 
 *      Fichero pdf en el que vamos a escribir. 
 */
//    public void createPDF(File pdfNewFile, ReparacionEntity reparacion) throws Exception {
public void createPDF(File pdfNewFile) throws Exception {
    // We create the document and set the file name.        
    // Creamos el documento e indicamos el nombre del fichero.
    try {
        //            ClienteController cc = new ClienteController();
        //            Cliente cliente = cc.buscarPorId(reparacion.getCliente());
        Document document = new Document();
        try {

            PdfWriter.getInstance(document, new FileOutputStream(pdfNewFile));

        } catch (FileNotFoundException fileNotFoundException) {
            System.out.println("No such file was found to generate the PDF "
                    + "(No se encontr el fichero para generar el pdf)" + fileNotFoundException);
        }
        document.open();
        // We add metadata to PDF
        // Aadimos los metadatos del PDF
        document.addTitle("Table export to PDF (Exportamos la tabla a PDF)");
        document.addSubject("Using iText (usando iText)");
        document.addKeywords("Java, PDF, iText");
        document.addAuthor("Cdigo Xules");
        document.addCreator("Cdigo Xules");

        // First page
        // Primera pgina 
        Chunk chunk = new Chunk("RDEN DE TRABAJO", categoryFont);
        Chunk c2 = new Chunk("\n\n\nCentro de Formacin SATCAR6\n" + "Calle Artes Grficas n1 Nave 12 A\n"
                + "Pinto (28320), Madrid", smallFont);

        Chunk c3 = new Chunk("Datos del Cliente", smallBold);
        //            Chunk c4 = new Chunk("Nombre: "+cliente.getRazonSocial(),smallBold);
        //            Chunk c5 = new Chunk("Poblacin: "+cliente.getPoblacion(),smallBold);
        //            Chunk c6 = new Chunk("Provincia: "+cliente.getProvincia(),smallBold);
        //            Chunk c7 = new Chunk("Cdigo Postal: "+cliente.getCp(),smallBold);
        //            Chunk c8 = new Chunk("Num Telfono: Pepito"+cliente.getTlf1(),smallBold);
        Chunk c4 = new Chunk("Nombre: Jesus Eduardo Garcia Toril", smallBold);
        Chunk c5 = new Chunk("Poblacin: Pinto", smallBold);
        Chunk c6 = new Chunk("Provincia: Madrid", smallBold);
        Chunk c7 = new Chunk("Cdigo Postal: 28320", smallBold);
        Chunk c8 = new Chunk("Num Telfono: 659408182", smallBold);

        Paragraph parrafo = new Paragraph(chunk);
        Paragraph p2 = new Paragraph(c2);
        Paragraph p3 = new Paragraph(c3);
        Phrase ph1 = new Phrase(c4);
        Phrase ph2 = new Phrase(c5);
        Phrase ph3 = new Phrase(c6);
        Phrase ph4 = new Phrase(c7);
        Phrase ph5 = new Phrase(c8);

        // Let's create de first Chapter (Creemos el primer captulo)

        // We add an image (Aadimos una imagen)
        Image image;
        try {
            parrafo.setAlignment(Element.ALIGN_CENTER);
            image = Image.getInstance(iTextExampleImage);
            image.setAbsolutePosition(0, 750);
            p2.setAlignment(Element.ALIGN_LEFT);
            document.add(parrafo);
            document.add(image);
            document.add(p2);
            document.add(p3);
            document.add(ph1);
            document.add(ph2);
            document.add(ph3);
            document.add(ph4);
            document.add(ph5);

        } catch (BadElementException ex) {
            System.out.println("Image BadElementException" + ex);
        }

        // Second page - some elements
        // Segunda pgina - Algunos elementos

        // List by iText (listas por iText)
        String text = "test 1 2 3 ";
        for (int i = 0; i < 5; i++) {
            text = text + text;
        }
        List list = new List(List.UNORDERED);
        ListItem item = new ListItem(text);
        item.setAlignment(Element.ALIGN_JUSTIFIED);
        list.add(item);
        text = "a b c align ";
        for (int i = 0; i < 5; i++) {
            text = text + text;
        }
        item = new ListItem(text);
        item.setAlignment(Element.ALIGN_JUSTIFIED);
        list.add(item);
        text = "supercalifragilisticexpialidocious ";
        for (int i = 0; i < 3; i++) {
            text = text + text;
        }
        item = new ListItem(text);
        item.setAlignment(Element.ALIGN_JUSTIFIED);
        list.add(item);

        // How to use PdfPTable
        // Utilizacin de PdfPTable

        // We use various elements to add title and subtitle
        // Usamos varios elementos para aadir ttulo y subttulo
        Anchor anchor = new Anchor("Table export to PDF (Exportamos la tabla a PDF)", categoryFont);
        anchor.setName("Table export to PDF (Exportamos la tabla a PDF)");
        Chapter chapTitle = new Chapter(new Paragraph(anchor), 1);
        Paragraph paragraph = new Paragraph("Do it by Xules (Realizado por Xules)", subcategoryFont);
        Section paragraphMore = chapTitle.addSection(paragraph);
        paragraphMore.add(new Paragraph("This is a simple example (Este es un ejemplo sencillo)"));
        Integer numColumns = 6;
        Integer numRows = 120;
        // We create the table (Creamos la tabla).
        PdfPTable table = new PdfPTable(numColumns);
        // Now we fill the PDF table 
        // Ahora llenamos la tabla del PDF
        PdfPCell columnHeader;
        // Fill table rows (rellenamos las filas de la tabla).                
        for (int column = 0; column < numColumns; column++) {
            columnHeader = new PdfPCell(new Phrase("COL " + column));
            columnHeader.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(columnHeader);
        }
        table.setHeaderRows(1);
        // Fill table rows (rellenamos las filas de la tabla).                
        for (int row = 0; row < numRows; row++) {
            for (int column = 0; column < numColumns; column++) {
                table.addCell("Row " + row + " - Col" + column);
            }
        }
        // We add the table (Aadimos la tabla)
        paragraphMore.add(table);
        // We add the paragraph with the table (Aadimos el elemento con la tabla).
        document.add(chapTitle);
        document.close();
        System.out.println("Your PDF file has been generated!(Se ha generado tu hoja PDF!");
    } catch (DocumentException documentException) {
        System.out.println(
                "The file not exists (Se ha producido un error al generar un documento): " + documentException);
    }
}

From source file:controller.PlanController.java

public Document PrintPressed(String Path) throws DocumentException, IOException {
    // step 1//w w w.  ja v  a2  s. c  om
    Document document = new Document();
    // step 2
    PdfWriter.getInstance(document, new FileOutputStream(Path));
    // step 3
    document.open();
    // step 4
    PdfPTable tablaDatosPlan = new PdfPTable(2);

    tablaDatosPlan.setWidthPercentage(100);

    if (!Team.getText().isEmpty()) {
        PdfPCell cell1 = new PdfPCell(new Phrase(messages.getString("Team") + ":" + Team.getText()));
        cell1.setBorderColor(BaseColor.WHITE);
        tablaDatosPlan.addCell(cell1);
    }
    if (!Season.getText().isEmpty()) {
        PdfPCell cell1 = new PdfPCell(new Phrase(messages.getString("Season") + ":" + Season.getText()));
        cell1.setBorderColor(BaseColor.WHITE);
        tablaDatosPlan.addCell(cell1);
    }
    if (!Date.getText().isEmpty()) {
        PdfPCell cell1 = new PdfPCell(new Phrase(messages.getString("Date") + ":" + Date.getText()));
        cell1.setBorderColor(BaseColor.WHITE);
        tablaDatosPlan.addCell(cell1);
    }
    if (!Players.getText().isEmpty()) {
        PdfPCell cell1 = new PdfPCell(new Phrase(messages.getString("Players") + ":" + Players.getText()));
        cell1.setBorderColor(BaseColor.WHITE);
        tablaDatosPlan.addCell(cell1);
    }
    if (!Start.getText().isEmpty()) {
        PdfPCell cell1 = new PdfPCell(new Phrase(messages.getString("Start") + ":" + Start.getText()));
        cell1.setBorderColor(BaseColor.WHITE);
        tablaDatosPlan.addCell(cell1);
    }
    if (!End.getText().isEmpty()) {
        PdfPCell cell1 = new PdfPCell(new Phrase(messages.getString("End") + ":" + End.getText()));
        cell1.setBorderColor(BaseColor.WHITE);
        tablaDatosPlan.addCell(cell1);
    }
    if (!Place.getText().isEmpty()) {
        PdfPCell cell1 = new PdfPCell(new Phrase(messages.getString("Place") + ":" + Place.getText()));
        cell1.setBorderColor(BaseColor.WHITE);
        tablaDatosPlan.addCell(cell1);
    }
    if (!Equipment.getText().isEmpty()) {
        PdfPCell cell1 = new PdfPCell(new Phrase(messages.getString("Equipment") + ":" + Equipment.getText()));
        cell1.setBorderColor(BaseColor.WHITE);
        tablaDatosPlan.addCell(cell1);
    }

    document.add(tablaDatosPlan);

    document.add(new Phrase("\n"));
    document.add(new Phrase("\n"));

    PdfPTable tablaEjercicios = new PdfPTable(4);
    tablaEjercicios.setHeaderRows(contadorlineas);
    tablaEjercicios.addCell(messages.getString("Start"));
    tablaEjercicios.addCell(messages.getString("End"));
    tablaEjercicios.addCell(messages.getString("Drill"));
    tablaEjercicios.addCell(messages.getString("Notes"));
    int cont = 0;
    for (int aw = 4; aw < contadorlineas + 4; aw++) {

        tablaEjercicios.addCell(starColumn.getCellData(cont));
        tablaEjercicios.addCell(endColumn.getCellData(cont));
        tablaEjercicios.addCell(drillColumn.getCellData(cont));
        tablaEjercicios.addCell(notesColumn.getCellData(cont));
        cont++;
    }

    document.add(tablaEjercicios);
    int contadorListado = 0, contadorRecorrer = 0;

    if (checkboxDrills.isSelected()) {

        while (contadorListado < planData.size()) {
            contadorRecorrer = 0;

            while (contadorRecorrer < playData.size()) {
                System.out.println("Busco el ejercicio " + drillColumn.getCellData(contadorListado));
                if (drillColumn.getCellData(contadorListado)
                        .contains(playData.get(contadorRecorrer).getNombreJugada())) {
                    int contador = 1;
                    System.out.println("Ejercicio encontrado");
                    document.add(new Paragraph(
                            messages.getString("Drill") + " " + drillColumn.getCellData(contadorListado)));
                    while (contador < playData.get(contadorRecorrer).getContadorJugada() + 1) {

                        document.add(new Paragraph(messages.getString("Diagram") + " " + contador));
                        document.add(new Paragraph(" "));

                        Image image2 = Image.getInstance(playData.get(contadorRecorrer).getNombreJugada() + "-"
                                + playData.get(contadorRecorrer).getTipoJugada() + "-"
                                + playData.get(contadorRecorrer).getSubtipoJugada() + "_" + contador);
                        image2.scalePercent(50);

                        PdfPTable table1 = new PdfPTable(2);

                        table1.addCell(image2);
                        table1.addCell(
                                textPdf.textPdf(contador, playData.get(contadorRecorrer).getDescripcionJugada(),
                                        playData.get(contadorRecorrer).getContadorJugada()));
                        document.add(table1);

                        contador++;

                    }

                }
                contadorRecorrer++;

            }
            contadorListado++;
        }

    }
    // step 5
    document.close();
    return document;

}

From source file:CTD.planer2.util.ExportToPdf.java

/**
 * We create the table we want to add to our pdf
 * //from  ww  w  . j ava 2s.c o  m
 * @param subCatPart
 * @throws BadElementException
 */
private static void createTable(Section subCatPart) throws BadElementException {

    // Get the number of days per Week from the Settings
    int daysPerWeek = App.theSettings.getDaysPerWeek();

    PdfPTable table = new PdfPTable(daysPerWeek + 1);

    String[] WeekDay = { "Zeit", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag",
            "Sonntag" };

    for (int i = 0; i < daysPerWeek + 1; i++) {
        PdfPCell c1 = new PdfPCell(new Phrase(WeekDay[i]));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);
        if (i == daysPerWeek) {
            table.setHeaderRows(1);
        }
    }

    // We take the first day to get the number of units and so the number of
    // times we have to run this.
    for (int j = 0; j < planExport.getWeekday(1).size(); j++) {
        // For each day available, we run this loop once.
        for (int k = 1; k < daysPerWeek + 1; k++) {
            // Read one unit per day and write it in a new cell of the pdf
            List<Units> tmp = planExport.getWeekday(k);
            // If it's the first day, we also want a first cell per line
            // containing the time this unit starts
            if (k == 1) {
                SimpleDateFormat df = new SimpleDateFormat("HH:mm");
                String time = df.format(tmp.get(j).getTime());
                table.addCell(time);
                String room = " ";
                // Check whether a room is given
                if (tmp.get(j).getRooms().size() < 1) {
                    room = " ";
                } else {
                    room = tmp.get(j).getRooms().get(0).toString();
                }
                String teacher = " ";
                if (tmp.get(j).getPerson() == null) {
                    teacher = " ";
                } else {
                    teacher = tmp.get(j).toString();
                }
                String subject = " ";
                if (tmp.get(j).getSubjects().size() < 1) {
                    subject = " ";
                } else {
                    subject = tmp.get(j).getSubjects().get(0).toString();
                }
                // If the plan is for a room, we just need the time and the
                // teachers name
                if (CPlaner.selRoom != null) {
                    table.addCell(teacher);
                    // If the plan is for a class, we need the time, the
                    // room and the teachers name
                } else if (CPlaner.selClass != null) {
                    table.addCell(room + ", " + teacher);
                    // For a teachers plan, we need the room and the subject
                } else {
                    table.addCell(room + ", " + subject);
                }
            } else {
                // If it's not the first day, we don't need to print the
                // start time again
                String room = " ";
                // Check again whether a room is given
                if (tmp.get(j).getRooms().size() < 1) {
                    room = " ";
                } else {
                    room = tmp.get(j).getRooms().get(0).toString();
                }
                String teacher = " ";
                if (tmp.get(j).getPerson() == null) {
                    teacher = " ";
                } else {
                    teacher = tmp.get(j).toString();
                }
                String subject = " ";
                if (tmp.get(j).getSubjects().size() < 1) {
                    subject = " ";
                } else {
                    subject = tmp.get(j).getSubjects().get(0).toString();
                }
                // If the plan is for a room, we just need the time and the
                // teachers name
                if (CPlaner.selRoom != null) {
                    table.addCell(teacher);
                    // If the plan is for a class, we need the time, the
                    // room and the teachers name
                } else if (CPlaner.selClass != null) {
                    table.addCell(room + ", " + teacher);
                    // For a teachers plan, we need the room and the subject
                } else {
                    table.addCell(room + ", " + subject);
                }
            }
        }
    }

    // Add the whole table we've just created to the pdf file
    subCatPart.add(table);

}

From source file:CTD.planer2.util.ExportToPdf.java

/**
 * We create the table we want to add to our pdf
 * //from   w  w w  . j  a  va  2  s  .  c o m
 * @param subCatPart
 * @throws BadElementException
 */
private static void createTable(Section subCatPart, Room room) throws BadElementException {
    // Get the number of days per Week from the Settings
    int daysPerWeek = App.theSettings.getDaysPerWeek();

    PdfPTable table = new PdfPTable(daysPerWeek + 1);

    String[] WeekDay = { "Zeit", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag",
            "Sonntag" };

    for (int i = 0; i < daysPerWeek + 1; i++) {
        PdfPCell c1 = new PdfPCell(new Phrase(WeekDay[i]));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);
        if (i == daysPerWeek) {
            table.setHeaderRows(1);
        }
    }
    double calc = 0;
    // Simplify the Date since we just need the time
    SimpleDateFormat df = new SimpleDateFormat("HH:mm");
    Date start = null;
    Date uSize = null;
    try {
        start = df.parse(App.theSettings.getStartingTimeH() + ":" + App.theSettings.getStartingTimeM());
        uSize = new Date(MINUTES.toMillis(App.theSettings.getUnitsSize()));
    } catch (ParseException e) {
    }
    // We take the first day to get the number of units and so the number of
    // times we have to run this.
    for (int j = 0; j < Tools.calcRows(); j++) {
        calc = j == 0 ? start.getTime() : (calc + (uSize.getTime()));

        // For each day available, we run this loop once.
        for (int k = 1; k < daysPerWeek + 1; k++) {
            Units u = room.getUnitByRowCol(k, j);
            // If it's the first day, we also want a first cell per line
            // containing the time this unit starts
            if (k == 1) {
                table.addCell(df.format(calc));
                // Check whether a room is given
                String teacher = " ";
                if (u != null) {
                    teacher = u.toString();
                }
                table.addCell(teacher);
            } else {
                // If it's not the first day, we don't need to print the
                // start time again
                String teacher = " ";
                if (u != null) {
                    teacher = u.toString();
                }
                table.addCell(teacher);
            }
        }
    }

    // Add the whole table we've just created to the pdf file
    subCatPart.add(table);

}

From source file:CTD.planer2.util.ExportToPdf.java

private static void createDayTable(Section subCatPart) throws BadElementException {

    List<Person> personList = App.theSemester.getPersonList();

    PdfPTable table = new PdfPTable(personList.size() + 1);

    PdfPCell c1 = new PdfPCell(new Phrase(" "));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);//from   www.j a  v a  2  s. c o m

    for (Person p : personList) {

        c1 = new PdfPCell(new Phrase(p.toString()));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);

        table.setHeaderRows(1);
        int k = 1;
        // We take the first person to get the number of units and so the
        // number
        // of
        // times we have to run this.

        for (int j = 1; j < p.getEntity().size(); j++) {
            // For each person available, we run this loop once.

            List<Units> tmp = p.getEntity();

            if (k == 1) {
                SimpleDateFormat df = new SimpleDateFormat("HH:mm");
                String time = df.format(tmp.get(j).getTime());
                table.addCell(time);
                String classes = " ";
                // Check whether a class is given
                if (tmp.get(j).getClasses().size() < 1) {
                    classes = " ";
                } else {
                    classes = tmp.get(j).getClasses().get(0).toString();
                }
                table.addCell(classes);
            } else {
                // If it's not the first day, we don't need to print the
                // start time again
                String classes = " ";
                // Check whether a class is given
                if (tmp.get(j).getClasses().size() < 1) {
                    classes = " ";
                } else {
                    classes = tmp.get(j).getClasses().get(0).toString();
                }
                table.addCell(classes);
            }
            k = k + 1;
        }

    }

    // Add the whole table we've just created to the pdf file
    subCatPart.add(table);

}

From source file:dbedit.actions.ExportPdfAction.java

License:Open Source License

@Override
protected void performThreaded(ActionEvent e) throws Exception {
    boolean selection = false;
    JTable table = ResultSetTable.getInstance();
    if (table.getSelectedRowCount() > 0 && table.getSelectedRowCount() != table.getRowCount()) {
        Object option = Dialog.show("PDF", "Export", Dialog.QUESTION_MESSAGE,
                new Object[] { "Everything", "Selection" }, "Everything");
        if (option == null || "-1".equals(option.toString())) {
            return;
        }// ww w.j a  va  2  s .  co  m
        selection = "Selection".equals(option);
    }
    List list = ((DefaultTableModel) table.getModel()).getDataVector();
    int columnCount = table.getColumnCount();
    PdfPTable pdfPTable = new PdfPTable(columnCount);
    pdfPTable.setWidthPercentage(100);
    pdfPTable.getDefaultCell().setPaddingBottom(4);
    int[] widths = new int[columnCount];

    // Row Header
    pdfPTable.getDefaultCell().setBorderWidth(2);
    for (int i = 0; i < columnCount; i++) {
        String columnName = table.getColumnName(i);
        pdfPTable.addCell(new Phrase(columnName, ROW_HEADER_FONT));
        widths[i] = Math.min(50000, Math.max(widths[i], ROW_HEADER_BASE_FONT.getWidth(columnName + " ")));
    }
    pdfPTable.getDefaultCell().setBorderWidth(1);
    if (!list.isEmpty()) {
        pdfPTable.setHeaderRows(1);
    }

    // Body
    for (int i = 0; i < list.size(); i++) {
        if (!selection || table.isRowSelected(i)) {
            List record = (List) list.get(i);
            for (int j = 0; j < record.size(); j++) {
                Object o = record.get(j);
                if (o != null) {
                    if (ResultSetTable.isLob(j)) {
                        o = Context.getInstance().getColumnTypeNames()[j];
                    }
                } else {
                    o = "";
                }
                PdfPCell cell = new PdfPCell(new Phrase(o.toString()));
                cell.setPaddingBottom(4);
                if (o instanceof Number) {
                    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                }
                pdfPTable.addCell(cell);
                widths[j] = Math.min(50000, Math.max(widths[j], BASE_FONT.getWidth(o.toString())));
            }
        }
    }

    // Size
    pdfPTable.setWidths(widths);
    int totalWidth = 0;
    for (int width : widths) {
        totalWidth += width;
    }
    Rectangle pageSize = PageSize.A4.rotate();
    pageSize.setRight(pageSize.getRight() * Math.max(1f, totalWidth / 53000f));
    pageSize.setTop(pageSize.getTop() * Math.max(1f, totalWidth / 53000f));

    // Document
    Document document = new Document(pageSize);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    PdfWriter writer = PdfWriter.getInstance(document, byteArrayOutputStream);
    document.open();
    pdfTemplate = writer.getDirectContent().createTemplate(100, 100);
    pdfTemplate.setBoundingBox(new Rectangle(-20, -20, 100, 100));
    writer.setPageEvent(this);
    document.add(pdfPTable);
    document.close();
    FileIO.saveAndOpenFile("export.pdf", byteArrayOutputStream.toByteArray());
}

From source file:de.aw.awlib.pdf.PDFDocument.java

License:Open Source License

/**
 * Erstellt eine Tabelle im pdf// w w w .j  a  v  a2  s .c  om
 *
 * @param columnHeaders
 *         Header der Tabellenspalten
 * @param rowCount
 *         Anzahl der Tabellenzeilen
 * @throws DocumentException
 *         wenn das Document nicht erstellt werden kann.
 */
public void createTable(@NonNull String[] columnHeaders, @Nullable String summary, int rowCount,
        CellCreator creator) throws DocumentException {
    if (summary != null) {
        addTableTitle(summary);
    }
    PdfPTable table = new PdfPTable(columnHeaders.length);
    // t.setBorderColor(BaseColor.GRAY);
    // t.setPadding(4);
    // t.setSpacing(4);
    // t.setBorderWidth(1);
    for (String columnHeader : columnHeaders) {
        PdfPCell c1 = new PdfPCell(new Phrase(columnHeader));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);
    }
    table.setHeaderRows(1);
    for (int row = 0; row < rowCount; row++) {
        for (int column = 0; column < columnHeaders.length; column++) {
            table.addCell(creator.getCellContent(row, column));
        }
    }
    mDocument.add(table);
}