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

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

Introduction

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

Prototype

public PdfPTable(PdfPTable table) 

Source Link

Document

Constructs a copy of a PdfPTable.

Usage

From source file:lmcpointofsalessystem.PDFCustomersEmployee.java

public PdfPTable getDatas(String tblName) {
    PdfPTable headerTable = new PdfPTable(1);
    String newT = tblName.toString();
    try {/*from   w  ww . j  a  v a  2  s.  c  om*/
        rs = s.executeQuery(
                "select C.CustomerID, C.FirstName, C.LastName, C.Address, C.ContactNumber from Customers C"); //alias lang ung "E"
        String columnExe = "";
        columnExe = "CustomerID,FirstName,LastName,Address,ContactNumber";//pdf column names
        String[] colH = columnExe.split(",");
        int colL = 0;
        colL = columnExe.split(",").length;
        headerTable = new PdfPTable(colL);

        for (int x = 0; x < colL; x++) {
            if (colH[x].toString().equals("C.CustomerID")) {
                colH[x] = "OrderNo1";
            } else if (colH[x].toString().equals("C.FirstName")) {
                colH[x] = "O.CustNo";
            } else if (colH[x].toString().equals("C.LastName")) {
                colH[x] = "OrderDate";
            } else if (colH[x].toString().equals("C.Address")) {
                colH[x] = "ItemDesc";
            } else if (colH[x].toString().equals("C.ContactNumber")) {
                colH[x] = "Unit";
            }

            PdfPCell newHeader = new PdfPCell();
            newHeader.addElement(new Paragraph(colH[x]));
            headerTable.addCell(newHeader);
        }

        //System.out.println(""+columnExe);
        rs = st.executeQuery("Select " + columnExe + " from Customers C");
        int colNums = colH.length;
        int colCount = 0;
        while (rs.next() == true) {
            for (int x = 1; x <= colL; x++) {
                colCount += 1;

                PdfPCell newCell = new PdfPCell();
                newCell.addElement(new Paragraph(rs.getString(x)));
                headerTable.setWidthPercentage(90);
                headerTable.addCell(newCell);
            }
        }

        float[] widths2 = new float[colNums];

        for (int i = 0; i < colNums; i++) {
            widths2[i] = 150;
        }
        try {
            headerTable.setWidths(widths2);
        } catch (DocumentException ex) {
            Logger.getLogger(PDFCustomersEmployee.class.getName()).log(Level.SEVERE, null, ex);
        }
    } catch (SQLException ex) {
        Logger.getLogger(PDFCustomersEmployee.class.getName()).log(Level.SEVERE, null, ex);
    }

    return headerTable;
}

From source file:lmcpointofsalessystem.PDFOrders.java

public PdfPTable getDatas(String tblName) {
    ;/*from   ww  w  . ja v a 2  s .  c  om*/
    PdfPTable headerTable = new PdfPTable(1);
    String newT = tblName.toString();
    String col1 = co.tblOrder.getColumnName(0);
    String col2 = co.tblOrder.getColumnName(1);
    int nrow = co.tblModel.getRowCount();
    int ncol = co.tblModel.getColumnCount();
    Object[][] tabledata = new Object[nrow][ncol];
    for (int i = 0; i < nrow; i++) {
        for (int j = 0; j < ncol; j++) {
            tabledata[i][j] = co.tblModel.getValueAt(i, j);
        }
    }
    String columnExe = "";
    columnExe = "empID,Fname,Lname,Username,Password,Address,Contact,Type";
    String[] colH = columnExe.split(",");
    int colL = 0;
    colL = columnExe.split(",").length;
    headerTable = new PdfPTable(colL);
    for (int x = 0; x < colL; x++) {
        if (colH[x].toString().equals(col1)) {
            colH[x] = "OrderNo1";
        } else if (colH[x].toString().equals(col2)) {
            colH[x] = "O.CustNo";
        }

        PdfPCell newHeader = new PdfPCell();
        newHeader.addElement(new Paragraph(colH[x]));
        headerTable.addCell(newHeader);
    }
    int colNums = colH.length;
    int colCount = 0;
    for (int x = 1; x <= colL; x++) {
        colCount += 1;

        PdfPCell newCell = new PdfPCell();
        newCell.addElement(new Paragraph((x)));
        headerTable.setWidthPercentage(90);
        headerTable.addCell(newCell);
    }
    float[] widths2 = new float[colNums];
    for (int i = 0; i < colNums; i++) {
        widths2[i] = 150;
    }
    try {
        headerTable.setWidths(widths2);
    } catch (DocumentException ex) {
        Logger.getLogger(PDFEmployees.class.getName()).log(Level.SEVERE, null, ex);
    }

    return headerTable;
}

From source file:lt.bsprendimai.ddesk.pdf.PDFTicket.java

License:Apache License

private void writeClientInfo(Document doc) throws Exception {
    PdfPTable tb = new PdfPTable(2);
    tb.setWidthPercentage(100.0f);//from w w  w .  j av a2  s  . c  o m
    tb.setSpacingAfter(20.0f);

    PdfPCell cl = new PdfPCell(
            new Phrase(this.client.getName() + "\n" + this.client.getAdress(), new Font(baseArial, 10)));
    tb.addCell(cl);

    cl = new PdfPCell(new Phrase(this.we.getName() + "\n" + this.we.getAdress(), new Font(baseArial, 10)));
    tb.addCell(cl);

    doc.add(tb);

}

From source file:lt.bsprendimai.ddesk.pdf.PDFTicket.java

License:Apache License

