Example usage for com.itextpdf.text Section add

List of usage examples for com.itextpdf.text Section add

Introduction

In this page you can find the example usage for com.itextpdf.text Section add.

Prototype

@Override
public boolean add(final Element element) 

Source Link

Document

Adds a Paragraph, List, Table or another Section to this Section.

Usage

From source file:Controller.CrearPDF.java

/**
 * We create a PDF document with iText using different elements to learn 
 * to use this library./*ww  w  .ja  va2  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:CTD.planer2.util.ExportToPdf.java

/**
 * We create the table we want to add to our pdf
 * //w w w .  j a  v a 2s .c  om
 * @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
 * /*w w w.  j a v  a  2  s  . co 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 w w w .  java 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:de.extra.xtt.util.pdf.PdfCreatorImpl.java

License:Apache License

/**
 * Das Element wird mit Datentyp, seinen Attributen und Kindelementen
 * geschrieben.//from ww  w .j  a v  a2 s.  c o m
 * 
 * @param currElement
 *            Zu behandelndes Element
 * @param currChapter
 *            Kapitel, zu dem das Element hinzugefgt wird
 * @param chapterEntry
 *            Eintrag des Kapitels fr das Inhaltsverzeichnis
 * @param schemaQueues
 *            Queues mit allen Elementen fr die einzelnen Schemas
 */
private void behandleElement(XSElementDecl currElement, Chapter currChapter, ContPdfEntry chapterEntry,
        Map<String, Queue<XSElementDecl>> schemaQueues) throws DocumentException {
    // Fr jedes Element eine Section; Titel ist der Elementname

    // eine Zeile Abstand
    docPdf.add(getEmptyLineText());

    // Referenz des Elements
    String currReferenzString = getReferenceForElement(currElement);

    // Titel des Elements inkl. Sprungmarke
    Chunk chunkElem = getChunkElement(currElement.getName());
    chunkElem.setLocalDestination(currReferenzString);

    Paragraph currElemPara = new Paragraph(getChunkElement(""));
    currElemPara.add(chunkElem);
    Section currSection = currChapter.addSection(currElemPara);

    // Eintrag fr Inhaltsverzeichnis (Element)
    listEntries.add(new ContPdfEntry(chapterEntry, currSection.getTitle().getContent(), currReferenzString,
            currPageNumber));

    // Sektion dem Dokument (vorlufig) hinzufgen (wichtig fr das
    // Aktualisieren der Seitenzahl)
    currSection.setComplete(false);
    docPdf.add(currSection);

    // Anmerkung zum Element
    XSAnnotation ann = currElement.getAnnotation();
    if (ann != null) {
        // Abstand
        currSection.add(getEmptyLineTextHalf());

        String beschreibung = ann.getAnnotation().toString();
        currSection.add(getParagraphTextItalic(beschreibung));
    }

    // Abstand
    currSection.add(getEmptyLineTextHalf());

    // Datentyp
    Paragraph paraTyp = new Paragraph();
    XSType currType = currElement.getType();
    paraTyp.add(getPhraseTextBold("Datentyp: "));
    String strTyp = getNameWithPrefix(currType);
    if (currType.isLocal()) {
        strTyp = "<lokal definiert>";
    }
    paraTyp.add(getPhraseText(strTyp + "\n"));

    // Basistyp
    if ((currType.getDerivationMethod() == XSType.RESTRICTION)
            || (currType.getDerivationMethod() == XSType.EXTENSION)) {
        paraTyp.add(getPhraseTextBold("basiert auf: "));
        paraTyp.add(getPhraseText(getNameWithPrefix(currType.getBaseType()) + "\n"));
    }
    currSection.add(paraTyp);

    // Attribute (falls vorhanden)
    behandleAttribute(currType, currSection);

    // Kind-Elemente (falls vorhanden)
    if (currType.isComplexType()) {
        // Gruppentyp (sequence oder choice)
        String strCompositor = getCompositorStr(currType.asComplexType());
        if (strCompositor.length() > 0) {
            // Abstand
            currSection.add(getEmptyLineTextHalf());

            currSection.add(getParagraphTextBold(strCompositor + "-Elemente:"));
            behandleKindElemente(currElement, currSection, schemaQueues);
        }
    }

    // Sektion dem Dokument (endgltig) hinzufgen
    currSection.setComplete(true);
    docPdf.add(currSection);
}

