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

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

Introduction

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

Prototype

public PdfPCell() 

Source Link

Document

Constructs an empty PdfPCell.

Usage

From source file:biblivre3.circulation.CirculationBO.java

License:Open Source License

public MemoryFileDTO createFileUserCardsPDF(ArrayList<UserCardDTO> cards, int startOffset, Properties i18n) {
    Document document = new Document();
    MemoryFileDTO file = new MemoryFileDTO();
    file.setFileName("user_cards_" + new Date().getTime() + ".pdf");
    try {/*from  ww  w  .  jav a2 s. co m*/
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        document.setPageSize(PageSize.A4);
        document.setMargins(7.15f * ApplicationConstants.MM_UNIT, 7.15f * ApplicationConstants.MM_UNIT,
                9.09f * ApplicationConstants.MM_UNIT, 9.09f * ApplicationConstants.MM_UNIT);
        document.open();
        PdfPTable table = new PdfPTable(3);
        table.setWidthPercentage(100f);
        PdfPCell cell;
        int i = 0;
        for (i = 0; i < startOffset; i++) {
            cell = new PdfPCell();
            cell.setBorder(Rectangle.NO_BORDER);
            cell.setFixedHeight(46.47f * ApplicationConstants.MM_UNIT);
            table.addCell(cell);
        }
        for (UserCardDTO card : cards) {
            String userEnrollNumber = String.valueOf(card.getUserId());
            PdfContentByte cb = writer.getDirectContent();
            Barcode39 code39 = new Barcode39();
            code39.setExtended(true);
            while (userEnrollNumber.length() < 10) {
                userEnrollNumber = "0" + userEnrollNumber;
            }
            code39.setCode(userEnrollNumber);
            code39.setStartStopText(false);
            Image image39 = code39.createImageWithBarcode(cb, null, null);
            image39.scalePercent(110f);
            Paragraph para = new Paragraph();
            String name = card.getUserName();
            name = name.length() >= 30 ? name.substring(0, 30) : name;
            Phrase p1 = new Phrase(name + "\n");
            Phrase p2 = new Phrase(new Chunk(image39, 0, 0));
            Phrase p3 = new Phrase(
                    I18nUtils.getText(i18n, "LABEL_USER_SERIAL") + ": " + card.getUserId() + "\n");
            Phrase p4 = new Phrase(
                    I18nUtils.getText(i18n, "LABEL_USER_TYPE") + ": " + card.getUserType() + "\n\n");
            para.add(p1);
            para.add(p3);
            para.add(p4);
            para.add(p2);
            cell = new PdfPCell(para);
            i++;
            cell.setFixedHeight(46.47f * ApplicationConstants.MM_UNIT);
            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
            cell.setBorder(Rectangle.NO_BORDER);
            table.addCell(cell);
        }
        if ((i % 3) != 0) {
            while ((i % 3) != 0) {
                i++;
                cell = new PdfPCell();
                cell.setBorder(Rectangle.NO_BORDER);
                table.addCell(cell);
            }
        }
        document.add(table);
        writer.flush();
        document.close();
        writer.close();
        file.setFileData(baos.toByteArray());
    } catch (DocumentException de) {
        System.out.println(de.getMessage());
    }
    return file;
}

