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

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

Introduction

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

Prototype

public void setWidths(int relativeWidths[]) throws DocumentException 

Source Link

Document

Sets the relative widths of the table.

Usage

From source file:corner.orm.tapestry.pdf.components.AbstractPdfTableDisplay.java

License:Apache License

protected PdfPTable createPdfTable(PdfWriter pdfWriter, List source, int start, int rows) {
    int columnCount = getDisplayTableModel().getColumnCount();

    PdfPTable table = new PdfPTable(columnCount);
    table.setTotalWidth(this.getCurrentColumnTextWidth());
    beginTableHeader(table);// TableHeader
    try {// ww  w  .  j av a2s .c  o m
        table.setWidths(this.getDisplayTableModel().getColumPercentWidths());
    } catch (DocumentException e) {
        throw new PdfSystemException(e);
    }

    for (int i = start; i < start + rows && i < source.size(); i++) {
        createTableRow(pdfWriter, table, source.get(i), columnCount, getDisplayTableModel());
    }
    return table;
}

From source file:CPS.Core.TODOLists.PDFExporter.java

License:Open Source License

/**
 * @param args the command line arguments
 *///from  ww w . j  a va2s  . c  om
public PdfPTable convertJTable(JTable jtable) {

    boolean tableIncludesNotes = false;
    boolean rowHasNotes = false;
    String notesValue = "";
    int notesIndex = -1;

    // find Notes column (if there is one)
    for (int col = 0; col < jtable.getColumnCount(); col++) {
        String headName;
        if (jtable instanceof CPSTable)
            headName = jtable.getColumnModel().getColumn(col).getHeaderValue().toString();
        else
            headName = jtable.getColumnName(col);
        if (headName.equalsIgnoreCase("Planting Notes")) {
            tableIncludesNotes = true;
            notesIndex = col;
        }
    }

    int colCount = (tableIncludesNotes) ? jtable.getColumnCount() - 1 : jtable.getColumnCount();
    PdfPTable table = new PdfPTable(colCount);

    // create header row
    for (int col = 0; col < jtable.getColumnCount(); col++) {
        String headName;
        if (jtable instanceof CPSTable)
            headName = jtable.getColumnModel().getColumn(col).getHeaderValue().toString();
        else
            headName = jtable.getColumnName(col);
        if (!tableIncludesNotes || col != notesIndex) {
            HeadCell hc = new HeadCell(headName);

            if (jtable.getColumnClass(col).equals(Boolean.TRUE.getClass())
                    || jtable.getColumnClass(col).equals(new Integer(0).getClass())
                    || jtable.getColumnClass(col).equals(new Double(0).getClass())
                    || jtable.getColumnClass(col).equals(new Float(0).getClass())) {
                hc.setRotation(90);
                hc.setFixedHeight(60f);
            }

            table.addCell(hc);
        }
    }
    table.setHeaderRows(1);

    // now fill in the rest of the table
    for (int row = 0; row < jtable.getRowCount(); row++) {
        rowHasNotes = false;

        for (int col = 0; col < jtable.getColumnCount(); col++) {
            Object o = jtable.getValueAt(row, col);

            if (o == null) {
                if (!tableIncludesNotes || col != notesIndex)
                    table.addCell(new RegCell(""));
            }

            else if (o instanceof Date)
                table.addCell(new RegCell(
                        CPSDateValidator.format((Date) o, CPSDateValidator.DATE_FORMAT_SHORT_DAY_OF_WEEK)));

            else if (o instanceof Boolean)
                if (((Boolean) o).booleanValue())
                    table.addCell(new CenterCell("X"));
                else
                    table.addCell(new RegCell(""));

            else if (o instanceof Float)
                table.addCell(new RegCell(CPSRecord.formatFloat(((Float) o).floatValue(), 3)));

            else if (o instanceof Double)
                table.addCell(new RegCell(CPSRecord.formatFloat(((Double) o).floatValue(), 3)));

            else {

                if (tableIncludesNotes && col == notesIndex) {
                    if (o == null || o.equals(""))
                        rowHasNotes = false;
                    else {
                        rowHasNotes = true;
                        notesValue = o.toString();
                    }
                } else
                    table.addCell(new RegCell(o.toString()));
            }
        }

        // now deal w/ the Notes data
        if (tableIncludesNotes && rowHasNotes) {
            table.addCell(new NoteHeadCell());
            NoteCell c = new NoteCell(notesValue);
            // reset the font to be smaller
            c.setPhrase(new Phrase(notesValue, fontHeadFootReg));
            c.setColspan(colCount - 1);
            table.addCell(c);
        }
    }

    // set the widths for the columns
    float[] widths = new float[colCount];
    for (int col = 0; col < colCount; col++) {
        if (tableIncludesNotes && col == notesIndex)
            continue;
        else if (jtable.getColumnClass(col).equals(new Boolean(true).getClass()))
            widths[col] = 2.25f;
        else if (jtable.getColumnClass(col).equals(new Integer(0).getClass())
                || jtable.getColumnClass(col).equals(new Double(0).getClass())
                || jtable.getColumnClass(col).equals(new Float(0).getClass()))
            widths[col] = 5f;
        else // String, Date, etc
            widths[col] = 10f;
    }

    try {
        table.setWidths(widths);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return table;
}

From source file:de.dhbw.humbuch.util.PDFHandler.java

/**
 * Adds a signature field with a date field to the document. Should be the
 * last part that is added to the document.
 * //  www.  j  a  v a  2 s  .c om
 * @param document
 *            represents the PDF before it is saved
 * @param role
 *            word for the kind of person that shall sign the paper
 */
protected void addSignatureField(Document document, String role) {
    Paragraph paragraph = new Paragraph();

    //this table contains the signatureTable and the dataTable.
    // this purpose makes it easier to format
    PdfPTable table = createMyStandardTable(2);

    //the first column is double times greater than the second column
    try {
        table.setWidths(new float[] { 10f, 20f });
    } catch (DocumentException e) {
        e.printStackTrace();
    }

    //create and fill date table
    PdfPTable dateTable = new PdfPTable(1);

    PdfPCell cell = new PdfPCell(new Phrase(""));
    //just the bottom border will be displayed (line for date)
    cell.setBorderWidthTop(0);
    cell.setBorderWidthLeft(0);
    cell.setBorderWidthRight(0);

    dateTable.addCell(cell);

    cell = new PdfPCell(new Phrase("Datum"));
    cell.setBorder(0);

    dateTable.addCell(cell);

    //put date table into the 'parent' table
    cell = new PdfPCell(dateTable);
    cell.setBorder(0);
    table.addCell(cell);

    //create and fill signature table
    PdfPTable signatureTable = new PdfPTable(1);
    cell = new PdfPCell(new Phrase(""));
    //just the bottom border will be displayed (line for signature)
    cell.setBorderWidthTop(0);
    cell.setBorderWidthLeft(0);
    cell.setBorderWidthRight(0);

    signatureTable.addCell(cell);

    cell = new PdfPCell(new Phrase("Unterschrift " + role));
    cell.setBorder(0);

    signatureTable.addCell(cell);

    //put signature table into the 'parent' table
    cell = new PdfPCell(signatureTable);
    cell.setBorder(0);
    table.addCell(cell);

    paragraph.add(table);
    try {
        document.add(paragraph);
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}

From source file:de.dhbw.humbuch.util.PDFHandler.java

/**
 * Create a standard table with constant table width.
 * //from   w w  w .  ja va 2 s  .co  m
 * @param columnNumber
 *            set how many columns the table will have
 * @param columnWidths
 *            set the ratio between the columns. If null, all columns will
 *            be equal.
 * @return table
 */
protected static PdfPTable createMyStandardTable(int columnNumber, float[] columnWidths) {
    PdfPTable table = new PdfPTable(columnNumber);
    table.setLockedWidth(true);
    table.setTotalWidth(TABLEWIDTH);

    if (!(columnWidths == null) && (columnWidths.length != 0)) {
        try {
            table.setWidths(columnWidths);
        } catch (DocumentException e) {
            System.err.println("Could not set columnWidths of standardTable " + e.getStackTrace());
        }
    }

    return table;
}

From source file:de.jdufner.sudoku.generator.pdf.PdfPrinterImpl.java

License:Open Source License

private void writeFrontpage(String name, Document document, List<PdfSolution> solutions)
        throws DocumentException {
    document.open();/*from   w  w  w .  ja  v  a  2 s  .  c o m*/
    Paragraph p = new Paragraph(name);
    p.setAlignment(Element.ALIGN_CENTER);
    p.setSpacingBefore(20f);
    p.setSpacingAfter(20f);
    document.add(p);
    PdfPTable table = new PdfPTable(17);
    table.setWidthPercentage(100);
    int[] width = { 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
    table.setWidths(width);
    PdfPCell cell;
    table.addCell(buildHeaderCell("Name", 90, true, false));
    table.addCell(buildHeaderCell("Schwierigkeitsgrad", 90, false, false));
    table.addCell(buildHeaderCell("Besetzte Zellen", 90, false, false));
    table.addCell(buildHeaderCell("Simple", 90, false, false));
    table.addCell(buildHeaderCell("Hidden Single", 90, false, false));
    table.addCell(buildHeaderCell("Naked Pair", 90, false, false));
    table.addCell(buildHeaderCell("Naked Triple", 90, false, false));
    table.addCell(buildHeaderCell("Naked Quad", 90, false, false));
    table.addCell(buildHeaderCell("Hidden Pair", 90, false, false));
    table.addCell(buildHeaderCell("Hidden Triple", 90, false, false));
    table.addCell(buildHeaderCell("Hidden Quad", 90, false, false));
    table.addCell(buildHeaderCell("Intersection Removal", 90, false, false));
    table.addCell(buildHeaderCell("Y-Wing", 90, false, false));
    table.addCell(buildHeaderCell("X-Wing", 90, false, false));
    table.addCell(buildHeaderCell("Jellyfish", 90, false, false));
    table.addCell(buildHeaderCell("Swordfish", 90, false, false));
    table.addCell(buildHeaderCell("Backtracking", 90, false, true));
    boolean even = false;
    for (PdfSolution solution : solutions) {
        table.addCell(buildBodyNumberCell(solution.getId(), even, true, false));
        table.addCell(buildBodyTextCell(solution.getLevel().toString(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getFixed(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategySimple(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategyHiddenSingle(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategyNakedPair(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategyNakedTriple(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategyNakedQuad(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategyHiddenPair(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategyHiddenTriple(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategyHiddenQuad(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategyIntersectionRemoval(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategyYwing(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategyXwing(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategyJellyfish(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategySwordfish(), even, false, false));
        table.addCell(buildBodyNumberCell(solution.getStrategyBacktracking(), even, false, true));
        even = (even ? false : true);
    }
    document.add(table);
    document.close();
}

From source file:domain.reports.menu.PDFReportMenu.java

License:LGPL

/**
 * Return a report section formatted as a table
 * @param data/* w w w  . j  a v  a  2  s .  c  om*/
 * @return
 */
PdfPTable getGroupDetail(Recordset master, Recordset detail) throws Throwable {

    //cols
    PdfPTable datatable = new PdfPTable(2);

    //header
    datatable.getDefaultCell().setPadding(1);
    int headerwidths[] = { 50, 50 }; // percentage
    datatable.setWidths(headerwidths);
    datatable.setWidthPercentage(70); // percentage
    datatable.setHorizontalAlignment(Element.ALIGN_CENTER);
    datatable.getDefaultCell().setBorderWidth(1);
    datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);

    PdfPCell c = null;
    String v = "";

    //encabezados de columnas
    c = new PdfPCell(new Phrase("ITEMS DEL MEN", tblHeaderFont));
    c.setGrayFill(0.95f);
    c.setColspan(2);
    c.setHorizontalAlignment(Element.ALIGN_CENTER);
    datatable.addCell(c);

    c = new PdfPCell(new Phrase("Item del men", tblHeaderFont));
    c.setGrayFill(0.95f);
    c.setHorizontalAlignment(Element.ALIGN_CENTER);
    datatable.addCell(c);

    c = new PdfPCell(new Phrase("Servicio", tblHeaderFont));
    c.setGrayFill(0.95f);
    c.setHorizontalAlignment(Element.ALIGN_CENTER);
    datatable.addCell(c);

    while (detail.next()) {
        v = detail.getString("description");
        c = new PdfPCell(new Phrase(v, tblBodyFont));
        c.setHorizontalAlignment(Element.ALIGN_LEFT);
        datatable.addCell(c);

        v = detail.getString("path");
        c = new PdfPCell(new Phrase(v, tblBodyFont));
        c.setHorizontalAlignment(Element.ALIGN_LEFT);
        datatable.addCell(c);
    }

    datatable.setSpacingBefore(20);
    return datatable;

}

From source file:domain.reports.role.PDFReportRole.java

License:LGPL

/**
 * Return a report section formatted as a table
 * @param data/* ww w.  jav a2  s  .c o m*/
 * @return
 */
PdfPTable getGroupDetail(Recordset master, Recordset detail) throws Throwable {

    //cols
    PdfPTable datatable = new PdfPTable(4);

    //header
    datatable.getDefaultCell().setPadding(1);
    int headerwidths[] = { 20, 20, 20, 20 }; // percentage
    datatable.setWidths(headerwidths);
    datatable.setWidthPercentage(100); // percentage
    datatable.setHorizontalAlignment(Element.ALIGN_CENTER);
    datatable.getDefaultCell().setBorderWidth(1);
    datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);

    PdfPCell c = null;
    String v = "";

    //encabezados de columnas
    c = new PdfPCell(new Phrase("USUARIOS DEL ROL", tblHeaderFont));
    c.setGrayFill(0.95f);
    c.setColspan(4);
    c.setHorizontalAlignment(Element.ALIGN_CENTER);
    datatable.addCell(c);

    c = new PdfPCell(new Phrase("Login de Usuario", tblHeaderFont));
    c.setGrayFill(0.95f);
    c.setHorizontalAlignment(Element.ALIGN_CENTER);
    datatable.addCell(c);

    c = new PdfPCell(new Phrase("Apellido", tblHeaderFont));
    c.setGrayFill(0.95f);
    c.setHorizontalAlignment(Element.ALIGN_CENTER);
    datatable.addCell(c);

    c = new PdfPCell(new Phrase("Nombre", tblHeaderFont));
    c.setGrayFill(0.95f);
    c.setHorizontalAlignment(Element.ALIGN_CENTER);
    datatable.addCell(c);

    c = new PdfPCell(new Phrase("Email", tblHeaderFont));
    c.setGrayFill(0.95f);
    c.setHorizontalAlignment(Element.ALIGN_CENTER);
    datatable.addCell(c);

    while (detail.next()) {
        v = detail.getString("userlogin");
        c = new PdfPCell(new Phrase(v, tblBodyFont));
        c.setHorizontalAlignment(Element.ALIGN_CENTER);
        datatable.addCell(c);

        v = detail.getString("lname");
        c = new PdfPCell(new Phrase(v, tblBodyFont));
        c.setHorizontalAlignment(Element.ALIGN_CENTER);
        datatable.addCell(c);

        v = detail.getString("fname");
        c = new PdfPCell(new Phrase(v, tblBodyFont));
        c.setHorizontalAlignment(Element.ALIGN_CENTER);
        datatable.addCell(c);

        v = detail.getString("email");
        c = new PdfPCell(new Phrase(v, tblBodyFont));
        c.setHorizontalAlignment(Element.ALIGN_CENTER);
        datatable.addCell(c);
    }

    datatable.setSpacingBefore(20);
    return datatable;

}

From source file:edu.harvard.mcz.imagecapture.encoder.LabelEncoder.java

License:Open Source License

@SuppressWarnings("hiding")
public static boolean printList(List<UnitTrayLabel> taxa) throws PrintFailedException {
    boolean result = false;
    UnitTrayLabel label = new UnitTrayLabel();
    LabelEncoder encoder = new LabelEncoder(label);
    Image image = encoder.getImage();
    int counter = 0;
    try {//w w w  .  ja  v  a2  s . c om
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream("labels.pdf"));
        document.setPageSize(PageSize.LETTER);
        document.open();

        PdfPTable table = new PdfPTable(4);
        table.setWidthPercentage(100f);
        //table.setHorizontalAlignment(PdfPTable.ALIGN_LEFT);
        float[] cellWidths = { 30f, 20f, 30f, 20f };
        table.setWidths(cellWidths);

        UnitTrayLabelLifeCycle uls = new UnitTrayLabelLifeCycle();
        if (taxa == null) {
            taxa = uls.findAll();
        }
        Iterator<UnitTrayLabel> i = taxa.iterator();
        PdfPCell cell = null;
        PdfPCell cell_barcode = null;
        // Create two lists of 12 cells, the first 6 of each representing
        // the left hand column of 6 labels, the second 6 of each 
        // representing the right hand column.  
        // cells holds the text for each label, cells_barcode the barcode.
        ArrayList<PdfPCell> cells = new ArrayList<PdfPCell>(12);
        ArrayList<PdfPCell> cells_barcode = new ArrayList<PdfPCell>(12);
        for (int x = 0; x < 12; x++) {
            cells.add(null);
            cells_barcode.add(null);
        }
        int cellCounter = 0;
        while (i.hasNext()) {
            // Loop through all of the taxa (unit tray labels) found to print 
            label = i.next();
            for (int toPrint = 0; toPrint < label.getNumberToPrint(); toPrint++) {
                // For each taxon, loop through the number of requested copies 
                // Generate a text and a barcode cell for each, and add to array for page
                log.debug("Label " + toPrint + " of " + label.getNumberToPrint());
                cell = new PdfPCell();
                cell.setBorderColor(Color.LIGHT_GRAY);
                cell.setVerticalAlignment(PdfPCell.ALIGN_TOP);
                cell.disableBorderSide(PdfPCell.RIGHT);
                cell.setPaddingLeft(3);

                String higherNames = "";
                if (label.getTribe().trim().length() > 0) {
                    higherNames = label.getFamily() + ": " + label.getSubfamily() + ": " + label.getTribe();
                } else {
                    higherNames = label.getFamily() + ": " + label.getSubfamily();
                }
                Paragraph higher = new Paragraph();
                higher.setFont(new Font(Font.TIMES_ROMAN, 11, Font.NORMAL));
                higher.add(new Chunk(higherNames));
                cell.addElement(higher);

                Paragraph name = new Paragraph();
                Chunk genus = new Chunk(label.getGenus().trim() + " ");
                genus.setFont(new Font(Font.TIMES_ROMAN, 11, Font.ITALIC));
                Chunk species = new Chunk(label.getSpecificEpithet().trim());
                Chunk normal = null; // normal font prefix to preceed specific epithet (nr. <i>epithet</i>)
                if (label.getSpecificEpithet().contains(".") || label.getSpecificEpithet().contains("[")) {
                    if (label.getSpecificEpithet().startsWith("nr. ")) {
                        normal = new Chunk("nr. ");
                        normal.setFont(new Font(Font.TIMES_ROMAN, 11, Font.NORMAL));
                        species = new Chunk(label.getSpecificEpithet().trim().substring(4));
                        species.setFont(new Font(Font.TIMES_ROMAN, 11, Font.ITALIC));
                    } else {
                        species.setFont(new Font(Font.TIMES_ROMAN, 11, Font.NORMAL));
                    }
                } else {
                    species.setFont(new Font(Font.TIMES_ROMAN, 11, Font.ITALIC));
                }
                String s = "";
                if (label.getSubspecificEpithet().trim().length() > 0) {
                    s = " ";
                } else {
                    s = "";
                }
                Chunk subspecies = new Chunk(s + label.getSubspecificEpithet().trim());
                if (label.getSubspecificEpithet().contains(".")
                        || label.getSubspecificEpithet().contains("[")) {
                    subspecies.setFont(new Font(Font.TIMES_ROMAN, 11, Font.NORMAL));
                } else {
                    subspecies.setFont(new Font(Font.TIMES_ROMAN, 11, Font.ITALIC));
                }
                if (label.getInfraspecificRank().trim().length() > 0) {
                    s = " ";
                } else {
                    s = "";
                }
                Chunk infraRank = new Chunk(s + label.getInfraspecificRank().trim());
                infraRank.setFont(new Font(Font.TIMES_ROMAN, 11, Font.NORMAL));

                if (label.getInfraspecificEpithet().trim().length() > 0) {
                    s = " ";
                } else {
                    s = "";
                }
                Chunk infra = new Chunk(s + label.getInfraspecificEpithet().trim());
                infra.setFont(new Font(Font.TIMES_ROMAN, 11, Font.ITALIC));
                if (label.getUnNamedForm().trim().length() > 0) {
                    s = " ";
                } else {
                    s = "";
                }
                Chunk unNamed = new Chunk(s + label.getUnNamedForm().trim());
                unNamed.setFont(new Font(Font.TIMES_ROMAN, 11, Font.NORMAL));

                name.add(genus);
                if (normal != null) {
                    name.add(normal);
                }
                name.add(species);
                name.add(subspecies);
                name.add(infraRank);
                name.add(infra);
                name.add(unNamed);
                cell.addElement(name);

                Paragraph authorship = new Paragraph();
                authorship.setFont(new Font(Font.TIMES_ROMAN, 10, Font.NORMAL));
                if (label.getAuthorship() != null && label.getAuthorship().length() > 0) {
                    Chunk c_authorship = new Chunk(label.getAuthorship());
                    authorship.add(c_authorship);
                }
                cell.addElement(authorship);
                //cell.addElement(new Paragraph(" "));
                if (label.getDrawerNumber() != null && label.getDrawerNumber().length() > 0) {
                    Paragraph drawerNumber = new Paragraph();
                    drawerNumber.setFont(new Font(Font.TIMES_ROMAN, 10, Font.NORMAL));
                    Chunk c_drawerNumber = new Chunk(label.getDrawerNumber());
                    drawerNumber.add(c_drawerNumber);
                    cell.addElement(drawerNumber);
                } else {
                    if (label.getCollection() != null && label.getCollection().length() > 0) {
                        Paragraph collection = new Paragraph();
                        collection.setFont(new Font(Font.TIMES_ROMAN, 10, Font.NORMAL));
                        Chunk c_collection = new Chunk(label.getCollection());
                        collection.add(c_collection);
                        cell.addElement(collection);
                    }
                }

                cell_barcode = new PdfPCell();
                cell_barcode.setBorderColor(Color.LIGHT_GRAY);
                cell_barcode.disableBorderSide(PdfPCell.LEFT);
                cell_barcode.setVerticalAlignment(PdfPCell.ALIGN_TOP);

                encoder = new LabelEncoder(label);
                image = encoder.getImage();
                image.setAlignment(Image.ALIGN_TOP);
                cell_barcode.addElement(image);

                cells.add(cellCounter, cell);
                cells_barcode.add(cellCounter, cell_barcode);

                cellCounter++;
                // If we have hit a full set of 12 labels, add them to the document
                // in two columns, filling left column first, then right
                if (cellCounter == 12) {
                    // add a page of 12 cells in columns of two.
                    for (int x = 0; x < 6; x++) {
                        if (cells.get(x) == null) {
                            PdfPCell c = new PdfPCell();
                            c.setBorder(0);
                            table.addCell(c);
                            table.addCell(c);
                        } else {
                            table.addCell(cells.get(x));
                            table.addCell(cells_barcode.get(x));
                        }
                        if (cells.get(x + 6) == null) {
                            PdfPCell c = new PdfPCell();
                            c.setBorder(0);
                            table.addCell(c);
                            table.addCell(c);
                        } else {
                            table.addCell(cells.get(x + 6));
                            table.addCell(cells_barcode.get(x + 6));
                        }
                    }
                    // Reset to begin next page
                    cellCounter = 0;
                    document.add(table);
                    table = new PdfPTable(4);
                    table.setWidthPercentage(100f);
                    table.setWidths(cellWidths);
                    for (int x = 0; x < 12; x++) {
                        cells.set(x, null);
                        cells_barcode.set(x, null);
                    }
                }
            } // end loop through toPrint (for a taxon)
            counter++;
        } // end while results has next (for all taxa requested)
          // get any remaining cells in pairs
        for (int x = 0; x < 6; x++) {
            if (cells.get(x) == null) {
                PdfPCell c = new PdfPCell();
                c.setBorder(0);
                table.addCell(c);
                table.addCell(c);
            } else {
                table.addCell(cells.get(x));
                table.addCell(cells_barcode.get(x));
            }
            if (cells.get(x + 6) == null) {
                PdfPCell c = new PdfPCell();
                c.setBorder(0);
                table.addCell(c);
                table.addCell(c);
            } else {
                table.addCell(cells.get(x + 6));
                table.addCell(cells_barcode.get(x + 6));
            }
        }
        // add any remaining cells
        document.add(table);
        try {
            document.close();
        } catch (Exception e) {
            throw new PrintFailedException("No labels to print." + e.getMessage());
        }
        // Check to see if there was content in the document.
        if (counter == 0) {
            result = false;
        } else {
            // Printed to pdf ok.
            result = true;
            // Increment number printed.
            i = taxa.iterator();
            while (i.hasNext()) {
                label = i.next();
                for (int toPrint = 0; toPrint < label.getNumberToPrint(); toPrint++) {
                    label.setPrinted(label.getPrinted() + 1);
                }
                label.setNumberToPrint(0);
                try {
                    uls.attachDirty(label);
                } catch (SaveFailedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        throw new PrintFailedException("File not found.");
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        throw new PrintFailedException("Error buiding PDF document.");
    } catch (OutOfMemoryError e) {
        System.out.println("Out of memory error. " + e.getMessage());
        System.out.println("Failed.  Too many labels.");
        throw new PrintFailedException("Ran out of memory, too many labels at once.");
    }
    return result;
}

From source file:fr.opensagres.xdocreport.itext.extension.TableWithAlignment.java

License:Open Source License

public static void main(String[] args) {
    Document document = new Document(PageSize.A4.rotate(), 10, 10, 10, 10);
    try {//from w  w  w . j a  va2 s  .  c  o m
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("TableWithAlignment.pdf"));

        document.open();

        PdfPTable table = new PdfPTable(2);
        table.getDefaultCell().setUseAscender(true);
        table.getDefaultCell().setUseDescender(true);

        table.setWidths(new float[] { 5, 10 });
        table.setWidthPercentage(10);

        PdfPCell cell1 = new PdfPCell();
        cell1.addElement(new Chunk("cell1"));
        table.addCell(cell1);

        PdfPCell cell2 = new PdfPCell();
        cell2.addElement(new Chunk("cell2"));
        table.addCell(cell2);

        table.setSpacingBefore(-100);

        document.add(table);
    } catch (Exception de) {
        de.printStackTrace();
    }
    document.close();
}

From source file:fr.univlorraine.mondossierweb.controllers.CalendrierController.java

License:Apache License

/**
 * //from   w w w  .ja  va2 s  . c  o  m
 * @param document pdf
 */
public void creerPdfCalendrier(final Document document, Etudiant etudiant) {

    //configuration des fonts
    Font normal = FontFactory.getFont(FontFactory.TIMES_ROMAN, 10, Font.NORMAL);
    Font normalbig = FontFactory.getFont(FontFactory.TIMES_ROMAN, 11, Font.BOLD);
    Font legerita = FontFactory.getFont(FontFactory.TIMES_ROMAN, 9, Font.ITALIC);
    Font headerbig = FontFactory.getFont(FontFactory.TIMES_ROMAN, 16, Font.BOLD);
    Font header = FontFactory.getFont(FontFactory.TIMES_ROMAN, 12, Font.BOLD);

    //pieds de pages:
    Date d = new Date();
    DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
    String date = dateFormat.format(d);
    //alignement des libells du pied de page:
    String partie1 = applicationContext.getMessage("pdf.calendrier.title", null, Locale.getDefault());
    String partie2 = applicationContext.getMessage("pdf.edition.date", null, Locale.getDefault()) + " : "
            + date;
    if (partie1.length() < ECARTEMENT_PIED_PAGE_PDF) {
        int diff = ECARTEMENT_PIED_PAGE_PDF - partie1.length();
        for (int i = 0; i < diff; i++) {
            partie1 = partie1 + " ";

        }
    }
    if (partie2.length() < ECARTEMENT_PIED_PAGE_PDF) {
        int diff = ECARTEMENT_PIED_PAGE_PDF - partie2.length();
        for (int i = 0; i < diff; i++) {
            partie2 = " " + partie2;
        }
    }

    //cration du pied de page:
    Phrase phra = new Phrase(
            partie1 + " -" + applicationContext.getMessage("pdf.page", null, Locale.getDefault()), legerita);
    Phrase phra2 = new Phrase("- " + partie2, legerita);
    HeaderFooter hf = new HeaderFooter(phra, phra2);
    hf.setAlignment(HeaderFooter.ALIGN_CENTER);
    document.setFooter(hf);

    //ouverte du document.
    document.open();
    try {
        //ajout image test
        if (configController.getLogoUniversitePdf() != null
                && !configController.getLogoUniversitePdf().equals("")) {
            Image image1 = Image.getInstance(configController.getLogoUniversitePdf());
            float scaleRatio = 40 / image1.getHeight();
            float newWidth = scaleRatio * image1.getWidth();
            image1.scaleAbsolute(newWidth, 40);
            image1.setAbsolutePosition(800 - newWidth, 528);
            document.add(image1);
        }

        //nouveau paragraphe
        Paragraph p = new Paragraph(
                applicationContext.getMessage("pdf.calendrier.title", null, Locale.getDefault()).toUpperCase()
                        + "\n\n",
                headerbig);
        p.setIndentationLeft(15);
        document.add(p);

        if (etudiant.getNom() != null) {
            Paragraph p0 = new Paragraph(etudiant.getNom(), normal);
            p0.setIndentationLeft(15);
            document.add(p0);
        }
        if (etudiant.getCod_etu() != null) {
            Paragraph p01 = new Paragraph(applicationContext.getMessage("pdf.folder", null, Locale.getDefault())
                    + " : " + etudiant.getCod_etu(), normal);
            p01.setIndentationLeft(15);
            document.add(p01);
        }
        if (etudiant.getCod_nne() != null) {
            Paragraph p02 = new Paragraph(applicationContext.getMessage("pdf.nne", null, Locale.getDefault())
                    + " : " + etudiant.getCod_nne(), normal);
            p02.setIndentationLeft(15);
            document.add(p02);
        }
        if (etudiant.getEmail() != null) {
            Paragraph p03 = new Paragraph(applicationContext.getMessage("pdf.mail", null, Locale.getDefault())
                    + " : " + etudiant.getEmail(), normal);
            p03.setIndentationLeft(15);
            document.add(p03);
        }

        Paragraph p03 = new Paragraph(
                applicationContext.getMessage("pdf.edition.date", null, Locale.getDefault()) + " : " + date,
                normal);
        p03.setIndentationLeft(15);
        document.add(p03);
        document.add(new Paragraph("\n"));

        //Partie Calendrier
        PdfPTable table = new PdfPTable(1);
        table.setWidthPercentage(98);
        PdfPCell cell = new PdfPCell(new Paragraph(applicationContext
                .getMessage("pdf.calendrier.subtitle", null, Locale.getDefault()).toUpperCase() + " ", header));
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setBackgroundColor(new Color(153, 153, 255));
        table.addCell(cell);

        PdfPTable table2;

        boolean affNumPlaceExamen = configController.isAffNumPlaceExamen();

        if (affNumPlaceExamen) {
            table2 = new PdfPTable(7);
            table2.setWidthPercentage(98);
            int[] tabWidth = { 15, 10, 10, 40, 30, 10, 60 };
            table2.setWidths(tabWidth);
        } else {
            table2 = new PdfPTable(6);
            table2.setWidthPercentage(98);
            int[] tabWidth = { 15, 10, 10, 45, 30, 65 };
            table2.setWidths(tabWidth);
        }

        Paragraph p1 = new Paragraph(applicationContext.getMessage("pdf.date", null, Locale.getDefault()),
                normalbig);
        Paragraph p2 = new Paragraph(applicationContext.getMessage("pdf.heure", null, Locale.getDefault()),
                normalbig);
        Paragraph p3 = new Paragraph(applicationContext.getMessage("pdf.duree", null, Locale.getDefault()),
                normalbig);
        Paragraph p4 = new Paragraph(applicationContext.getMessage("pdf.batiment", null, Locale.getDefault()),
                normalbig);
        Paragraph p5 = new Paragraph(applicationContext.getMessage("pdf.salle", null, Locale.getDefault()),
                normalbig);
        Paragraph p6 = new Paragraph(applicationContext.getMessage("pdf.place", null, Locale.getDefault()),
                normalbig);
        Paragraph p7 = new Paragraph(applicationContext.getMessage("pdf.examen", null, Locale.getDefault()),
                normalbig);

        PdfPCell ct1 = new PdfPCell(p1);
        PdfPCell ct2 = new PdfPCell(p2);
        PdfPCell ct3 = new PdfPCell(p3);
        PdfPCell ct4 = new PdfPCell(p4);
        PdfPCell ct5 = new PdfPCell(p5);
        PdfPCell ct6 = new PdfPCell(p6);
        PdfPCell ct7 = new PdfPCell(p7);

        ct1.setBorder(Rectangle.BOTTOM);
        ct1.setBorderColorBottom(Color.black);
        ct2.setBorder(Rectangle.BOTTOM);
        ct2.setBorderColorBottom(Color.black);
        ct3.setBorder(Rectangle.BOTTOM);
        ct2.setBorderColorBottom(Color.black);
        ct4.setBorder(Rectangle.BOTTOM);
        ct1.setBorderColorBottom(Color.black);
        ct5.setBorder(Rectangle.BOTTOM);
        ct2.setBorderColorBottom(Color.black);
        ct6.setBorder(Rectangle.BOTTOM);
        ct2.setBorderColorBottom(Color.black);
        ct7.setBorder(Rectangle.BOTTOM);
        ct2.setBorderColorBottom(Color.black);

        table2.addCell(ct1);
        table2.addCell(ct2);
        table2.addCell(ct3);
        table2.addCell(ct4);
        table2.addCell(ct5);
        if (affNumPlaceExamen)
            table2.addCell(ct6);
        table2.addCell(ct7);

        for (int i = 0; i < etudiant.getCalendrier().size(); i++) {
            Paragraph pa = new Paragraph(etudiant.getCalendrier().get(i).getDatedeb(), normal);
            PdfPCell celltext = new PdfPCell(pa);
            celltext.setBorder(Rectangle.NO_BORDER);

            Paragraph pa2 = new Paragraph(etudiant.getCalendrier().get(i).getHeure(), normal);
            PdfPCell celltext2 = new PdfPCell(pa2);
            celltext2.setBorder(Rectangle.NO_BORDER);

            Paragraph pa3 = new Paragraph(etudiant.getCalendrier().get(i).getDuree(), normal);
            PdfPCell celltext3 = new PdfPCell(pa3);
            celltext3.setBorder(Rectangle.NO_BORDER);

            Paragraph pa4 = new Paragraph(etudiant.getCalendrier().get(i).getBatiment(), normal);
            PdfPCell celltext4 = new PdfPCell(pa4);
            celltext4.setBorder(Rectangle.NO_BORDER);

            Paragraph pa5 = new Paragraph(etudiant.getCalendrier().get(i).getSalle(), normal);
            PdfPCell celltext5 = new PdfPCell(pa5);
            celltext5.setBorder(Rectangle.NO_BORDER);

            Paragraph pa6 = new Paragraph(etudiant.getCalendrier().get(i).getPlace(), normal);
            PdfPCell celltext6 = new PdfPCell(pa6);
            celltext6.setBorder(Rectangle.NO_BORDER);

            Paragraph pa7 = new Paragraph(etudiant.getCalendrier().get(i).getEpreuve(), normal);
            PdfPCell celltext7 = new PdfPCell(pa7);
            celltext7.setBorder(Rectangle.NO_BORDER);

            table2.addCell(celltext);
            table2.addCell(celltext2);
            table2.addCell(celltext3);
            table2.addCell(celltext4);
            table2.addCell(celltext5);
            if (affNumPlaceExamen)
                table2.addCell(celltext6);
            table2.addCell(celltext7);

            /*PdfPCell celltext4 = new PdfPCell(table3);
            celltext4.setBorder(Rectangle.NO_BORDER);
            table2.addCell(celltext4);*/

        }
        document.add(table);
        document.add(table2);
        document.add(new Paragraph("\n"));

    } catch (BadElementException e) {
        LOG.error("Erreur  la gnration du calendrier des examens : BadElementException ", e);
    } catch (MalformedURLException e) {
        LOG.error("Erreur  la gnration du calendrier des examens : MalformedURLException ", e);
    } catch (IOException e) {
        LOG.error("Erreur  la gnration du calendrier des examens : IOException ", e);
    } catch (DocumentException e) {
        LOG.error("Erreur  la gnration du calendrier des examens : DocumentException ", e);
    }
    // step 6: fermeture du document.
    document.close();

}