private void writeTicketInfo(Document doc) throws Exception {
    Paragraph pg = new Paragraph("#" + tt.getUniqueId(), new Font(baseArial, 12, Font.BOLD));
    doc.add(pg);/*from  w w  w . j  a v a  2 s .  c  om*/

    PdfPTable tb = new PdfPTable(1);
    tb.setWidthPercentage(100.0f);
    tb.setSpacingBefore(5.0f);
    tb.setSpacingAfter(5.0f);

    PdfPCell cl = new PdfPCell(new Phrase(tt.getName(), new Font(baseArial, 10, Font.BOLD)));

    tb.addCell(cl);

    if (clientPerson != null) {
        cl = new PdfPCell(new Phrase(
                "Prane: " + clientPerson.getName() + " (Telefono Nr: " + clientPerson.getPhoneNo() + ")",
                new Font(baseArial, 10)));
        tb.addCell(cl);
    }

    cl = new PdfPCell(new Phrase("Uduoties informacija: ", new Font(baseArial, 10)));
    tb.addCell(cl);

    cl = new PdfPCell(new Phrase(tt.getDescription(), new Font(baseArial, 10)));

    tb.addCell(cl);

    doc.add(tb);
}

From source file:lt.bsprendimai.ddesk.pdf.PDFTicket.java

License:Apache License

private void writeWorkerInfo(Document doc) throws Exception {

    PdfPTable tb = new PdfPTable(2);
    tb.setWidthPercentage(100.0f);/*from   w w w  .  j  av a  2s.  co m*/
    tb.setSpacingBefore(8.0f);
    tb.setSpacingAfter(8.0f);

    PdfPCell cl;

    cl = new PdfPCell(new Phrase("Atsakingas asmuo: " + me.getName(), new Font(baseArial, 10)));
    cl.setColspan(2);
    tb.addCell(cl);

    cl = new PdfPCell(new Phrase("vykdymo data: " + timeFormat(tt.getDateClosed()), new Font(baseArial, 10)));
    tb.addCell(cl);

    if (tt.getWorktime() != null) {
        cl = new PdfPCell(new Phrase("Darbo valandos:" + tt.getWorktime(), new Font(baseArial, 10)));
        tb.addCell(cl);
    } else {
        cl = new PdfPCell(new Phrase("Darbo valandos: ", new Font(baseArial, 10)));
        tb.addCell(cl);
    }

    doc.add(tb);

    tb = new PdfPTable(2);

    tb.setWidthPercentage(100.0f);
    tb.setSpacingBefore(50.0f);

    cl = new PdfPCell(new Phrase("Kliento paraas\n\n\n\n", new Font(baseArial, 10)));
    cl.setBorder(0);
    tb.addCell(cl);

    cl = new PdfPCell(new Phrase("Uduot atliks darbuotojas\n\n\n\n", new Font(baseArial, 10)));
    cl.setBorder(0);
    tb.addCell(cl);
    doc.add(tb);

}

From source file:lt.bsprendimai.ddesk.pdf.PDFTicket.java

License:Apache License

private void writeJobInfo(Document doc) throws Exception {

    Paragraph pg = new Paragraph("\nUDUOTIES ATLIKIMO INFORMACIJA", new Font(baseArial, 10, Font.BOLD));
    doc.add(pg);/*  ww w .  j  a  v  a2s . c o  m*/

    PdfPTable tb = new PdfPTable(3);
    tb.setWidthPercentage(100.0f);
    tb.setSpacingBefore(5.0f);
    tb.setSpacingAfter(12.0f);
    tb.setWidths(new float[] { 6.0f, 84.0f, 10.0f });

    PdfPCell cl;

    doc.add(new Phrase("\nAtlikti darbai", new Font(baseArial, 12, Font.BOLD)));

    cl = new PdfPCell(new Phrase("Eil.nr", new Font(baseArial, 10, Font.BOLD)));
    tb.addCell(cl);
    cl = new PdfPCell(new Phrase("Uduoties pavadinimas", new Font(baseArial, 10, Font.BOLD)));
    tb.addCell(cl);
    cl = new PdfPCell(new Phrase("Valandos", new Font(baseArial, 10, Font.BOLD)));
    tb.addCell(cl);

    doc.add(tb);

}

From source file:mitm.common.pdf.MessagePDFBuilder.java

License:Open Source License

private void addReplyLink(Document document, String replyURL) throws DocumentException {
    PdfPTable replyTable = new PdfPTable(1);
    replyTable.setWidthPercentage(100f);

    replyTable.setSplitLate(false);//from ww  w .  j a  v  a2  s  . c om

    replyTable.setSpacingBefore(5f);
    replyTable.setHorizontalAlignment(Element.ALIGN_LEFT);

    Font linkFont = new Font();

    linkFont.setStyle(Font.BOLD);
    linkFont.setColor(0, 0, 255);
    linkFont.setSize(headerFontSize);

    Chunk anchor = new Chunk("Reply", linkFont);

    anchor.setAnchor(replyURL);

    Phrase phrase = new Phrase();

    phrase.add(anchor);

    PdfPCell cell = new PdfPCell(phrase);
    cell.setBorder(Rectangle.NO_BORDER);

    replyTable.addCell(cell);

    document.add(replyTable);
}

From source file:mitm.common.pdf.MessagePDFBuilder.java

License:Open Source License