From source file:classroom.filmfestival_b.Movies14.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {

    // step 1//from   w w  w.j a  va 2  s .co  m
    Document document = new Document();
    try {
        // step 2
        OutputStream os = new FileOutputStream(RESULT);
        PdfWriter.getInstance(document, os);
        // step 3
        document.open();
        // step 4
        Session session = (Session) MySessionFactory.currentSession();
        Query q = session.createQuery("from FilmTitle order by title");
        java.util.List<FilmTitle> results = q.list();

        PdfPTable table = new PdfPTable(2);
        table.setWidths(new float[] { 1, 5 });
        File f;
        Paragraph p;
        Chunk c;
        PdfPCell cell = new PdfPCell();
        Font bold = new Font(Font.HELVETICA, 12, Font.BOLD);
        Font italic = new Font(Font.HELVETICA, 12, Font.ITALIC);
        p = new Paragraph("FILMFESTIVAL", bold);
        p.setAlignment(Element.ALIGN_CENTER);
        cell.addElement(p);
        cell.setColspan(2);
        cell.setBorder(PdfPCell.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell();
        cell.setFixedHeight(20);
        cell.setColspan(2);
        cell.setBorder(PdfPCell.NO_BORDER);
        cell.setCellEvent(new Movies14().new PageCell());
        table.addCell(cell);
        table.setHeaderRows(2);
        table.setFooterRows(1);
        for (FilmTitle movie : results) {
            f = new File("resources/classroom/filmposters/" + movie.getFilmId() + ".jpg");
            if (f.exists()) {
                cell = new PdfPCell(Image.getInstance(f.getPath()), true);
                cell.setPadding(2);
            } else {
                cell = new PdfPCell();
            }
            table.addCell(cell);
            p = new Paragraph(20);
            c = new Chunk(movie.getTitle(), bold);
            c.setAnchor("http://cinema.lowagie.com/titel.php?id=" + movie.getFilmId());
            p.add(c);
            c = new Chunk(" (" + movie.getYear() + ") ", italic);
            p.add(c);
            c = new Chunk("IMDB");
            c.setAnchor("http://www.imdb.com/title/tt" + movie.getImdb());
            p.add(c);
            cell = new PdfPCell();
            cell.setUseAscender(true);
            cell.setUseDescender(true);
            cell.addElement(p);
            Set<DirectorName> directors = movie.getDirectorNames();
            List list = new List();
            for (DirectorName director : directors) {
                list.add(director.getName());
            }
            cell.addElement(list);
            table.addCell(cell);
        }
        document.add(table);
        // step 5
        document.close();
    } catch (IOException e) {
        LOGGER.error("IOException: ", e);
    } catch (DocumentException e) {
        LOGGER.error("DocumentException: ", e);
    }
}

From source file:classroom.filmfestival_b.Movies15.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {

    // step 1//w w w  .  ja  va  2  s  .  co  m
    Document document = new Document();
    try {
        // step 2
        OutputStream os = new FileOutputStream(RESULT);
        PdfWriter writer = PdfWriter.getInstance(document, os);
        // step 3
        document.open();
        // step 4
        Session session = (Session) MySessionFactory.currentSession();
        Query q = session.createQuery("from FilmTitle order by title");
        java.util.List<FilmTitle> results = q.list();

        PdfPTable table = new PdfPTable(2);
        table.setComplete(false);
        table.setWidths(new float[] { 1, 5 });
        File f;
        Paragraph p;
        Chunk c;
        PdfPCell cell = new PdfPCell();
        Font bold = new Font(Font.HELVETICA, 12, Font.BOLD);
        Font italic = new Font(Font.HELVETICA, 12, Font.ITALIC);
        p = new Paragraph("FILMFESTIVAL", bold);
        p.setAlignment(Element.ALIGN_CENTER);
        cell.addElement(p);
        cell.setColspan(2);
        cell.setBorder(PdfPCell.NO_BORDER);
        table.addCell(cell);
        cell = new PdfPCell();
        cell.setFixedHeight(20);
        cell.setColspan(2);
        cell.setBorder(PdfPCell.NO_BORDER);
        cell.setCellEvent(new Movies14().new PageCell());
        table.addCell(cell);
        table.setHeaderRows(2);
        table.setFooterRows(1);
        int counter = 10;
        for (FilmTitle movie : results) {
            f = new File("resources/classroom/filmposters/" + movie.getFilmId() + ".jpg");
            if (f.exists()) {
                cell = new PdfPCell(Image.getInstance(f.getPath()), true);
                cell.setPadding(2);
            } else {
                cell = new PdfPCell();
            }
            table.addCell(cell);
            p = new Paragraph(20);
            c = new Chunk(movie.getTitle(), bold);
            c.setAnchor("http://cinema.lowagie.com/titel.php?id=" + movie.getFilmId());
            p.add(c);
            c = new Chunk(" (" + movie.getYear() + ") ", italic);
            p.add(c);
            c = new Chunk("IMDB");
            c.setAnchor("http://www.imdb.com/title/tt" + movie.getImdb());
            p.add(c);
            cell = new PdfPCell();
            cell.setUseAscender(true);
            cell.setUseDescender(true);
            cell.addElement(p);
            Set<DirectorName> directors = movie.getDirectorNames();
            List list = new List();
            for (DirectorName director : directors) {
                list.add(director.getName());
            }
            cell.addElement(list);
            table.addCell(cell);
            if (counter % 10 == 0) {
                document.add(table);
            }
            System.out.println(writer.getPageNumber());
            counter++;
        }
        table.setComplete(true);
        document.add(table);
        // step 5
        document.close();
    } catch (IOException e) {
        LOGGER.error("IOException: ", e);
    } catch (DocumentException e) {
        LOGGER.error("DocumentException: ", e);
    }
}

From source file:classroom.filmfestival_c.Movies17.java

protected static void addScreening(PdfPTable outer, FestivalScreening screening) throws DocumentException {
    FilmTitle movie = screening.getFilmTitle();
    // we construct a 3 column table
    PdfPTable table = new PdfPTable(3);
    table.setWidths(WIDTHS);/*from  ww  w  .  j a v a2 s  .  co m*/
    // the first cell with the full title spans all the columns
    PdfPCell cell = new PdfPCell();
    cell.addElement(fullTitle(screening));
    cell.setColspan(3);
    cell.setBorder(PdfPCell.NO_BORDER);
    setColor(movie, cell);
    table.addCell(cell);

    cell = new PdfPCell();
    cell.setBorder(PdfPCell.NO_BORDER);
    cell.setUseAscender(true);
    cell.setUseDescender(true);
    table.addCell(cell);

    cell = new PdfPCell();
    cell.addElement(directors(movie));
    cell.setBorder(PdfPCell.NO_BORDER);
    cell.setUseAscender(true);
    cell.setUseDescender(true);
    table.addCell(cell);

    cell = new PdfPCell();
    cell.addElement(screenings(screening));
    cell.setBorder(PdfPCell.NO_BORDER);
    cell.setUseAscender(true);
    cell.setUseDescender(true);
    table.addCell(cell);

    outer.addCell(table);

}

From source file:classroom.filmfestival_c.Movies17.java

protected static Element fullTitle(FestivalScreening screening) throws DocumentException {
    FilmTitle movie = screening.getFilmTitle();
    // a table with 3 cells
    PdfPTable table = new PdfPTable(3);
    table.setWidths(INNER);//from w ww . j a  v a  2 s . com
    table.setWidthPercentage(100);

    // the title(s)
    Paragraph p = new Paragraph();
    p.add(new Phrase(movie.getTitle(), BOLD));
    p.setLeading(16);
    // maybe an alternative title
    if (movie.getATitle().trim().length() > 0) {
        p.add(new Phrase(" (" + movie.getATitle() + ")"));
    }
    PdfPCell cell = new PdfPCell();
    cell.addElement(p);
    cell.setBorder(PdfPCell.NO_BORDER);
    cell.setUseAscender(true);
    cell.setUseDescender(true);
    table.addCell(cell);

    // eXploreZone?
    cell = new PdfPCell();
    cell.setBorder(PdfPCell.NO_BORDER);
    if (isExploreZone(movie)) {
        cell.setBackgroundColor(WHITE);
        cell.setUseAscender(true);
        cell.setUseDescender(true);
        cell.addElement(new Paragraph("eXplore"));
    }
    table.addCell(cell);

    // Duration / shortfilm
    cell = new PdfPCell();
    cell.setBorder(PdfPCell.NO_BORDER);
    cell.setBackgroundColor(WHITE);
    cell.setUseAscender(true);
    cell.setUseDescender(true);
    StringBuffer buf = new StringBuffer();
    buf.append(movie.getDuration());
    buf.append('\'');
    if (getExtra(screening) > 0) {
        buf.append(" + KF");
        buf.append(getExtra(screening));
        buf.append('\'');
    }
    p = new Paragraph(buf.toString());
    p.setAlignment(Element.ALIGN_CENTER);
    cell.addElement(p);
    table.addCell(cell);
    return table;
}

From source file:com.actelion.research.spiritapp.ui.util.PDFUtils.java

License:Open Source License

public static void convertHSSF2Pdf(Workbook wb, String header, File reportFile) throws Exception {
    assert wb != null;
    assert reportFile != null;

    //Precompute formula
    FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
    for (int i = 0; i < wb.getNumberOfSheets(); i++) {
        Sheet sheet = wb.getSheetAt(i);//  ww w. j a  v a 2s  . co  m

        for (Row r : sheet) {
            for (Cell c : r) {
                if (c.getCellType() == HSSFCell.CELL_TYPE_FORMULA) {
                    try {
                        evaluator.evaluateFormulaCell(c);
                    } catch (Exception e) {
                        System.err.println(e);
                    }
                }
            }
        }
    }

    File tmp = File.createTempFile("tmp_", ".xlsx");
    try (OutputStream out = new BufferedOutputStream(new FileOutputStream(tmp))) {
        wb.write(out);
    }

    //Find page orientation
    int maxColumnsGlobal = 0;
    for (int sheetNo = 0; sheetNo < wb.getNumberOfSheets(); sheetNo++) {
        Sheet sheet = wb.getSheetAt(sheetNo);
        for (Iterator<Row> rowIterator = sheet.iterator(); rowIterator.hasNext();) {
            Row row = rowIterator.next();
            maxColumnsGlobal = Math.max(maxColumnsGlobal, row.getLastCellNum());
        }
    }

    Rectangle pageSize = maxColumnsGlobal < 10 ? PageSize.A4 : PageSize.A4.rotate();
    Document pdfDocument = new Document(pageSize, 10f, 10f, 20f, 20f);

    PdfWriter writer = PdfWriter.getInstance(pdfDocument, new FileOutputStream(reportFile));
    addHeader(writer, header);
    pdfDocument.open();
    //we have two columns in the Excel sheet, so we create a PDF table with two columns
    //Note: There are ways to make this dynamic in nature, if you want to.
    //Loop through sheets
    for (int sheetNo = 0; sheetNo < wb.getNumberOfSheets(); sheetNo++) {
        Sheet sheet = wb.getSheetAt(sheetNo);

        //Loop through rows, to find number of columns
        int minColumns = 1000;
        int maxColumns = 0;
        for (Iterator<Row> rowIterator = sheet.iterator(); rowIterator.hasNext();) {
            Row row = rowIterator.next();
            if (row.getFirstCellNum() >= 0)
                minColumns = Math.min(minColumns, row.getFirstCellNum());
            if (row.getLastCellNum() >= 0)
                maxColumns = Math.max(maxColumns, row.getLastCellNum());
        }
        if (maxColumns == 0)
            continue;

        //Loop through first rows, to find relative width
        float[] widths = new float[maxColumns];
        int totalWidth = 0;
        for (int c = 0; c < maxColumns; c++) {
            int w = sheet.getColumnWidth(c);
            widths[c] = w;
            totalWidth += w;
        }

        for (int c = 0; c < maxColumns; c++) {
            widths[c] /= totalWidth;
        }

        //Create new page and a new chapter with the sheet's name
        if (sheetNo > 0)
            pdfDocument.newPage();
        Chapter pdfSheet = new Chapter(sheet.getSheetName(), sheetNo + 1);

        PdfPTable pdfTable = null;
        PdfPCell pdfCell = null;
        boolean inTable = false;

        //Loop through cells, to create the content
        //         boolean leftBorder = true;
        //         boolean[] topBorder = new boolean[maxColumns+1];
        for (int r = 0; r <= sheet.getLastRowNum(); r++) {
            Row row = sheet.getRow(r);

            //Check if we exited a table (empty line)
            if (row == null) {
                if (pdfTable != null) {
                    addTable(pdfDocument, pdfSheet, totalWidth, widths, pdfTable);
                    pdfTable = null;
                }
                inTable = false;
                continue;
            }

            //Check if we start a table (>MIN_COL_IN_TABLE columns)
            if (row.getLastCellNum() >= MIN_COL_IN_TABLE) {
                inTable = true;
            }

            if (!inTable) {
                //Process the data outside table, just add the text
                boolean hasData = false;
                Iterator<Cell> cellIterator = row.cellIterator();
                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();
                    if (cell.getCellType() == Cell.CELL_TYPE_BLANK)
                        continue;
                    Chunk chunk = getChunk(wb, cell);
                    pdfSheet.add(chunk);
                    pdfSheet.add(new Chunk(" "));
                    hasData = true;
                }
                if (hasData)
                    pdfSheet.add(Chunk.NEWLINE);

            } else {
                //Process the data in table
                if (pdfTable == null) {
                    //Create table
                    pdfTable = new PdfPTable(maxColumns);
                    pdfTable.setWidths(widths);
                    //                  topBorder = new boolean[maxColumns+1];
                }

                int cellNumber = minColumns;
                //               leftBorder = false;
                Iterator<Cell> cellIterator = row.cellIterator();
                while (cellIterator.hasNext()) {

                    Cell cell = cellIterator.next();

                    for (; cellNumber < cell.getColumnIndex(); cellNumber++) {
                        pdfCell = new PdfPCell();
                        pdfCell.setBorder(0);
                        pdfTable.addCell(pdfCell);
                    }

                    Chunk phrase = getChunk(wb, cell);
                    pdfCell = new PdfPCell(new Phrase(phrase));
                    pdfCell.setFixedHeight(row.getHeightInPoints() - 3);
                    pdfCell.setNoWrap(!cell.getCellStyle().getWrapText());
                    pdfCell.setPaddingLeft(1);
                    pdfCell.setHorizontalAlignment(
                            cell.getCellStyle().getAlignment() == CellStyle.ALIGN_CENTER ? PdfPCell.ALIGN_CENTER
                                    : cell.getCellStyle().getAlignment() == CellStyle.ALIGN_RIGHT
                                            ? PdfPCell.ALIGN_RIGHT
                                            : PdfPCell.ALIGN_LEFT);
                    pdfCell.setUseBorderPadding(false);
                    pdfCell.setUseVariableBorders(false);
                    pdfCell.setBorderWidthRight(cell.getCellStyle().getBorderRight() == 0 ? 0 : .5f);
                    pdfCell.setBorderWidthBottom(cell.getCellStyle().getBorderBottom() == 0 ? 0
                            : cell.getCellStyle().getBorderBottom() > 1 ? 1 : .5f);
                    pdfCell.setBorderWidthLeft(cell.getCellStyle().getBorderLeft() == 0 ? 0
                            : cell.getCellStyle().getBorderLeft() > 1 ? 1 : .5f);
                    pdfCell.setBorderWidthTop(cell.getCellStyle().getBorderTop() == 0 ? 0
                            : cell.getCellStyle().getBorderTop() > 1 ? 1 : .5f);
                    String color = cell.getCellStyle().getFillForegroundColorColor() == null ? null
                            : ((XSSFColor) cell.getCellStyle().getFillForegroundColorColor()).getARGBHex();
                    if (color != null)
                        pdfCell.setBackgroundColor(new Color(Integer.decode("0x" + color.substring(2))));
                    pdfTable.addCell(pdfCell);
                    cellNumber++;
                }
                for (; cellNumber < maxColumns; cellNumber++) {
                    pdfCell = new PdfPCell();
                    pdfCell.setBorder(0);
                    pdfTable.addCell(pdfCell);
                }
            }

            //Custom code to add all images on the first sheet (works for reporting)
            if (sheetNo == 0 && row.getRowNum() == 0) {
                for (PictureData pd : wb.getAllPictures()) {
                    try {
                        Image pdfImg = Image.getInstance(pd.getData());
                        pdfImg.scaleToFit(
                                pageSize.getWidth() * .8f - pageSize.getBorderWidthLeft()
                                        - pageSize.getBorderWidthRight(),
                                pageSize.getHeight() * .8f - pageSize.getBorderWidthTop()
                                        - pageSize.getBorderWidthBottom());
                        pdfSheet.add(pdfImg);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        if (pdfTable != null) {
            addTable(pdfDocument, pdfSheet, totalWidth, widths, pdfTable);
        }

        pdfDocument.add(pdfSheet);
    }
    pdfDocument.close();

}

From source file:com.actelion.research.spiritapp.ui.util.PDFUtils.java

License:Open Source License

private static void addTable(Document pdfDocument, Chapter pdfSheet, int totalWidth, float[] widths,
        PdfPTable pdfTable) throws Exception {
    final int MAX_WIDTH = (int) (pdfDocument.getPageSize().getWidth() / 842 * 65000);
    //      if(totalWidth>MAX_WIDTH) {
    //Split the tables in subcolumns
    for (int offset = 0; offset < pdfTable.getNumberOfColumns();) {
        if (offset > 0)
            pdfSheet.add(new Chunk(" "));

        //Calculates the indexes that fit the page: [offset; index2]
        int subTotalWidth = 0;
        int index2;
        for (index2 = offset; index2 < pdfTable.getNumberOfColumns() && subTotalWidth < MAX_WIDTH; index2++) {
            subTotalWidth += widths[index2] * totalWidth;
        }/*from ww w.j a  v  a2 s . c om*/
        index2 = Math.min(index2, pdfTable.getNumberOfColumns() - 1);

        //Calculates the new sub widths
        float[] subWidths = new float[index2 - offset + 2];
        for (int i = 0; i < subWidths.length - 1; i++) {
            subWidths[i] = widths[offset + i] * totalWidth / MAX_WIDTH;
        }
        subWidths[subWidths.length - 1] = Math.max(0, (float) (MAX_WIDTH - subTotalWidth) / MAX_WIDTH);
        System.out.println("PDFUtils.addTable() " + Arrays.toString(subWidths));

        //Creates the new sub widths
        PdfPTable subtable = new PdfPTable(subWidths.length);
        subtable.setWidths(subWidths);
        for (int r = 0; r < pdfTable.getRows().size(); r++) {
            for (int c = 0; c < index2 - offset + 1; c++) {
                PdfPCell cell = pdfTable.getRow(r).getCells()[c + offset];
                subtable.addCell(cell);
            }
            PdfPCell pdfCell = new PdfPCell();
            pdfCell.setBorder(0);
            subtable.addCell(pdfCell);
        }

        subtable.setWidthPercentage(100);
        collapseBorder(subtable);
        pdfSheet.add(subtable);

        //Go to the next index offset
        offset = index2 + 1;
    }
    //      } else {
    //         //Calculates the new sub widths
    //         float[] subWidths = new float[widths.length+1];
    //         for (int i = 0; i < subWidths.length-1; i++) {
    //            subWidths[i] = widths[0]*totalWidth/MAX_WIDTH;
    //         }
    //         subWidths[subWidths.length-1] = Math.max(0, (float)(MAX_WIDTH-totalWidth)/MAX_WIDTH);
    //         pdfTable.setWidths(subWidths);
    //         pdfTable.setWidthPercentage(100);
    //         collapseBorder(pdfTable);
    //         pdfSheet.add(pdfTable);
    //      }
}

From source file:com.aryjr.nheengatu.pdf.PDFTable.java

License:Open Source License

private static PdfPCell createCell(final Tag ref) {
    final PdfPCell cell = new PdfPCell();
    cell.setBorderWidth(ref.getPropertyValue(PDFTable.CELLSPACING) == null ? 1
            : Integer.parseInt(ref.getPropertyValue(PDFTable.CELLSPACING)));
    cell.setPadding(ref.getPropertyValue(PDFTable.CELLPADDING) == null ? 1
            : Integer.parseInt(ref.getPropertyValue(PDFTable.CELLPADDING)));
    cell.setColspan(Integer.parseInt(
            ref.getPropertyValue(PDFTable.COLSPAN) == null ? "0" : ref.getPropertyValue(PDFTable.COLSPAN)));
    cell.setNoWrap(ref.getPropertyValue("nowrap") != null);
    return cell;//w w w  .j a v a 2  s  .  c  om
}

From source file:com.bytecode.customexporter.PDFCustomExporter.java

protected void exportCells(DataTable table, PdfPTable pdfTable) {
    for (UIColumn col : table.getColumns()) {

        if (col instanceof DynamicColumn) {
            ((DynamicColumn) col).applyStatelessModel();
        }// w  w w  . j av  a 2 s.co m

        if (col.isRendered() && col.isExportable()) {
            if (col.getSelectionMode() != null) {
                pdfTable.addCell(new Paragraph(col.getSelectionMode(), this.cellFont));
                continue;
            }
            addColumnValue(pdfTable, col.getChildren(), this.cellFont, "data");
        }

    }
    pdfTable.completeRow();
    FacesContext context = null;
    if (table.getRowIndex() == 0) {
        for (UIComponent component : table.getChildren()) {
            if (component instanceof RowExpansion) {
                RowExpansion rowExpansion = (RowExpansion) component;
                if (rowExpansion.getChildren() != null) {
                    if (rowExpansion.getChildren().get(0) instanceof DataTable) {
                        DataTable childTable = (DataTable) rowExpansion.getChildren().get(0);
                        childTable.setRowIndex(-1);
                    }
                    if (rowExpansion.getChildren().get(0) instanceof DataList) {
                        DataList childList = (DataList) rowExpansion.getChildren().get(0);
                        childList.setRowIndex(-1);
                    }
                }

            }
        }
    }
    for (UIComponent component : table.getChildren()) {
        if (component instanceof RowExpansion) {
            RowExpansion rowExpansion = (RowExpansion) component;
            if (rowExpansion.getChildren() != null) {
                if (rowExpansion.getChildren().get(0) instanceof DataTable) {
                    DataTable childTable = (DataTable) rowExpansion.getChildren().get(0);
                    PdfPTable pdfTableChild = exportPDFTable(context, childTable, false, false, "-", false);
                    PdfPCell cell = new PdfPCell();
                    cell.addElement(pdfTableChild);
                    cell.setColspan(pdfTable.getNumberOfColumns());
                    pdfTable.addCell(cell);
                }
                if (rowExpansion.getChildren().get(0) instanceof DataList) {
                    DataList list = (DataList) rowExpansion.getChildren().get(0);
                    PdfPTable pdfTableChild = exportPDFTable(context, list, false, "-");
                    pdfTableChild.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                    PdfPCell cell = new PdfPCell();
                    cell.addElement(pdfTableChild);
                    cell.setColspan(pdfTable.getNumberOfColumns());
                }
            }

        }
        pdfTable.completeRow();
    }

}

From source file:com.concursive.connect.web.modules.wiki.utils.WikiPDFUtils.java

License:Open Source License

private static String parseTable(WikiPDFContext context, Wiki wiki, String line, Document document,
        Connection db, ArrayList<Integer> wikiListTodo, ArrayList<Integer> wikiListDone, BufferedReader in)
        throws Exception {
    if (line == null) {
        return null;
    }//from w  w  w.  j av a 2 s . co m
    PdfPTable pdfTable = null;
    int columnCount = 0;
    int rowCount = 0;

    // Keep track of the table's custom styles
    HashMap<Integer, String> cStyle = new HashMap<Integer, String>();

    while (line != null && (line.startsWith("|") || line.startsWith("!"))) {

        // Build a complete line
        String lineToParse = line;
        while (!line.endsWith("|")) {
            line = in.readLine();
            if (line == null) {
                // there is an error in the line to process
                return null;
            }
            if (line.startsWith("!")) {
                lineToParse += CRLF + line.substring(1);
            }
        }
        line = lineToParse;

        // Determine if the row can output
        boolean canOutput = true;

        ++rowCount;

        String cellType = null;
        Scanner sc = null;
        if (line.startsWith("||") && line.endsWith("||")) {
            cellType = "th";
            sc = new Scanner(line).useDelimiter("[|][|]");
            //        sc = new Scanner(line.substring(2, line.length() - 2)).useDelimiter("[|][|]");
        } else if (line.startsWith("|")) {
            cellType = "td";
            sc = new Scanner(line.substring(1, line.length() - 1)).useDelimiter("\\|(?=[^\\]]*(?:\\[|$))");
        }

        if (sc != null) {

            if (rowCount == 1) {
                // Count the columns, get the specified widths too...
                while (sc.hasNext()) {
                    ++columnCount;
                    sc.next();
                }
                // Reset the scanner now that the columns have been counted
                if (line.startsWith("||") && line.endsWith("||")) {
                    sc = new Scanner(line).useDelimiter("[|][|]");
                } else if (line.startsWith("|")) {
                    sc = new Scanner(line.substring(1, line.length() - 1))
                            .useDelimiter("\\|(?=[^\\]]*(?:\\[|$))");
                }

                // Start the table
                pdfTable = new PdfPTable(columnCount);
                //pdfTable.setWidthPercentage(100);
                pdfTable.setHorizontalAlignment(Element.ALIGN_LEFT);
                pdfTable.setSpacingBefore(10);
                pdfTable.setWidthPercentage(100);
                pdfTable.setKeepTogether(true);
            }

            // Determine the column span
            int colSpan = 1;
            // Determine the cell being output
            int cellCount = 0;

            while (sc.hasNext()) {
                String cellData = sc.next();
                if (cellData.length() == 0) {
                    ++colSpan;
                    continue;
                }

                // Track the cell count being output
                ++cellCount;

                if (rowCount == 1) {
                    // Parse and validate the style input
                    LOG.debug("Checking style value: " + cellData);
                    if (cellData.startsWith("{") && cellData.endsWith("}")) {
                        String[] style = cellData.substring(1, cellData.length() - 1).split(":");
                        String attribute = style[0].trim();
                        String value = style[1].trim();
                        // Determine the width of each column and store it
                        if ("width".equals(attribute)) {
                            // Validate the width style
                            if (StringUtils.hasAllowedOnly("0123456789%.", value)) {
                                cStyle.put(cellCount, attribute + ": " + value + ";");
                            }
                        } else {
                            LOG.debug("Unsupported style: " + cellData);
                        }
                        canOutput = false;
                    }
                }

                // Output the header
                if (canOutput) {

                    PdfPCell cell = new PdfPCell();
                    cell.setPadding(10);
                    cell.setBorderColor(new Color(100, 100, 100));
                    if ("th".equals(cellType)) {
                        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                        cell.setBackgroundColor(new Color(0xC0, 0xC0, 0xC0));
                    }
                    if (colSpan > 1) {
                        cell.setColspan(colSpan);
                    }

                    // Output the data
                    if (" ".equals(cellData) || "".equals(cellData)) {
                        // Put a blank space in blank cells for output consistency
                        cell.addElement(new Chunk(" "));
                        LOG.debug("   OUTPUTTING A BLANK");
                    } else {
                        // Output the cell as a complete wiki
                        float cellWidth = (100.0f / columnCount);
                        parseContent(context, wiki, cellData, document, cell, db, wikiListTodo, wikiListDone,
                                cellWidth);
                        LOG.debug("   OUTPUTTING CONTENT");
                    }
                    pdfTable.addCell(cell);
                }
            }
        }
        // read another line to see if it's part of the table
        line = in.readLine();
    }
    if (pdfTable != null) {
        LOG.debug("document.add(pdfTable)");
        document.add(pdfTable);
        //          document.add(Chunk.NEWLINE);
    }
    return line;
}