From source file:de.extra.xtt.util.pdf.PdfCreatorImpl.java

License:Apache License

/**
 * Die Kindelemente (Sequence oder Choice) des bergebenen Elements werden
 * behandelt//from   w  w  w  .j  ava  2s.com
 * 
 * @param currElementMain
 *            Element, dessen Kindelemente gesucht und behandelt werden
 * @param currSection
 *            Sektion des PDF-Dokuments
 * @param schemaQueues
 *            Queues mit allen Elementen fr die einzelnen Schemas
 */
private void behandleKindElemente(XSElementDecl currElementMain, Section currSection,
        Map<String, Queue<XSElementDecl>> schemaQueues) {

    // Kind-Elemente bestimmen
    XSParticle[] childs = null;
    XSType currType = currElementMain.getType();
    if (currType.isComplexType()) {
        XSParticle currParticle = null;
        if (currType.asComplexType().getExplicitContent() != null) {
            currParticle = currType.asComplexType().getExplicitContent().asParticle();
        } else if (currType.asComplexType().getContentType() != null) {
            currParticle = currType.asComplexType().getContentType().asParticle();
        }
        if (currParticle != null) {
            XSModelGroup modelGroup = currParticle.getTerm().asModelGroup();
            childs = modelGroup.getChildren();
        }
    }

    if ((childs != null) && (childs.length > 0)) {
        // Fr jedes Kind wird ein Listeneintrag erstellt
        List currList = erzeugeListeFuerKindElemente(childs, schemaQueues, bulletMain);
        currSection.add(currList);
    }
}

From source file:de.extra.xtt.util.pdf.PdfCreatorImpl.java

License:Apache License

/**
 * Fr die Attribute des aktuellen Typs wird eine Liste erzeugt und der
 * angegebenen Sektion hinzugefgt.//from  w  ww.j a  v  a2s.c  o m
 * 
 * @param currType
 *            Schemtyp, fr den die Attribute bestimmt werden
 * @param currSection
 *            Aktuelle Sektion des PDF-Dokuments
 */
private void behandleAttribute(XSType currType, Section currSection) {
    if (currType.isComplexType()) {
        @SuppressWarnings("unchecked")
        Iterator<XSAttGroupDecl> itr1 = (Iterator<XSAttGroupDecl>) currType.asComplexType().iterateAttGroups();
        @SuppressWarnings("unchecked")
        Iterator<XSAttributeUse> itr2 = (Iterator<XSAttributeUse>) currType.asComplexType()
                .iterateAttributeUses();

        if (itr1.hasNext() || itr2.hasNext()) {
            // Abstand
            currSection.add(getEmptyLineTextHalf());

            currSection.add(getParagraphTextBold("Attribute:"));

            List currList = new List(false, 12);
            currList.setListSymbol(bulletMain);

            while (itr1.hasNext()) {
                XSAttGroupDecl currAttr = itr1.next();
                String strAttribute = currAttr.getName();
                currList.add(new ListItem(getPhraseText(strAttribute)));
            }

            while (itr2.hasNext()) {
                XSAttributeDecl currAttr = itr2.next().getDecl();
                String strAttribute = currAttr.getName();
                // Typ kann lokal sein
                if (!currAttr.getType().isLocal()) {
                    strAttribute += " (" + getNameWithPrefix(currAttr.getType()) + ")";
                }
                currList.add(new ListItem(getPhraseText(strAttribute)));
            }
            currSection.add(currList);
        }
    }
}

From source file:drugsupplychain.neu.css.gui.common.distributor.GenerateBillPDF.java

/**
 * add content to the page/*from w ww  .j  a v a 2 s . c o  m*/
 * @param document
 * @throws DocumentException 
 */