public void buildPDF(MimeMessage message, String replyURL, OutputStream pdfStream)
        throws DocumentException, MessagingException, IOException {
    Document document = createDocument();

    PdfWriter pdfWriter = createPdfWriter(document, pdfStream);

    document.open();//from w  w  w. j  a  v  a 2 s .c o m

    String[] froms = null;

    try {
        froms = EmailAddressUtils.addressesToStrings(message.getFrom(), true /* mime decode */);
    } catch (MessagingException e) {
        logger.warn("From address is not a valid email address.");
    }

    if (froms != null) {
        for (String from : froms) {
            document.addAuthor(from);
        }
    }

    String subject = null;

    try {
        subject = message.getSubject();
    } catch (MessagingException e) {
        logger.error("Error getting subject.", e);
    }

    if (subject != null) {
        document.addSubject(subject);
        document.addTitle(subject);
    }

    String[] tos = null;

    try {
        tos = EmailAddressUtils.addressesToStrings(message.getRecipients(RecipientType.TO),
                true /* mime decode */);
    } catch (MessagingException e) {
        logger.warn("To is not a valid email address.");
    }

    String[] ccs = null;

    try {
        ccs = EmailAddressUtils.addressesToStrings(message.getRecipients(RecipientType.CC),
                true /* mime decode */);
    } catch (MessagingException e) {
        logger.warn("CC is not a valid email address.");
    }

    Date sentDate = null;

    try {
        sentDate = message.getSentDate();
    } catch (MessagingException e) {
        logger.error("Error getting sent date.", e);
    }

    Collection<Part> attachments = new LinkedList<Part>();

    String body = BodyPartUtils.getPlainBodyAndAttachments(message, attachments);

    attachments = preprocessAttachments(attachments);

    if (body == null) {
        body = MISSING_BODY;
    }

    /*
     * PDF does not have tab support so we convert tabs to spaces
     */
    body = StringReplaceUtils.replaceTabsWithSpaces(body, tabWidth);

    PdfPTable headerTable = new PdfPTable(2);

    headerTable.setHorizontalAlignment(Element.ALIGN_LEFT);
    headerTable.setWidthPercentage(100);
    headerTable.setWidths(new int[] { 1, 6 });
    headerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);

    Font headerFont = createHeaderFont();

    FontSelector headerFontSelector = createHeaderFontSelector();

    PdfPCell cell = new PdfPCell(new Paragraph("From:", headerFont));
    cell.setBorder(Rectangle.NO_BORDER);
    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

    headerTable.addCell(cell);

    String decodedFroms = StringUtils.defaultString(StringUtils.join(froms, ", "));

    headerTable.addCell(headerFontSelector.process(decodedFroms));

    cell = new PdfPCell(new Paragraph("To:", headerFont));
    cell.setBorder(Rectangle.NO_BORDER);
    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

    headerTable.addCell(cell);
    headerTable.addCell(headerFontSelector.process(StringUtils.defaultString(StringUtils.join(tos, ", "))));

    cell = new PdfPCell(new Paragraph("CC:", headerFont));
    cell.setBorder(Rectangle.NO_BORDER);
    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

    headerTable.addCell(cell);
    headerTable.addCell(headerFontSelector.process(StringUtils.defaultString(StringUtils.join(ccs, ", "))));

    cell = new PdfPCell(new Paragraph("Subject:", headerFont));
    cell.setBorder(Rectangle.NO_BORDER);
    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

    headerTable.addCell(cell);
    headerTable.addCell(headerFontSelector.process(StringUtils.defaultString(subject)));

    cell = new PdfPCell(new Paragraph("Date:", headerFont));
    cell.setBorder(Rectangle.NO_BORDER);
    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

    headerTable.addCell(cell);
    headerTable.addCell(ObjectUtils.toString(sentDate));

    cell = new PdfPCell(new Paragraph("Attachments:", headerFont));
    cell.setBorder(Rectangle.NO_BORDER);
    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

    headerTable.addCell(cell);
    headerTable
            .addCell(headerFontSelector.process(StringUtils.defaultString(getAttachmentHeader(attachments))));

    document.add(headerTable);

    if (replyURL != null) {
        addReplyLink(document, replyURL);
    }

    /*
     * Body table will contain the body of the message
     */
    PdfPTable bodyTable = new PdfPTable(1);
    bodyTable.setWidthPercentage(100f);

    bodyTable.setSplitLate(false);

    bodyTable.setSpacingBefore(15f);
    bodyTable.setHorizontalAlignment(Element.ALIGN_LEFT);

    addBodyAndAttachments(pdfWriter, document, bodyTable, body, attachments);

    Phrase footer = new Phrase(FOOTER_TEXT);

    PdfContentByte cb = pdfWriter.getDirectContent();

    ColumnText.showTextAligned(cb, Element.ALIGN_RIGHT, footer, document.right(), document.bottom(), 0);

    document.close();
}

From source file:mx.avanti.siract.ui.RACTBeanUI.java