private static void addContent(Document document, Order order, Distributor distributor, Address billingAddress)
        throws DocumentException {
    Paragraph paragraph = new Paragraph();
    Anchor anchor = new Anchor("DISTRIBUTOR INVOICE", catFont);
    anchor.setName("DISTRIBUTOR INVOICE");
    // Second parameter is the number of the chapter
    Chapter catPart = new Chapter(new Paragraph(anchor), 1);
    Paragraph subPara = new Paragraph("CUSTOMER DETAILS", subFont);
    Section subCatPart = catPart.addSection(subPara);
    subCatPart.add(new Paragraph("ID: " + distributor.getOrganizationID()));
    subCatPart.add(new Paragraph("NAME: " + distributor.getName()));
    subCatPart.add(new Paragraph("LOCATION: " + distributor.getLocation()));
    subCatPart.add(new Paragraph("LICENSE NUMBER: " + distributor.getLincense().getLicenseNumber()));
    //add empty lines
    addEmptyLine(paragraph, 1);
    subCatPart.add(paragraph);
    subPara = new Paragraph("BILLING ADDRESS DETAILS", subFont);
    subCatPart = catPart.addSection(subPara);
    subCatPart.add(new Paragraph("ADDRESS LINE 1: " + billingAddress.getAddressLine1()));
    subCatPart.add(new Paragraph("ADDRESS LINE 2: " + billingAddress.getAddressLine2()));
    subCatPart.add(new Paragraph("CITY: " + billingAddress.getCity()));
    subCatPart.add(new Paragraph("STATE: " + billingAddress.getState()));
    subCatPart.add(new Paragraph("COUNTRY: " + billingAddress.getCountry()));
    subCatPart.add(new Paragraph("ZIP CODE: " + billingAddress.getZipcode()));
    //add empty lines
    addEmptyLine(paragraph, 1);
    subCatPart.add(paragraph);
    subPara = new Paragraph("ORDER SUMMARY TABLE", subFont);
    subCatPart = catPart.addSection(subPara);
    //add empty lines
    addEmptyLine(paragraph, 1);
    subCatPart.add(paragraph);
    // add a table
    int totalPrice = createTable(subCatPart, order);
    subCatPart.add(new Paragraph("Total Price: " + totalPrice));
    subCatPart.add(new Paragraph(
            "ORDER DATE(MM/DD/YYYY): " + ImplCommonUtil.getFormattedDate(order.getCreationDate())));
    subCatPart.add(new Paragraph("BILL GENERATED BY: " + System.getProperty("user.name")));
    // now add all this to the document
    document.add(catPart);
}

From source file:drugsupplychain.neu.css.gui.common.distributor.GenerateBillPDF.java

/**
 * create table/*  w ww.ja v a 2 s  . com*/
 * @param subCatPart
 * @throws BadElementException 
 */
private static int createTable(Section subCatPart, Order order) throws BadElementException {
    PdfPTable table = new PdfPTable(3);
    PdfPCell c1 = new PdfPCell(new Phrase("Order Item ID"));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);
    c1 = new PdfPCell(new Phrase("Quantity"));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);
    c1 = new PdfPCell(new Phrase("Value"));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);
    table.setHeaderRows(1);
    int totalPrice = 0;
    for (OrderItem orderItem : order.getOrderItemList()) {
        table.addCell(orderItem.getProduct().getBarcode());
        table.addCell(String.valueOf(orderItem.getQuantity()));
        table.addCell(String.valueOf(orderItem.getQuantity() * orderItem.getProduct().getPrice()));
        totalPrice = totalPrice + (orderItem.getQuantity() * orderItem.getProduct().getPrice());
    }
    subCatPart.add(table);
    return totalPrice;
}

From source file:edu.avans.ivh5.shared.util.generateInvoicePDF.java

private static void createTable(Section preface) throws BadElementException {

    PdfPTable table = new PdfPTable(2);

    table.getDefaultCell().setBorder(PdfPCell.NO_BORDER);

    table.addCell("Naam klant");
    table.addCell("Naam bedrijf");
    table.addCell("Adres Klant");
    table.addCell("Adres Bedrijf");
    table.addCell("Postcode + Plaats klant ");
    table.addCell("Postcode + Plaats klant");
    table.addCell("");
    table.addCell("telefoonnummer bedrijf");
    table.addCell("");
    table.addCell("Bankgegevens bedrijf");
    table.addCell("");
    table.addCell("BTW-nummer bedrijf");
    table.addCell(" ");
    table.addCell(" ");
    table.addCell(" ");
    table.addCell(" ");

    preface.add(table);

}