public void postProcessPDF(Object document) throws IOException, DocumentException {
    final Document pdf = (Document) document;
    TreeNode[] selectedNodesPDF = selectedNodes;

    if (selectedNodes != null) {
        for (TreeNode nodo : selectedNodes) {
            System.out.println("*********************" + ((NodoMultiClass) nodo.getData()).getNombre());
        }/*  w w w  . j a  v  a2  s.  c  o m*/
    }
    pdf.setPageSize(PageSize.A4.rotate());
    pdf.open();
    String nombrep = profesor.getPronombre() + " " + profesor.getProapellidoPaterno() + " "
            + profesor.getProapellidoMaterno();
    String numEmpPro = Integer.toString(profesor.getPronumeroEmpleado());
    String porAv = Float.toString(porcentajeAvance);
    SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");

    //Obtener el nombre del programa educativo seleccionado
    String nombreProgEdu = "";
    int programaEducativoSeleccionado2 = Integer.parseInt(programaEducativoSeleccionado);
    for (int x = 0; x < programasEducativos.size(); x++) {
        if (programasEducativos.get(x).getPedid() == programaEducativoSeleccionado2) {
            nombreProgEdu = programasEducativos.get(x).getPednombre();
        }
    }
    //----------------------------------------------------------------------------------

    //Obtener el nombre de la unidad de aprendizaje y clave seleccionada
    String nombreUniApr = "";
    String nombreclave = "";
    int uniAprselec2 = Integer.parseInt(unidadAprendizajeSeleccionada);
    for (int x = 0; x < unidadesaprendisaje.size(); x++) {
        if (unidadesaprendisaje.get(x).getUapclave() == uniAprselec2) {
            nombreUniApr = unidadesaprendisaje.get(x).getUapnombre();
            nombreclave = Integer.toString(unidadesaprendisaje.get(x).getUapclave());
        }
    }
    //----------------------------------------------------------------------

    // rutaImagen es la ruta para acceder a la imagen guardada en el folder resources del proyecto
    try {
        //            Image imagenLogo = Image.getInstance("C:\\Users\\Y\\Desktop\\RACT 22-01-2015\\RACT\\build\\web\\resources\\imagenes\\logo.jpg");
        Image imagenLogo = Image.getInstance(RACTBeanUI.class.getResource("imagenes/logo.jpg"));

        //Posicion de imagen (Horizontal, Vertiacal)
        imagenLogo.setAbsolutePosition(120f, 460f);

        //Tamao de imagen (Ancho, largo)
        imagenLogo.scaleAbsolute(90, 120);
        //imagenLogo.scaleAbsoluteWidth(100f);
        //imagenLogo.scaleAbsoluteHeight(150f);
        //imagenLogo.scaleToFit(100f, 120f); Esta es la buena
        //Image imagenLogo = Image.getInstance("http://ed.uabc.mx/sed/images/logo.jpg");
        //imagenLogo.scaleAbsolute(70f, 90f);
        pdf.add(imagenLogo);
    } catch (Exception exception) {
        System.out.println("****NO SE ENCONTRO LA RUTA DE IMAGEN ESPECIFICADA");
    }
    //Tabla con UABC y Nombre del profesor(a)
    PdfPTable pdfTabletitulo = new PdfPTable(2);
    pdfTabletitulo.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
    PdfPTable pdfTabletitulo2 = new PdfPTable(2);
    pdfTabletitulo2.getDefaultCell().setBorder(PdfPCell.NO_BORDER);

    Paragraph UABC = new Paragraph("Universidad Autnoma de Baja California",
            FontFactory.getFont(FontFactory.TIMES, 22, Font.BOLD, new Color(0, 113, 65)));
    UABC.setAlignment(Element.ALIGN_CENTER);
    Paragraph esp = new Paragraph(" ");
    pdf.add(UABC);
    pdf.add(esp);
    pdf.add(esp);
    pdf.add(esp);
    pdf.add(esp);
    pdfTabletitulo.addCell(new Paragraph(""));
    pdfTabletitulo.addCell(new Paragraph(""));
    pdfTabletitulo.addCell(new Paragraph(""));
    pdfTabletitulo.addCell(new Paragraph(""));
    pdfTabletitulo.addCell(new Paragraph(""));
    pdfTabletitulo.addCell(new Paragraph(""));
    pdfTabletitulo.addCell(new Paragraph(""));
    pdfTabletitulo.addCell(new Paragraph(""));
    pdfTabletitulo.addCell(new Paragraph(""));
    pdfTabletitulo.addCell(new Paragraph(""));

    pdfTabletitulo.addCell(new Paragraph("Profesor(a): ",
            FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, new Color(0, 0, 0))));
    pdfTabletitulo.addCell(new Paragraph(nombrep));

    pdfTabletitulo2.addCell(new Paragraph("Num. de Empleado: ",
            FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, new Color(0, 0, 0))));
    pdfTabletitulo2.addCell(new Paragraph(numEmpPro));

    pdfTabletitulo.setHorizontalAlignment(25);
    //pdfTabletitulo.setHorizontalAlignment(Element.ALIGN_CENTER);
    //document.add(table);
    float[] columnWidthsss = new float[] { 4f, 28 };
    pdfTabletitulo.setWidths(columnWidthsss);
    pdf.add(pdfTabletitulo);

    float[] columnWidthss = new float[] { 10f, 38 };
    pdfTabletitulo2.setWidths(columnWidthss);
    pdf.add(pdfTabletitulo2);

    pdf.add(new Phrase(" "));

    //----------------------------------------------------------------------
    //Tabla Cabezera
    PdfPTable pdftablecabezera = new PdfPTable(4);
    pdftablecabezera.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
    PdfPTable pdftablecabezera2 = new PdfPTable(5);
    pdftablecabezera2.getDefaultCell().setBorder(PdfPCell.NO_BORDER);

    pdftablecabezera.addCell(new Paragraph("Programa educativo: ",
            FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, new Color(0, 0, 0))));
    pdftablecabezera.addCell(new Paragraph("Fecha: ",
            FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, new Color(0, 0, 0))));
    pdftablecabezera.addCell(new Paragraph("Ciclo Escolar: ",
            FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, new Color(0, 0, 0))));
    pdftablecabezera.addCell(new Paragraph("Avance Global: ",
            FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, new Color(0, 0, 0))));
    pdftablecabezera.addCell(new Paragraph(nombreProgEdu));
    pdftablecabezera.addCell(new Paragraph(formato.format(new Date())));
    pdftablecabezera.addCell(new Paragraph("        " + cicloEscolar));
    pdftablecabezera.addCell(new Paragraph("        " + porAv));

    pdftablecabezera.addCell(new Paragraph(" "));
    pdftablecabezera.addCell(new Paragraph(" "));
    pdftablecabezera.addCell(new Paragraph(" "));
    pdftablecabezera.addCell(new Paragraph(" "));

    pdftablecabezera2.addCell(new Paragraph("Unidad de Aprendizaje: ",
            FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, new Color(0, 0, 0))));
    pdftablecabezera2.addCell(new Paragraph("Clave: ",
            FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, new Color(0, 0, 0))));
    pdftablecabezera2.addCell(new Paragraph("Grupo: ",
            FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, new Color(0, 0, 0))));
    pdftablecabezera2.addCell(new Paragraph("Subgrupo: ",
            FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, new Color(0, 0, 0))));
    pdftablecabezera2.addCell(new Paragraph("Tipo Grupo: ",
            FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, new Color(0, 0, 0))));
    pdftablecabezera2.addCell(new Paragraph(nombreUnidadSeleccionado));
    pdftablecabezera2.addCell(new Paragraph(claveUnidadAprendizajeSeleccionada));
    pdftablecabezera2.addCell(new Paragraph("   " + grupo));
    pdftablecabezera2.addCell(new Paragraph("       " + subGrupo));
    String tipoGrupo = "";
    switch (this.tipoUnidadAprendizaje) {
    case "C":
        tipoGrupo = "Clase";
        break;
    case "L":
        tipoGrupo = "Laboratorio";
        break;
    case "T":
        tipoGrupo = "Taller";
        break;
    case "P":
        tipoGrupo = "Practica";
        break;
    case "CL":
        tipoGrupo = "Practicas Clinica";
        break;
    }
    pdftablecabezera2.addCell(new Paragraph("       " + tipoGrupo));
    pdftablecabezera2.addCell(new Paragraph(" "));

    pdftablecabezera.setHorizontalAlignment(25);
    float[] columnWidths = new float[] { 38f, 10f, 14f, 18f };
    pdftablecabezera.setWidths(columnWidths);
    pdf.add(pdftablecabezera);

    pdftablecabezera2.setHorizontalAlignment(25);
    float[] columnWidthss2 = new float[] { 38f, 10f, 8f, 11f, 14f };
    pdftablecabezera2.setWidths(columnWidthss2);
    pdf.add(pdftablecabezera2);

    pdf.add(new Phrase(" "));

    //----------------------------------------------------------------------
    Paragraph numrep = new Paragraph("Reporte # " + numeroReporte,
            FontFactory.getFont(FontFactory.TIMES, 16, Font.BOLD, new Color(0, 0, 0)));
    numrep.setAlignment(Element.ALIGN_CENTER);
    pdf.add(numrep);
    pdf.add(new Paragraph(" "));
    //Tabla con Datos 
    PdfPTable pdfTable = new PdfPTable(3);
    pdfTable.addCell(new Phrase("Nombre",
            FontFactory.getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, new Color(0, 0, 0))));
    pdfTable.addCell(new Phrase("Porcentaje",
            FontFactory.getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, new Color(0, 0, 0))));
    pdfTable.addCell(new Phrase("Observaciones",
            FontFactory.getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, new Color(0, 0, 0))));

    //Evitar Null pointer exception por no tener nodoes en selectedNodes
    //Se utiliza un auxiliar de selectedNodes por que hay posibilidad de que selectedNodes se modifique durante el proceso de generacion del PDF
    if (selectedNodesPDF != null && selectedNodesPDF.length > 0) {

        //Regresar a lo basicoString
        int nns = selectedNodesPDF.length;
        String[] ns = new String[nns];
        for (int x = 0; x < selectedNodesPDF.length; x++) {
            ns[x] = ((NodoMultiClass) selectedNodesPDF[x].getData()).getNumero() + "--"
                    + ((NodoMultiClass) selectedNodes[x].getData()).getNombre() + "--"
                    + ((NodoMultiClass) selectedNodes[x].getData()).getPorcentajeAvance() + "--"
                    + ((NodoMultiClass) selectedNodes[x].getData()).getObservaciones() + " -- ";
        }
        String[] filas = new String[4];
        String[] nstr = new String[3];

        String[] filas2 = new String[4];
        String[] nstr2 = new String[3];

        for (int x = 1; x < ns.length; x++) {
            for (int y = 0; y < ns.length - x; y++) {
                //Obtengo los valores para hacer las comparaciones
                int[] n = new int[3];
                int[] n2 = new int[3];
                filas = ns[y].split("--");
                nstr = filas[0].split("\\.");
                for (int z = 0; z < nstr.length; z++) {
                    if (nstr == null) {
                        n[z] = 0;
                    } else {
                        n[z] = Integer.parseInt(nstr[z]);
                    }
                }
                filas2 = ns[y + 1].split("--");
                nstr2 = filas2[0].split("\\.");
                for (int z = 0; z < nstr2.length; z++) {
                    if (nstr2 == null) {
                        n2[z] = 0;
                    } else {
                        n2[z] = Integer.parseInt(nstr2[z]);
                    }
                }
                //-------------------------------------------------comparacion
                if (n[0] == n2[0]) {
                    if (n[1] == n2[1]) {
                        if (n[2] > n2[2]) {
                            String aux = ns[y];
                            ns[y] = ns[y + 1];
                            ns[y + 1] = aux;
                        }
                    } else {
                        if (n[1] > n2[1]) {
                            String aux = ns[y];
                            ns[y] = ns[y + 1];
                            ns[y + 1] = aux;
                        }
                    }
                } else {
                    if (n[0] > n2[0]) {
                        String aux = ns[y];
                        ns[y] = ns[y + 1];
                        ns[y + 1] = aux;
                    }
                }
                //-------------------------------------------------------------
            }
        }

        String[] auxNum = new String[4];
        for (int x = 0; x < ns.length; x++) {

            filas = ns[x].split("--");
            num = filas[0].split("\\.");

            //Auxiliar para agregar padre de tema/subtema
            int auxMargen = 1;
            //Agregar unidad a la que pertenece el tema/subtema

            String[] auxNum2 = auxNum;
            int tamanoArbol = root.getChildCount();
            //AGREGAR A TEMA
            if (Integer.parseInt(num[0]) > tamanoArbol) {
                auxMargen = Integer.parseInt(num[0]) - tamanoArbol;
            }
            if (num.length >= 2 && auxNum2[0] != null && !auxNum2[0].equals(num[0])) {
                if (!num[1].equals("0")) {
                    while (!num[0].equals(auxNum2[0]) && auxMargen > 0) {
                        System.out.println("XXXXXXIteracion  para encontrar padre XXXXXXX 0" + auxMargen);
                        auxNum2 = (((NodoMultiClass) root.getChildren()
                                .get(Integer.parseInt(num[0]) - auxMargen).getData()).getNumero()).split("\\.");
                        //if(auxNum[0]!=null&&Integer.parseInt(num[0])>Integer.parseInt(auxNum[0])){
                        if (num[0].equals(auxNum2[0])) {

                        } else {
                            auxMargen--;
                        }

                    }
                    System.out.println("***Unidad Padre" + ((NodoMultiClass) root.getChildren()
                            .get(Integer.parseInt(num[0]) - auxMargen).getData()).getNombre());
                    NodoMultiClass auxNodo = ((NodoMultiClass) root.getChildren()
                            .get(Integer.parseInt(num[0]) - auxMargen).getData());
                    //UTIL PARA PONER TEXTO TACHADO
                    //                     Chunk strikethrough = new Chunk("Strikethrough.");
                    //                      strikethrough.setUnderline(0.1f, 3f); //0.1 thick, 2 y-location
                    //                     document.add(strikethrough);
                    pdfTable.addCell(new Phrase(auxNodo.getNumero() + ".- " + auxNodo.getNombre(), FontFactory
                            .getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, new Color(154, 151, 151))));
                    pdfTable.addCell(new Phrase(auxNodo.getPorcentajeAvance(), FontFactory
                            .getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, new Color(154, 151, 151))));
                    pdfTable.addCell(auxNodo.getObservaciones());

                }
            } else {
                if (auxNum2[0] == null && num.length >= 2) {
                    auxNum2 = (((NodoMultiClass) root.getChildren().get(Integer.parseInt(num[0]) - auxMargen)
                            .getData()).getNumero()).split("\\.");
                    while (!num[0].equals(auxNum2[0]) && auxMargen > 0) {
                        System.out.println("XXXXXXIteracion  para encontrar padre XXXXXXX 0" + auxMargen);
                        auxNum2 = (((NodoMultiClass) root.getChildren()
                                .get(Integer.parseInt(num[0]) - auxMargen).getData()).getNumero()).split("\\.");
                        //if(auxNum[0]!=null&&Integer.parseInt(num[0])>Integer.parseInt(auxNum[0])){
                        if (num[0].equals(auxNum2[0])) {

                        } else {
                            auxMargen--;
                        }
                    }
                    System.out.println("***Unidad Padre" + ((NodoMultiClass) root.getChildren()
                            .get(Integer.parseInt(num[0]) - auxMargen).getData()).getNombre());
                    NodoMultiClass auxNodo = ((NodoMultiClass) root.getChildren()
                            .get(Integer.parseInt(num[0]) - auxMargen).getData());
                    //UTIL PARA PONER TEXTO TACHADO
                    //                     Chunk strikethrough = new Chunk("Strikethrough.");
                    //                      strikethrough.setUnderline(0.1f, 3f); //0.1 thick, 2 y-location
                    //                     document.add(strikethrough);
                    pdfTable.addCell(new Phrase(auxNodo.getNumero() + ".- " + auxNodo.getNombre(), FontFactory
                            .getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, new Color(154, 151, 151))));
                    pdfTable.addCell(new Phrase(auxNodo.getPorcentajeAvance(), FontFactory
                            .getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, new Color(154, 151, 151))));
                    pdfTable.addCell(auxNodo.getObservaciones());

                }
            }

            //AGREGAR A SUBTEMA
            String[] auxNumeroUnidad = new String[4];
            int auxMargen2 = 1;
            if (num.length == 3 && auxNum[1] != null && !auxNum[1].equals(num[1])) {
                if (!num[2].equals("0")) {
                    while (!num[0].equals(auxNum[0]) && auxMargen >= 0) {
                        NodoMultiClass auxNodoUnidad = ((NodoMultiClass) root.getChildren()
                                .get(Integer.parseInt(num[0]) - auxMargen).getData());
                        auxNumeroUnidad = auxNodoUnidad.getNumero().split("\\.");
                        tamanoArbol = root.getChildren().get(Integer.parseInt(num[0])).getChildCount();
                        if (Integer.parseInt(num[1]) > tamanoArbol) {
                            auxMargen2 = Integer.parseInt(num[1]) - tamanoArbol;
                        }

                        while (auxNumeroUnidad[0].equals(num[0]) && !num[1].equals(auxNum[1])
                                && auxMargen > 0) {
                            System.out.println("XXXXXXIteracion  para encontrar padre XXXXXXX 0" + auxMargen);
                            auxNum = (((NodoMultiClass) root.getChildren()
                                    .get(Integer.parseInt(num[0]) - auxMargen).getChildren()
                                    .get(Integer.parseInt(num[1]) - auxMargen2).getData()).getNumero())
                                            .split("\\.");
                            //if(auxNum[0]!=null&&Integer.parseInt(num[0])>Integer.parseInt(auxNum[0])){
                            if (num[1].equals(auxNum[1])) {

                            } else {
                                auxMargen2--;
                            }

                        }
                        //                            auxNum = (((NodoMultiClass) root.getChildren().get(Integer.parseInt(num[1]) - auxMargen).getData()).getNumero()).split("\\.");
                        if (num[0].equals(auxNum[0])) {
                        } else {
                            auxMargen--;
                        }
                    }

                    System.out.println("*****Unidad Padre(SUBTEMA)"
                            + ((NodoMultiClass) root.getChildren().get(Integer.parseInt(num[0]) - auxMargen)
                                    .getChildren().get(Integer.parseInt(num[1]) - auxMargen2).getData())
                                            .getNombre());
                    NodoMultiClass auxNodo = ((NodoMultiClass) root.getChildren()
                            .get(Integer.parseInt(num[0]) - auxMargen).getChildren()
                            .get(Integer.parseInt(num[1]) - auxMargen2).getData());
                    //UTIL PARA PONER TEXTO TACHADO
                    //                     Chunk strikethrough = new Chunk("Strikethrough.");
                    //                      strikethrough.setUnderline(0.1f, 3f); //0.1 thick, 2 y-location
                    //                     document.add(strikethrough);
                    pdfTable.addCell(
                            new Phrase("   " + auxNodo.getNumero() + ".- " + auxNodo.getNombre(), FontFactory
                                    .getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, new Color(154, 151, 151))));
                    pdfTable.addCell(new Phrase(auxNodo.getPorcentajeAvance(), FontFactory
                            .getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, new Color(154, 151, 151))));
                    pdfTable.addCell(auxNodo.getObservaciones());

                }
            } else {
                if (auxNum[0] == null && num.length == 3) {
                    auxNum = (((NodoMultiClass) root.getChildren().get(Integer.parseInt(num[0]) - auxMargen)
                            .getData()).getNumero()).split("\\.");
                    while (!num[0].equals(auxNum[0]) && auxMargen > 0) {
                        NodoMultiClass auxNodoUnidad = ((NodoMultiClass) root.getChildren()
                                .get(Integer.parseInt(num[0]) - auxMargen).getData());
                        auxNumeroUnidad = auxNodoUnidad.getNumero().split("\\.");
                        tamanoArbol = root.getChildren().get(Integer.parseInt(num[0])).getChildCount();
                        if (Integer.parseInt(num[1]) > tamanoArbol) {
                            auxMargen2 = Integer.parseInt(num[1]) - tamanoArbol;
                        }
                        while (auxNumeroUnidad[0].equals(num[0]) && !num[1].equals(auxNum[1])
                                && auxMargen > 0) {
                            System.out.println("Iteracion  para encontrar padre XXXXXXX 0" + auxMargen);
                            auxNum = (((NodoMultiClass) root.getChildren()
                                    .get(Integer.parseInt(num[0]) - auxMargen).getChildren()
                                    .get(Integer.parseInt(num[1]) - auxMargen2).getData()).getNumero())
                                            .split("\\.");
                            //if(auxNum[0]!=null&&Integer.parseInt(num[0])>Integer.parseInt(auxNum[0])){
                            if (num[1].equals(auxNum[1])) {

                            } else {
                                auxMargen2--;
                            }
                        }
                        //                            auxNum = (((NodoMultiClass) root.getChildren().get(Integer.parseInt(num[1]) - auxMargen).getData()).getNumero()).split("\\.");
                        if (num[0].equals(auxNum[0])) {
                        } else {
                            auxMargen--;
                        }
                    }

                    System.out.println("***Unidad Padre(SUBTEMA)"
                            + ((NodoMultiClass) root.getChildren().get(Integer.parseInt(num[0]) - auxMargen)
                                    .getChildren().get(Integer.parseInt(num[1]) - auxMargen2).getData())
                                            .getNombre());
                    NodoMultiClass auxNodo = ((NodoMultiClass) root.getChildren()
                            .get(Integer.parseInt(num[0]) - auxMargen).getChildren()
                            .get(Integer.parseInt(num[1]) - auxMargen2).getData());
                    //UTIL PARA PONER TEXTO TACHADO
                    //                     Chunk strikethrough = new Chunk("Strikethrough.");
                    //                      strikethrough.setUnderline(0.1f, 3f); //0.1 thick, 2 y-location
                    //                     document.add(strikethrough);
                    pdfTable.addCell(
                            new Phrase("   " + auxNodo.getNumero() + ".- " + auxNodo.getNombre(), FontFactory
                                    .getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, new Color(154, 151, 151))));
                    pdfTable.addCell(new Phrase(auxNodo.getPorcentajeAvance(), FontFactory
                            .getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, new Color(154, 151, 151))));
                    pdfTable.addCell(auxNodo.getObservaciones());

                }
            }

            auxNum = num;
            //FIN AGREGAR PADRE DE TEMA/SUBTEMA 
            boolean banpor = true;
            if (num.length == 1) {
                pdfTable.addCell(new Phrase(filas[0] + ".- " + filas[1],
                        FontFactory.getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, new Color(0, 0, 0))));
                pdfTable.addCell(new Phrase(String.valueOf(dosDecimales(Float.parseFloat(filas[2]))),
                        FontFactory.getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, new Color(0, 0, 0))));
                banpor = false;
            }
            if (num.length == 2) {
                pdfTable.addCell(new Phrase("   " + filas[0] + ".- " + filas[1]));
            }
            if (num.length == 3) {
                pdfTable.addCell(new Phrase("       " + filas[0] + ".- " + filas[1],
                        FontFactory.getFont(FontFactory.TIMES_ITALIC, 12)));
                pdfTable.addCell(new Phrase(String.valueOf(dosDecimales(Float.parseFloat(filas[2]))),
                        FontFactory.getFont(FontFactory.TIMES_ITALIC, 12)));
                banpor = false;
            }
            if (banpor) {
                pdfTable.addCell(String.valueOf(dosDecimales(Float.parseFloat(filas[2]))));
                pdfTable.addCell(filas[3]);
            } else {
                pdfTable.addCell(filas[3]);
            }
        }

    } else {
        pdfTable.addCell("No hay nada seleccionado");
        pdfTable.addCell("");
        pdfTable.addCell("");
    }

    pdfTable.setHorizontalAlignment(15);
    float[] columnWidths2 = new float[] { 32f, 8f, 14f };
    pdfTable.setWidths(columnWidths2);
    pdf.add(pdfTable);
    //----------------------------------------------------------------------
}

From source file:mx.dr.util.report.impl.PdfService.java

License:Open Source License

/**
* write a label in pdf document.//from   w  w w.  ja  v a  2 s.co m
* <br/>
* escribe una etiqueta en el documento pdf.
* @param doc pdf document / documento pdf.
* @param dto object that encompasses the values of the labels to be placed in the document / objeto que engloba los valores de las etiquetas que se colocaran en el documento.
* @param offset jump on the Y axis to be given before placing the tag in the document / salto en el eje Y que se dara antes de colocar la etiqueta en el documento.
* @param table container table if applicable / contenedor de tabla si es que aplica.
* @throws Exception If an error occurs / si ocurre algun error.
*/
public void estampaEtiqueta(Document doc, Object dto, Float offset, PdfPTable table) throws Exception {
    List<Field> fields = new ArrayList<Field>();

    for (Field m : dto.getClass().getDeclaredFields()) {
        m.setAccessible(true);
        if (m.getAnnotation(DRPdfLabel.class) != null) {
            fields.add(m);
        }
    }
    Collections.sort(fields, new Comparator<Field>() {

        public int compare(Field o1, Field o2) {
            DRPdfLabel etiqueta1 = o1.getAnnotation(DRPdfLabel.class);
            DRPdfLabel etiqueta2 = o2.getAnnotation(DRPdfLabel.class);
            String uno = int2String(etiqueta1.y()) + "." + int2String(etiqueta1.order());
            String dos = int2String(etiqueta2.y()) + "." + int2String(etiqueta2.order());
            return uno.compareTo(dos);

        }

        private String int2String(int num) {
            if (num < 10) {
                return "0" + num;
            } else {
                return String.valueOf(num);
            }
        }
    });
    DRPdfLabel etiqueta;
    DRPdfTable etiquetaTabla;
    int lineaActual = 0;
    Paragraph pantagram = null;
    StringBuffer sb = null;
    Font font;
    Object valor;
    String label;
    DRPdfImage img;
    int residuo;
    int adicional = 0;
    for (Field m : fields) {
        etiqueta = m.getAnnotation(DRPdfLabel.class);
        img = m.getAnnotation(DRPdfImage.class);
        valor = m.get(dto);
        if (valor != null && valor instanceof List) {
            etiquetaTabla = m.getAnnotation(DRPdfTable.class);
            PdfPTable tableDance = null;
            if (etiquetaTabla != null) {
                tableDance = new PdfPTable(etiquetaTabla.colsPercentage());
                tableDance.setSpacingBefore(etiqueta.offset());
                for (String c : etiquetaTabla.columnLabels()) {
                    tableDance.addCell(c);
                }
            }
            if (pantagram != null) {
                doc.add(pantagram);
                pantagram = null;
            }
            for (int i = 0; i < ((List) valor).size(); i++) {
                if (i == 0 && etiqueta.offset() > 0) {
                    estampaEtiqueta(doc, ((List) valor).get(i), etiqueta.offset(), tableDance);
                } else {
                    estampaEtiqueta(doc, ((List) valor).get(i), null, tableDance);
                }
            }
            if (etiquetaTabla != null) {
                doc.add(tableDance);
            }
        } else if (img != null) {
            /* File file = new File(IMGDIR + valor);
            FileInputStream inImg = new FileInputStream(file);
            byte[] b=new byte[(int)file.length()];
            inImg.read(b);*/

            Image ima = Image.getInstance(IMGDIR + valor);

            //System.out.println(ima.getPlainWidth());
            ima.scaleAbsoluteWidth(img.width());
            //System.out.println(ima.getScaledWidth());
            ima.scaleAbsoluteHeight(ima.getScaledWidth());
            ima.setAlignment(img.style());
            ima.setAbsolutePosition(img.x(), img.y());
            doc.add(ima);

        } else if (table != null) {

            PdfPCell cerda = null;

            label = value2String(valor);
            residuo = etiqueta.length() - label.length();
            label = etiqueta.length() > 0 && residuo < 0 ? label.substring(0, etiqueta.length()) : label;
            DRPdfColumn col = m.getAnnotation(DRPdfColumn.class);
            if (col != null) {
                cerda = new PdfPCell(new Paragraph(label));
                cerda.setColspan(col.colspan());
                table.addCell(cerda);
            } else {
                table.addCell(label);
            }

        } else {
            if (lineaActual < etiqueta.y()) {
                if (pantagram != null) {
                    doc.add(pantagram);
                }
                if (offset == null || etiqueta.y() > 1) {
                    if (etiqueta.offset() > 0) {
                        pantagram = new Paragraph(etiqueta.offset());
                    } else {
                        pantagram = new Paragraph();
                    }
                } else {
                    pantagram = new Paragraph(offset);
                }
                lineaActual = etiqueta.y();
            }

            if (etiqueta.wspacesBefore() > 0) {
                sb = new StringBuffer("");
                fillEmpty(etiqueta.wspacesBefore(), sb);
                font = new Font(Font.COURIER, 12);
                pantagram.add(new Chunk(sb.toString(), font));
            }
            sb = new StringBuffer("");
            label = value2String(valor);
            residuo = etiqueta.length() - label.length();
            label = etiqueta.length() > 0 && residuo < 0 ? label.substring(0, etiqueta.length()) : label;

            if (etiqueta.font().equals(BaseFont.COURIER)) {
                font = new Font(Font.COURIER, etiqueta.fontSize(), etiqueta.style(),
                        new Color(etiqueta.color()[0], etiqueta.color()[1], etiqueta.color()[2]));
                adicional = 0;
            } else {
                font = FontFactory.getFont(TTFDIR + etiqueta.font(), BaseFont.CP1252, BaseFont.EMBEDDED,
                        etiqueta.fontSize(), etiqueta.style(),
                        new Color(etiqueta.color()[0], etiqueta.color()[1], etiqueta.color()[2]));
                adicional = label.equals("") ? (residuo / 2) + 1 : 0;
            }

            if (etiqueta.length() > 0 && etiqueta.justified().equals(DRPdfLabel.JUSTIFIED.DER) && residuo > 0) {
                fillEmpty(residuo + adicional, sb);
            }
            sb.append(label);
            if (etiqueta.length() > 0 && etiqueta.justified().equals(DRPdfLabel.JUSTIFIED.IZQ) && residuo > 0) {
                fillEmpty(residuo + adicional, sb);
            }
            pantagram.add(new Chunk(sb.toString(), font));
        }
    }
    if (pantagram != null) {
        doc.add(pantagram);
    }

}