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

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

Introduction

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

Prototype

public void setNoWrap(boolean noWrap) 

Source Link

Document

Setter for property noWrap.

Usage

From source file:biblivre3.cataloging.bibliographic.BiblioBO.java

License:Open Source License

public MemoryFileDTO createFileLabelsPDF(ArrayList<LabelDTO> labels, LabelConfigDTO labelConfig) {
    Document document = new Document();
    final MemoryFileDTO file = new MemoryFileDTO();
    file.setFileName("biblivre_etiquetas_" + new Date().getTime() + ".pdf");
    try {//from  w w w.  j a  v a2s  .c  o  m
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        document.setPageSize(PageSize.A4);
        float verticalMargin = (297.0f - (labelConfig.getHeight() * labelConfig.getRows())) / 2;
        document.setMargins(7.15f * ApplicationConstants.MM_UNIT, 7.15f * ApplicationConstants.MM_UNIT,
                verticalMargin * ApplicationConstants.MM_UNIT, verticalMargin * ApplicationConstants.MM_UNIT);
        document.open();

        PdfPTable table = new PdfPTable(labelConfig.getColumns());
        table.setWidthPercentage(100f);
        PdfPCell cell;

        int i = 0;
        for (i = 0; i < labelConfig.getOffset(); i++) {
            cell = new PdfPCell();
            cell.setBorder(Rectangle.NO_BORDER);
            cell.setFixedHeight(labelConfig.getHeight() * ApplicationConstants.MM_UNIT);
            table.addCell(cell);
        }

        for (LabelDTO ldto : labels) {
            PdfContentByte cb = writer.getDirectContent();

            String holdingSerial = String.valueOf(ldto.getHoldingSerial());
            while (holdingSerial.length() < 10) {
                holdingSerial = "0" + holdingSerial;
            }
            Barcode39 code39 = new Barcode39();
            code39.setExtended(true);
            code39.setCode(holdingSerial);
            code39.setStartStopText(false);

            Image image39 = code39.createImageWithBarcode(cb, null, null);
            if (labelConfig.getHeight() > 30.0f) {
                image39.scalePercent(110f);
            } else {
                image39.scalePercent(90f);
            }

            Paragraph para = new Paragraph();
            Phrase p1 = new Phrase(StringUtils.left(ldto.getAuthor(), 28) + "\n");
            Phrase p2 = new Phrase(StringUtils.left(ldto.getTitle(), 28) + "\n\n");
            Phrase p3 = new Phrase(new Chunk(image39, 0, 0));
            para.add(p1);
            para.add(p2);
            para.add(p3);

            cell = new PdfPCell(para);
            i++;
            cell.setNoWrap(true);
            cell.setFixedHeight(labelConfig.getHeight() * ApplicationConstants.MM_UNIT);
            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
            cell.setBorder(Rectangle.NO_BORDER);
            table.addCell(cell);

            Paragraph para2 = new Paragraph();
            Phrase p5 = new Phrase(ldto.getLocationA() + "\n");
            Phrase p6 = new Phrase(ldto.getLocationB() + "\n");
            Phrase p7 = new Phrase(ldto.getLocationC() + "\n");
            Phrase p8 = new Phrase(ldto.getLocationD() + "\n");
            Phrase p4 = new Phrase(ldto.getAssetHolding() + "\n");
            para2.add(p5);
            para2.add(p6);
            para2.add(p7);
            para2.add(p8);
            para2.add(p4);

            cell = new PdfPCell(para2);
            i++;
            cell.setFixedHeight(labelConfig.getHeight() * ApplicationConstants.MM_UNIT);
            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
            cell.setBorder(Rectangle.NO_BORDER);
            table.addCell(cell);
        }
        if ((i % labelConfig.getColumns()) != 0) {
            while ((i % labelConfig.getColumns()) != 0) {
                i++;
                cell = new PdfPCell();
                cell.setBorder(Rectangle.NO_BORDER);
                table.addCell(cell);
            }
        }
        document.add(table);
        writer.flush();
        document.close();
        file.setFileData(baos.toByteArray());
    } catch (Exception de) {
        System.out.println(de.getMessage());
    }
    return file;
}

From source file:ca.sqlpower.architect.profile.output.ProfilePDFFormat.java

License:Open Source License

private void addBodyRow(TableProfileResult tProfile, ColumnProfileResult result, DDLGenerator ddlg,
        PdfPTable table, BaseFont bf, Font f, float fsize, float[] widths)
        throws DocumentException, IOException, SQLObjectException, SQLException {

    SQLColumn col = result.getProfiledObject();

    int rowCount = -1;
    if (tProfile != null && tProfile.getException() == null) {
        rowCount = tProfile.getRowCount();
    }//from ww w.  j  a v  a 2s.  c  om
    java.util.List<ColumnValueCount> topTen = null;

    boolean errorColumnProfiling = false;
    Exception columnException = null;
    if (result != null && result.getException() == null) {
        topTen = result.getValueCount();
    } else {
        errorColumnProfiling = true;
        if (result != null && result.getException() != null) {
            columnException = result.getException();
            logger.debug("Exception " + columnException + " on column " + col.getName());
        }
    }

    DecimalFormat pctFormat = new DecimalFormat("0%");

    DecimalFormat df = new DecimalFormat("#,##0.00");
    df.setMaximumFractionDigits(col.getScale());
    df.setMinimumFractionDigits(col.getScale());

    DecimalFormat adf = new DecimalFormat("#,##0.00");
    adf.setMaximumFractionDigits(Math.max(2, col.getScale()));
    adf.setMinimumFractionDigits(Math.max(2, col.getScale()));

    DecimalFormat aldf = new DecimalFormat("#,##0.0");
    aldf.setMaximumFractionDigits(1);
    aldf.setMinimumFractionDigits(0);

    boolean errorSpanRemaining = false;
    for (int colNo = 0; colNo < totalColumn; colNo++) {

        String contents;
        int alignment;

        if (headings[colNo].equalsIgnoreCase("table name")) {
            String fqTableName = SQLObjectUtils.toQualifiedName(col.getParent(), SQLDatabase.class);
            if (tProfile == null || tProfile.getException() != null) {
                contents = fqTableName + "\nProfiling Error:\n";
                if (tProfile != null && tProfile.getException() != null) {
                    contents += tProfile.getException();
                    errorSpanRemaining = true;
                }
            } else {
                contents = fqTableName;
            }
            alignment = Element.ALIGN_LEFT;
        } else if (headings[colNo].equalsIgnoreCase("row count")) {
            contents = String.valueOf(rowCount);
            alignment = Element.ALIGN_RIGHT;
        } else if (headings[colNo].equalsIgnoreCase("column name")) {
            contents = col.getName();
            alignment = Element.ALIGN_LEFT;
        } else if (headings[colNo].equalsIgnoreCase("data type")) {
            contents = ddlg.columnType(col);
            alignment = Element.ALIGN_LEFT;
        } else if (headings[colNo].equalsIgnoreCase("null count")) {

            if (errorColumnProfiling) {
                if (result == null) {
                    contents = "Column Profiling Not Found\n";
                } else {
                    contents = "Column Profiling Error:\n";
                    if (columnException != null) {
                        contents += columnException;
                        errorSpanRemaining = true;
                    }
                }
                alignment = Element.ALIGN_LEFT;
            } else {
                if (col.isDefinitelyNullable()) {
                    contents = String.valueOf(result.getNullCount());
                } else {
                    contents = "---";
                }
                alignment = Element.ALIGN_RIGHT;
            }
        } else if (headings[colNo].equalsIgnoreCase("% null")) {
            if (errorColumnProfiling) {
                continue;
            } else {
                if (col.isDefinitelyNullable()) {
                    if (rowCount <= 0) {
                        contents = "N/A";
                        alignment = Element.ALIGN_CENTER;
                    } else {
                        contents = pctFormat.format(result.getNullCount() / (double) rowCount);
                        alignment = Element.ALIGN_RIGHT;
                    }
                } else {
                    contents = "---";
                    alignment = Element.ALIGN_CENTER;
                }
            }
        } else if (headings[colNo].equalsIgnoreCase("Unique Count")) {
            if (!errorColumnProfiling) {
                contents = String.valueOf(result.getDistinctValueCount());
                alignment = Element.ALIGN_RIGHT;
            } else {
                continue;
            }
        } else if (headings[colNo].equalsIgnoreCase("% unique")) {
            if (!errorColumnProfiling) {
                if (rowCount == 0) {
                    contents = "N/A";
                    alignment = Element.ALIGN_CENTER;
                } else {
                    contents = pctFormat.format(result.getDistinctValueCount() / (double) rowCount);
                    alignment = Element.ALIGN_RIGHT;
                }
            } else {
                continue;
            }
        } else if (headings[colNo].equalsIgnoreCase("Min Length")) {
            if (!errorColumnProfiling) {
                contents = String.valueOf(result.getMinLength());
                alignment = Element.ALIGN_RIGHT;
            } else {
                contents = "";
                alignment = Element.ALIGN_LEFT;
            }
        } else if (headings[colNo].equalsIgnoreCase("Max Length")) {
            if (!errorColumnProfiling) {
                contents = String.valueOf(result.getMaxLength());
                alignment = Element.ALIGN_RIGHT;
            } else {
                contents = "";
                alignment = Element.ALIGN_LEFT;
            }
        } else if (headings[colNo].equalsIgnoreCase("avg Length")) {
            if (!errorColumnProfiling) {
                contents = aldf.format(result.getAvgLength());
                alignment = Element.ALIGN_RIGHT;
            } else {
                contents = "";
                alignment = Element.ALIGN_LEFT;
            }
        } else if (headings[colNo].equalsIgnoreCase("Min value")) {
            if (!errorColumnProfiling) {
                if (result.getMinValue() == null) {
                    alignment = Element.ALIGN_CENTER;
                    contents = "";
                } else if (result.getMinValue() instanceof Number) {
                    alignment = Element.ALIGN_RIGHT;
                    contents = df.format((Number) result.getMinValue());
                } else {
                    alignment = Element.ALIGN_LEFT;
                    contents = String.valueOf(result.getMinValue());
                }
                alignment = Element.ALIGN_LEFT;
            } else {
                contents = "";
                alignment = Element.ALIGN_LEFT;
            }
        } else if (headings[colNo].equalsIgnoreCase("Max value")) {
            if (!errorColumnProfiling) {
                if (result.getMaxValue() == null) {
                    alignment = Element.ALIGN_CENTER;
                    contents = "";
                } else if (result.getMaxValue() instanceof Number) {
                    alignment = Element.ALIGN_RIGHT;
                    contents = df.format((Number) result.getMaxValue());
                } else {
                    alignment = Element.ALIGN_LEFT;
                    contents = String.valueOf(result.getMaxValue());
                }
                alignment = Element.ALIGN_LEFT;
            } else {
                contents = "";
                alignment = Element.ALIGN_LEFT;
            }
        } else if (headings[colNo].equalsIgnoreCase("avg value")) {
            if (!errorColumnProfiling) {
                if (result.getAvgValue() == null) {
                    alignment = Element.ALIGN_CENTER;
                    contents = "";
                } else if (result.getAvgValue() instanceof Number) {
                    alignment = Element.ALIGN_RIGHT;
                    contents = adf.format((Number) result.getAvgValue());
                } else {
                    alignment = Element.ALIGN_LEFT;
                    contents = String.valueOf(result.getAvgValue());
                }
            } else {
                contents = "";
                alignment = Element.ALIGN_LEFT;
            }
        } else if (headings[colNo].equalsIgnoreCase("Top N Values")) {
            if (!errorColumnProfiling && topTen != null) {
                StringBuffer sb = new StringBuffer();
                for (ColumnValueCount cvc : topTen) {
                    sb.append(cvc.getValue()).append("\n");
                }
                contents = sb.toString();
                alignment = Element.ALIGN_LEFT;
            } else {
                contents = "";
                alignment = Element.ALIGN_LEFT;
            }
        } else if (headings[colNo].equalsIgnoreCase("Count")) {
            if (!errorColumnProfiling) {
                StringBuffer sb = new StringBuffer();
                for (ColumnValueCount cvc : topTen) {
                    sb.append(cvc.getCount()).append("\n");
                }
                contents = sb.toString();
                alignment = Element.ALIGN_RIGHT;
            } else {
                contents = "";
                alignment = Element.ALIGN_LEFT;
            }
        } else {
            throw new IllegalStateException("I don't know about column " + colNo);
        }

        StringBuffer truncContents = new StringBuffer(contents.length());

        // update column width to reflect the widest cell
        for (String contentLine : contents.split("\n")) {
            String newLine;
            if (truncateLength >= 0 && !errorSpanRemaining) {
                if (bf.getWidthPoint(contentLine, fsize) < truncateLength) {
                    newLine = contentLine + "\n";
                } else {
                    double currentLength = bf.getWidthPoint("...", fsize);
                    int stringPosition = 0;
                    for (; stringPosition < contentLine.length(); stringPosition++) {
                        if (currentLength > truncateLength) {
                            break;
                        }
                        currentLength = bf.getWidthPoint(contentLine.substring(0, stringPosition) + "...",
                                fsize);
                        stringPosition++;
                    }
                    newLine = contentLine.substring(0, stringPosition - 1) + "...\n";
                }
            } else {
                newLine = contentLine + "\n";
            }
            truncContents.append(newLine);
            if (!errorSpanRemaining) {
                widths[colNo] = Math.max(widths[colNo], bf.getWidthPoint(newLine, fsize));
                logger.debug("width is now " + widths[colNo] + " for column " + colNo);
            }
        }

        PdfPCell cell;
        if (headings[colNo].equalsIgnoreCase("Top N Values") || headings[colNo].equalsIgnoreCase("Count")) {
            cell = new PdfPCell(new Paragraph(truncContents.toString(), f));
            cell.setNoWrap(true);
        } else if (headings[colNo].equalsIgnoreCase("null count") && errorColumnProfiling) {
            cell = new PdfPCell(new Paragraph(truncContents.toString(), f));
            cell.setColspan(4);
        } else {
            Phrase phr = new Phrase(truncContents.toString(), f);
            cell = new PdfPCell(phr);

        }
        //            cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(alignment);
        if (errorSpanRemaining) {
            cell.setColspan(totalColumn - colNo);
        }
        table.addCell(cell);
        if (errorSpanRemaining) {
            break;
        }
    }
}

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);//  w  w w.ja  va 2 s . 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.aryjr.nheengatu.pdf.PDFTable.java

License:Open Source License

private static float extractVisibleComponents(final Tag tag, final PdfPCell cell, final Paragraph paragraph,
        float cellWidth) throws DocumentException {
    final Iterator tags = tag.tags();// tags inside the cell
    Object component;/*from w  w  w . j a va2s .  c  o m*/
    final TagsManager tm = TagsManager.getInstance();
    // Seting the HTML row or table background color
    if (tag.getName().equalsIgnoreCase("TD")) {
        cell.setBorderColor(tm.getPreviousState(2).getBgcolor());
        cell.setBorderWidth(tag.getPropertyValue(PDFTable.CELLSPACING) == null ? 1
                : Integer.parseInt(tag.getPropertyValue(PDFTable.CELLSPACING)));
        //cell.setBackgroundColor(tm.getBgcolor());
        cell.setBackgroundColor(new Color(255, 255, 255));
        cell.setVerticalAlignment(tm.getValign());
        cell.setHorizontalAlignment(tm.getAlign());
        paragraph.setAlignment(tm.getAlign());
    }
    while (tags.hasNext()) {
        component = tags.next();
        if (component instanceof Text) {
            String s = ((Text) component).getText();
            if (s.contains("\\\"")) {
                s = s.replace("\\\"", "\"");
                ((Text) component).setText(s);
            }
            // If it's a text, create a iText text component for it
            paragraph.add(PDFText.createChunk((Text) component));
            cellWidth += PDFText.getWidth((Text) component);
        } else if (component instanceof Tag && ((Tag) component).getName().equalsIgnoreCase("br")) {
            // If it's a HTML line break
            paragraph.add("\n");
        } else if (component instanceof Tag && ((Tag) component).getName().equalsIgnoreCase("img")) {
            // If it's a HTML image, create a iText image component for it
            try {
                final Image img = PDFImage.createImage((Tag) component);
                //Nato: paragraph.add(new Chunk(img, 0, -2));
                paragraph.add(new Chunk(img, 0, 0));
                cellWidth += img.getScaledWidth();
                // TODO Is there an iText bug here?
                //if (img.scaledHeight() == 1f) {
                //cell.setFixedHeight(img.getScaledHeight());
                //}
            } catch (final Exception e) {
                e.printStackTrace();
            }
        } else if (component instanceof Tag && ((Tag) component).getName().equalsIgnoreCase("table")) {
            // If it's a HTML table, create a iText table component for it
            try {
                // TODO the default value of nowrap here will be true or
                // false??? If true, there is a problem with the cell width
                cell.setNoWrap(false);
                final PDFTable t = PDFTable.createTable((Tag) component);
                cell.addElement(t);
                final float[] cw = t.getWidths();
                for (final float element : cw) {
                    cellWidth += element;
                }
            } catch (final Exception e) {
                e.printStackTrace();
            }
        } else if (component instanceof Tag && ((Tag) component).getName().equalsIgnoreCase("select")) {
            // If it's a HTML select field, I will get only the selected
            // option
            final Tag select = (Tag) component;
            Tag opt;
            tm.checkTag(select);
            final Iterator opts = select.tags();
            boolean selected = false;
            while (opts.hasNext()) {
                opt = (Tag) opts.next();
                if (opt.getPropertyValue("selected") != null) {
                    tm.checkTag(opt);
                    cellWidth = PDFTable.extractVisibleComponents(opt, cell, paragraph, cellWidth);
                    selected = true;
                    break;
                }
            }
            if (!selected) {
                // if none option have the selected attribute the first will
                // be shown
                opt = select.getFirstTag("option");
                tm.checkTag(opt);
                cellWidth = PDFTable.extractVisibleComponents(opt, cell, paragraph, cellWidth);
            }
        } else {
            // If it's an another tag, check the name and call this method
            // again
            tm.checkTag((Tag) component);
            cellWidth = PDFTable.extractVisibleComponents((Tag) component, cell, paragraph, cellWidth);
            tm.back();
        }
    }
    return cellWidth;
}

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;//from   w  w  w .  j a v  a 2 s .  co  m
}

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

License:Open Source License

protected static String parseForm(WikiPDFContext context, Connection db, BufferedReader in, String line,
        Document document, PdfPCell cell) throws Exception {
    if (line == null) {
        return line;
    }/*w  ww.j  av  a  2 s .  c o  m*/
    CustomForm form = WikiToHTMLUtils.retrieveForm(in, line);
    LOG.debug("parseForm");
    for (CustomFormGroup group : form) {
        LOG.debug(" group...");
        // Start the table

        PdfPTable pdfTable = new PdfPTable(2);
        pdfTable.setHorizontalAlignment(Element.ALIGN_LEFT);
        pdfTable.setSpacingBefore(10);
        //      pdfTable.setWidthPercentage(100);
        pdfTable.setKeepTogether(true);

        if (group.getDisplay() && StringUtils.hasText(group.getName())) {
            // output the 1st row with a colspan of 2
            if (StringUtils.hasText(group.getName())) {
                Paragraph groupParagraph = new Paragraph(group.getName());
                PdfPCell groupCell = new PdfPCell(groupParagraph);
                groupCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                groupCell.setColspan(2);
                groupCell.setPadding(20);
                groupCell.setBorderColor(new Color(100, 100, 100));
                groupCell.setBackgroundColor(new Color(200, 200, 200));
                groupCell.setNoWrap(true);
                pdfTable.addCell(groupCell);
            }
        }
        for (CustomFormField field : group) {
            LOG.debug("  field...");
            if (field.hasValue()) {
                // output the row (2 columns: label, value)
                Paragraph fieldLabelParagraph = new Paragraph(field.getLabel());
                PdfPCell fieldLabelCell = new PdfPCell(fieldLabelParagraph);
                fieldLabelCell.setPadding(20);
                fieldLabelCell.setBorderColor(new Color(100, 100, 100));
                //          fieldLabelCell.setNoWrap(true);
                pdfTable.addCell(fieldLabelCell);

                Paragraph fieldValueParagraph = new Paragraph(getFieldValue(context, field));
                PdfPCell fieldValueCell = new PdfPCell(fieldValueParagraph);
                fieldValueCell.setPadding(20);
                fieldValueCell.setBorderColor(new Color(100, 100, 100));
                //          fieldValueCell.setNoWrap(true);
                pdfTable.addCell(fieldValueCell);
            }
        }
        LOG.debug("document.add(pdfTable)");
        document.add(pdfTable);

    }
    return null;
}

From source file:com.efficio.fieldbook.service.LabelPrintingServiceImpl.java

License:Open Source License

/**
 * Gets the cell height./*ww w.j  a v a  2 s  .co  m*/
 *
 * @param numberOfRowsPerPage the number of rows per page
 * @param pageSizeId the page size id
 * @return the cell height
 */
/*
private float getCellHeight(int numberOfRowsPerPage, int pageSizeId){
if(pageSizeId == AppConstants.SIZE_OF_PAPER_A4){
    if(numberOfRowsPerPage == 7){
        return 108f; //ok
    }else if(numberOfRowsPerPage == 8){
        return 97f;//ok
    }else if(numberOfRowsPerPage == 10){
        return 72.5f;
    }
}else{
    if(numberOfRowsPerPage == 7){
        return 108f; //ok
    }else if(numberOfRowsPerPage == 8){
        return 98.1f;//ok
    }else if(numberOfRowsPerPage == 10){
        return 72.5f;//ok
    }
}
           
return 0f;
}
*/
/* (non-Javadoc)
 * @see com.efficio.fieldbook.service.api.LabelPrintingService#generateLabels(com.efficio.fieldbook.web.fieldmap.bean.UserFieldmap)
 */
@Override
public String generatePDFLabels(List<StudyTrialInstanceInfo> trialInstances,
        UserLabelPrinting userLabelPrinting, ByteArrayOutputStream baos) throws MiddlewareQueryException {

    // setUserLabelPrinting(form.getUserLabelPrinting());
    int pageSizeId = Integer.parseInt(userLabelPrinting.getSizeOfLabelSheet());
    int numberOfLabelPerRow = Integer.parseInt(userLabelPrinting.getNumberOfLabelPerRow());
    int numberofRowsPerPageOfLabel = Integer.parseInt(userLabelPrinting.getNumberOfRowsPerPageOfLabel());
    int totalPerPage = numberOfLabelPerRow * numberofRowsPerPageOfLabel;
    String leftSelectedFields = userLabelPrinting.getLeftSelectedLabelFields();
    String rightSelectedFields = userLabelPrinting.getRightSelectedLabelFields();
    String barcodeNeeded = userLabelPrinting.getBarcodeNeeded();

    String firstBarcodeField = userLabelPrinting.getFirstBarcodeField();
    String secondBarcodeField = userLabelPrinting.getSecondBarcodeField();
    String thirdBarcodeField = userLabelPrinting.getThirdBarcodeField();

    String currentDate = DateUtil.getCurrentDate();
    // String fileName = currentDate + ".pdf";

    String fileName = userLabelPrinting.getFilenameDLLocation();

    try {
        FileOutputStream fileOutputStream = new FileOutputStream(fileName);

        try {

            // Image image1 = Image.getInstance(imageLocation);

            // PageSize.A4
            LabelPaper paper = LabelPaperFactory.generateLabelPaper(numberOfLabelPerRow,
                    numberofRowsPerPageOfLabel, pageSizeId);

            Rectangle pageSize = PageSize.LETTER;

            if (pageSizeId == AppConstants.SIZE_OF_PAPER_A4.getInt())
                pageSize = PageSize.A4;

            Document document = new Document(pageSize);
            /*
             * 2, 2, 33.3f, 5
             * 15, 0, 42, 5
             * 10, 0, 17, 5
             * 10, 0, 17, 5
             * 5, 0, 0, 5
             * 15, 0, 37, 5
             * 10, 0, 17, 5
            if (pageSizeId == AppConstants.SIZE_OF_PAPER_LETTER) {
            if (numberofRowsPerPageOfLabel == 7)
                document.setMargins(10, 0, 17, 5);
            else if (numberofRowsPerPageOfLabel == 8)
                document.setMargins(5, 0, 0, 5);
            else if (numberofRowsPerPageOfLabel == 10)
                document.setMargins(2, 2, 33.3f, 5);
            } else if (pageSizeId == AppConstants.SIZE_OF_PAPER_A4) {
            if (numberofRowsPerPageOfLabel == 7)
                document.setMargins(15, 0, 42, 5);
            else if (numberofRowsPerPageOfLabel == 8)
                document.setMargins(15, 0, 37, 5);
            else if (numberofRowsPerPageOfLabel == 10)
                document.setMargins(6, 2, 17.5f, 5);
            }
            */
            //float marginLeft, float marginRight, float marginTop, float marginBottom
            document.setMargins(paper.getMarginLeft(), paper.getMarginRight(), paper.getMarginTop(),
                    paper.getMarginBottom());

            // PdfWriter writer = PdfWriter.getInstance(document, baos);
            PdfWriter writer = PdfWriter.getInstance(document, fileOutputStream);
            // step 3
            document.open();
            // step 4

            PdfContentByte canvas = writer.getDirectContent();

            int i = 0;
            int fixTableRowSize = numberOfLabelPerRow;
            PdfPTable table = new PdfPTable(fixTableRowSize);

            // table.writeSelectedRows(0, -1, 10, 12, canvas);
            float columnWidthSize = 265f;// 180f;
            float[] widthColumns = new float[fixTableRowSize];

            for (int counter = 0; counter < widthColumns.length; counter++) {
                widthColumns[counter] = columnWidthSize;
            }

            table.setWidths(widthColumns);
            table.setWidthPercentage(100);
            int width = 600;
            int height = 75;

            List<File> filesToBeDeleted = new ArrayList<File>();
            //float cellHeight = getCellHeight(numberofRowsPerPageOfLabel, pageSizeId);
            float cellHeight = paper.getCellHeight();

            for (StudyTrialInstanceInfo trialInstance : trialInstances) {
                FieldMapTrialInstanceInfo fieldMapTrialInstanceInfo = trialInstance.getTrialInstance();

                Map<String, String> moreFieldInfo = new HashMap<String, String>();
                moreFieldInfo.put("locationName", fieldMapTrialInstanceInfo.getLocationName());
                moreFieldInfo.put("blockName", fieldMapTrialInstanceInfo.getBlockName());
                moreFieldInfo.put("selectedName", trialInstance.getFieldbookName());
                moreFieldInfo.put("trialInstanceNumber", fieldMapTrialInstanceInfo.getTrialInstanceNo());

                for (FieldMapLabel fieldMapLabel : fieldMapTrialInstanceInfo.getFieldMapLabels()) {

                    i++;
                    String barcodeLabel = generateBarcodeField(moreFieldInfo, fieldMapLabel, firstBarcodeField,
                            secondBarcodeField, thirdBarcodeField, barcodeNeeded);
                    if ("0".equalsIgnoreCase(barcodeNeeded)) {
                        barcodeLabel = " ";
                    }

                    BitMatrix bitMatrix = new Code128Writer().encode(barcodeLabel, BarcodeFormat.CODE_128,
                            width, height, null);
                    String imageLocation = System.getProperty("user.home") + "/" + Math.random() + ".png";
                    File imageFile = new File(imageLocation);
                    FileOutputStream fout = new FileOutputStream(imageFile);
                    MatrixToImageWriter.writeToStream(bitMatrix, "png", fout);
                    filesToBeDeleted.add(imageFile);

                    Image mainImage = Image.getInstance(imageLocation);

                    PdfPCell cell = new PdfPCell();
                    cell.setFixedHeight(cellHeight);
                    cell.setNoWrap(false);
                    cell.setPadding(5f);
                    cell.setPaddingBottom(1f);

                    PdfPTable innerImageTableInfo = new PdfPTable(1);
                    innerImageTableInfo.setWidths(new float[] { 1 });
                    innerImageTableInfo.setWidthPercentage(82);
                    PdfPCell cellImage = new PdfPCell();
                    if ("1".equalsIgnoreCase(barcodeNeeded)) {
                        cellImage.addElement(mainImage);
                    } else {
                        cellImage.addElement(new Paragraph(" "));
                    }
                    cellImage.setBorder(Rectangle.NO_BORDER);
                    cellImage.setBackgroundColor(Color.white);
                    cellImage.setPadding(1.5f);

                    innerImageTableInfo.addCell(cellImage);

                    //float fontSize = 6.8f;
                    float fontSize = paper.getFontSize();
                    //if (numberofRowsPerPageOfLabel == 10)
                    //    fontSize = 4.8f;

                    Font fontNormal = FontFactory.getFont("Arial", fontSize, Font.NORMAL);

                    // cell.addElement(mainImage);
                    cell.addElement(innerImageTableInfo);

                    cell.addElement(new Paragraph());
                    for (int row = 0; row < 5; row++) {
                        if (row == 0) {
                            PdfPTable innerDataTableInfo = new PdfPTable(1);
                            innerDataTableInfo.setWidths(new float[] { 1 });
                            innerDataTableInfo.setWidthPercentage(85);

                            Font fontNormalData = FontFactory.getFont("Arial", 5.0f, Font.NORMAL);
                            PdfPCell cellInnerData = new PdfPCell(new Phrase(barcodeLabel, fontNormalData));

                            cellInnerData.setBorder(Rectangle.NO_BORDER);
                            cellInnerData.setBackgroundColor(Color.white);
                            cellInnerData.setPaddingBottom(0.2f);
                            cellInnerData.setPaddingTop(0.2f);
                            cellInnerData.setHorizontalAlignment(Element.ALIGN_MIDDLE);

                            innerDataTableInfo.addCell(cellInnerData);
                            innerDataTableInfo.setHorizontalAlignment(Element.ALIGN_MIDDLE);
                            cell.addElement(innerDataTableInfo);
                        }
                        PdfPTable innerTableInfo = new PdfPTable(2);
                        innerTableInfo.setWidths(new float[] { 1, 1 });
                        innerTableInfo.setWidthPercentage(85);

                        String leftText = generateBarcodeLabel(moreFieldInfo, fieldMapLabel, leftSelectedFields,
                                row);
                        PdfPCell cellInnerLeft = new PdfPCell(new Paragraph(leftText, fontNormal));

                        cellInnerLeft.setBorder(Rectangle.NO_BORDER);
                        cellInnerLeft.setBackgroundColor(Color.white);
                        cellInnerLeft.setPaddingBottom(0.5f);
                        cellInnerLeft.setPaddingTop(0.5f);

                        innerTableInfo.addCell(cellInnerLeft);

                        String rightText = generateBarcodeLabel(moreFieldInfo, fieldMapLabel,
                                rightSelectedFields, row);
                        PdfPCell cellInnerRight = new PdfPCell(new Paragraph(rightText, fontNormal));

                        cellInnerRight.setBorder(Rectangle.NO_BORDER);
                        cellInnerRight.setBackgroundColor(Color.white);
                        cellInnerRight.setPaddingBottom(0.5f);
                        cellInnerRight.setPaddingTop(0.5f);

                        innerTableInfo.addCell(cellInnerRight);

                        cell.addElement(innerTableInfo);
                    }

                    cell.setBorder(Rectangle.NO_BORDER);
                    cell.setBackgroundColor(Color.white);

                    //cell.setBorderColor(Color.BLUE);

                    table.addCell(cell);

                    if (i % numberOfLabelPerRow == 0) {
                        // we go the next line

                        int needed = fixTableRowSize - numberOfLabelPerRow;

                        for (int neededCount = 0; neededCount < needed; neededCount++) {
                            PdfPCell cellNeeded = new PdfPCell();

                            cellNeeded.setBorder(Rectangle.NO_BORDER);
                            cellNeeded.setBackgroundColor(Color.white);

                            table.addCell(cellNeeded);
                        }

                        table.completeRow();
                        if (numberofRowsPerPageOfLabel == 10) {

                            //table.setSpacingAfter(9f);
                            table.setSpacingAfter(paper.getSpacingAfter());
                        }

                        document.add(table);

                        table = new PdfPTable(fixTableRowSize);
                        table.setWidths(widthColumns);
                        table.setWidthPercentage(100);

                    }
                    if (i % totalPerPage == 0) {
                        // we go the next page
                        document.newPage();
                    }
                    fout.flush();
                    fout.close();

                }
            }
            // we need to add the last row
            if (i % numberOfLabelPerRow != 0) {
                // we go the next line

                int needed = fixTableRowSize - numberOfLabelPerRow;
                int remaining = numberOfLabelPerRow - (i % numberOfLabelPerRow);
                for (int neededCount = 0; neededCount < remaining; neededCount++) {
                    PdfPCell cellNeeded = new PdfPCell();

                    cellNeeded.setBorder(Rectangle.NO_BORDER);
                    cellNeeded.setBackgroundColor(Color.white);

                    table.addCell(cellNeeded);
                }

                table.completeRow();
                if (numberofRowsPerPageOfLabel == 10) {

                    table.setSpacingAfter(paper.getSpacingAfter());
                }

                document.add(table);

                table = new PdfPTable(fixTableRowSize);
                table.setWidths(widthColumns);
                table.setWidthPercentage(100);

            }

            document.close();
            for (File file : filesToBeDeleted) {
                file.delete();
            }
            fileOutputStream.close();

        } catch (FileNotFoundException e) {
            LOG.error(e.getMessage(), e);
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }

    } catch (WriterException e) {
        LOG.error(e.getMessage(), e);
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
    }
    return fileName;
}

From source file:com.gp.cong.logisoft.reports.BookingCoverSheetPdfCreater.java

public void createBody(SearchBookingReportDTO searchBookingReportDTO, String simpleRequest,
        MessageResources messageResources, String printFromBl, String documentName)
        throws DocumentException, MalformedURLException, IOException, Exception {
    NumberFormat numformat = new DecimalFormat("##,###,##0.00");
    PdfPCell cell = new PdfPCell();
    Paragraph paragraph;//from   w w  w .jav  a2  s .  c o  m
    PdfPTable table;
    Phrase phrase;

    PdfPTable mainTable = makeTable(2);
    mainTable.setWidthPercentage(100);

    BookingFcl bookingFcl = searchBookingReportDTO.getBookingflFcl();
    FclBl fclBl = null;
    if (CommonUtils.isNotEmpty(printFromBl)) {
        fclBl = new FclBlDAO().getFileNoObject(bookingFcl.getFileNo());
    }
    String company = null;
    String contactName = "";
    String email = null;
    String phone = null;
    String fax = null;
    String address = null;
    QuotationDAO quotationDAO = new QuotationDAO();
    CustAddressBC custAddressBC = new CustAddressBC();
    Quotation quotation = quotationDAO.getFileNoObject(bookingFcl.getFileNo());
    if (null != quotation) {
        contactName = quotation.getContactname();
    }
    if (bookingFcl.getShippercheck() != null && bookingFcl.getShippercheck().equals("on")) {
        //from=bookingFcl.getShipper();
        company = bookingFcl.getShipper();
        email = bookingFcl.getShipperEmail();
        phone = bookingFcl.getShipperPhone();
        fax = bookingFcl.getShipperFax();
        address = bookingFcl.getAddressforShipper();
    } else if (bookingFcl.getForwardercheck() != null && bookingFcl.getForwardercheck().equals("on")) {
        company = bookingFcl.getForward();
        email = bookingFcl.getForwarderEmail();
        phone = bookingFcl.getForwarderPhone();
        fax = bookingFcl.getForwarderFax();
        address = bookingFcl.getAddressforForwarder();
    } else if (bookingFcl.getConsigneecheck() != null && bookingFcl.getConsigneecheck().equals("on")) {
        company = bookingFcl.getConsignee();
        email = bookingFcl.getConsingeeEmail();
        phone = bookingFcl.getConsingeePhone();
        fax = bookingFcl.getConsigneeFax();
        address = bookingFcl.getAddressforConsingee();
    } else {
        if (null != quotation) {
            company = quotation.getClientname();
            email = quotation.getEmail1();
            phone = quotation.getPhone();
            fax = quotation.getFax();
            CustAddress custAddress = custAddressBC.getClientAddress(quotation.getClientnumber());
            if (null != custAddress) {
                address = custAddress.getAddress1();
            }
        }
    }

    PdfPTable headerTable = makeTable(3);
    headerTable.setWidths(new float[] { 20, 50, 30 });
    headerTable.setWidthPercentage(100);

    PdfPTable headerTable1 = makeTable(1);
    headerTable1.setWidths(new float[] { 100 });
    headerTable1.setWidthPercentage(100);

    PdfPCell headingCell1 = makeCell(
            new Phrase(messageResources.getMessage("fileNumberPrefix") + String.valueOf(bookingFcl.getFileNo()),
                    headingFont1),
            Element.ALIGN_CENTER);
    headingCell1.setBackgroundColor(Color.LIGHT_GRAY);
    headingCell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
    headerTable1.addCell(headingCell1);
    cell = makeCellleftNoBorder("");
    cell.addElement(headerTable1);
    headerTable.addCell(headerTable1);

    PdfPTable headerTable2 = makeTable(2);
    headerTable2.setWidths(new float[] { 38, 62 });
    headerTable2.setWidthPercentage(100);

    SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy HH:mm a");
    SimpleDateFormat sdfForddMMyyyy = new SimpleDateFormat("dd-MMM-yyyy");
    String colon = ": ";
    String docCut = "";
    String carrierDocCut = "";
    String etd = "";
    String eta = "";
    if (bookingFcl.getDocCutOff() != null) {
        docCut = sdf.format(bookingFcl.getDocCutOff());
    }
    if (bookingFcl.getCarrierDocCut() != null) {
        carrierDocCut = sdf.format(bookingFcl.getCarrierDocCut());
    }
    if (bookingFcl.getEtd() != null) {
        etd = sdfForddMMyyyy.format(bookingFcl.getEtd());
    }
    if (bookingFcl.getEta() != null) {
        eta = sdfForddMMyyyy.format(bookingFcl.getEta());
    }

    headerTable2.addCell(makeCell(new Phrase("Doc Cutoff", headingFont2), Element.ALIGN_LEFT));
    headerTable2.addCell(makeCell(new Phrase(colon + docCut, redBoldFont), Element.ALIGN_LEFT));
    headerTable2.addCell(makeCell(new Phrase("Carrier Doc Cut", headingFont2), Element.ALIGN_LEFT));
    headerTable2.addCell(makeCell(new Phrase(colon + carrierDocCut, redBoldFont), Element.ALIGN_LEFT));

    cell = makeCellleftNoBorder("");
    cell.addElement(headerTable2);
    headerTable.addCell(headerTable2);

    PdfPTable headerTable3 = makeTable(2);
    headerTable3.setWidths(new float[] { 20, 80 });
    headerTable3.setWidthPercentage(100);

    headerTable3.addCell(makeCell(new Phrase("ETD", headingFont2), Element.ALIGN_LEFT));
    headerTable3.addCell(makeCell(new Phrase(colon + etd, headingFont2), Element.ALIGN_LEFT));
    headerTable3.addCell(makeCell(new Phrase("ETA", headingFont2), Element.ALIGN_LEFT));
    headerTable3.addCell(makeCell(new Phrase(colon + eta, headingFont2), Element.ALIGN_LEFT));

    cell = makeCellleftNoBorder("");
    cell.addElement(headerTable3);
    headerTable.addCell(headerTable3);

    document.add(headerTable);

    PdfPTable pTable = new PdfPTable(2);
    pTable.setWidthPercentage(100);

    PdfPTable clientTable = makeTable(2);
    clientTable.setWidths(new float[] { 27, 73 });
    clientTable.setWidthPercentage(100);

    clientTable.addCell(makeCellleftNoBorderWithBoldFont("Client Name"));
    clientTable.addCell(makeCellLeftNoBorderValue(company));
    clientTable.addCell(makeCellleftNoBorderWithBoldFont("Client Address"));
    clientTable.addCell(makeCellLeftNoBorderValue(address));
    clientTable.addCell(makeCellleftNoBorderWithBoldFont("Contact Name"));
    clientTable.addCell(makeCellLeftNoBorderValue(contactName));
    cell = makeCellleftNoBorderWithBoldFont("Contact Number");
    cell.setNoWrap(true);
    clientTable.addCell(cell);
    clientTable.addCell(makeCellLeftNoBorderValue(phone));
    clientTable.addCell(makeCellleftNoBorderWithBoldFont("Contact Fax"));
    clientTable.addCell(makeCellLeftNoBorderValue(fax));
    clientTable.addCell(makeCellleftNoBorderWithBoldFont("Contact Email"));
    clientTable.addCell(makeCellLeftNoBorderValue(email));

    cell = makeCellleftNoBorder("");
    cell.setBorderWidthRight(0.6f);
    cell.setBorderWidthBottom(0.6f);
    cell.setBorderWidthLeft(0.6f);
    cell.setBorderWidthTop(0.6f);
    cell.addElement(clientTable);
    pTable.addCell(cell);

    PdfPTable carrierTable = makeTable(2);
    carrierTable.setWidths(new float[] { 26, 74 });
    carrierTable.setWidthPercentage(100);
    String sslName[] = bookingFcl.getSslname().split("//");

    carrierTable.addCell(makeCellleftNoBorderWithBoldFont("Carrier"));
    carrierTable.addCell(makeCellLeftNoBorderValue(sslName.length > 1 ? sslName[0] : ""));
    carrierTable.addCell(makeCellleftNoBorderWithBoldFont("Vessel"));
    carrierTable.addCell(makeCellLeftNoBorderValue(bookingFcl.getVessel()));
    carrierTable.addCell(makeCellleftNoBorderWithBoldFont("Voyage"));
    carrierTable.addCell(makeCellLeftNoBorderValue(bookingFcl.getVoyageCarrier()));
    carrierTable.addCell(makeCellleftNoBorderWithBoldFont("SSL Booking#"));
    carrierTable.addCell(makeCellLeftNoBorderValue(bookingFcl.getSSBookingNo()));
    carrierTable.addCell(makeCellleftNoBorderWithBoldFont("POO"));
    carrierTable.addCell(makeCellLeftNoBorderValue(getCityStateName(bookingFcl.getOriginTerminal())));
    carrierTable.addCell(makeCellleftNoBorderWithBoldFont("POL"));
    carrierTable.addCell(makeCellLeftNoBorderValue(getCityStateName(bookingFcl.getPortofOrgin())));
    carrierTable.addCell(makeCellleftNoBorderWithBoldFont("POD"));
    carrierTable.addCell(makeCellLeftNoBorderValue(getCityStateName(bookingFcl.getDestination())));
    carrierTable.addCell(makeCellleftNoBorderWithBoldFont("FD"));
    carrierTable.addCell(makeCellLeftNoBorderValue(getCityStateName(bookingFcl.getPortofDischarge())));
    carrierTable.addCell(makeCellleftNoBorderWithBoldFont("Containers"));
    carrierTable.addCell(makeCellLeftNoBorderValue(
            this.getContainers(simpleRequest, searchBookingReportDTO, messageResources).getContent()));
    //        PdfPCell cell1 = makeCell(this.getContainers(simpleRequest, searchBookingReportDTO, messageResources), 1);
    //        cell1.setColspan(2);
    //        cell1.setBorderWidthLeft(0.0F);
    //        carrierTable.addCell(cell1);

    cell = makeCellleftNoBorder("");
    cell.setBorderWidthRight(0.6f);
    cell.setBorderWidthBottom(0.6f);
    cell.setBorderWidthTop(0.6f);
    cell.addElement(carrierTable);

    pTable.addCell(cell);

    document.add(pTable);

    PdfPTable hazardsMainTable = makeTable(1);
    hazardsMainTable.setWidths(new float[] { 100 });
    hazardsMainTable.setWidthPercentage(100);

    PdfPTable hazardsTable = makeTable(3);
    hazardsTable.setWidths(new float[] { 70, 15, 15 });
    hazardsTable.setWidthPercentage(100);

    Image yes = Image.getInstance(searchBookingReportDTO.getContextPath() + "/images/icons/y.png");
    yes.scalePercent(60);
    yes.scaleAbsoluteWidth(18);
    PdfPCell yesCell = new PdfPCell();
    yesCell.setBorder(0);
    yesCell.addElement(new Chunk(yes, 32, -0));

    Image no = Image.getInstance(searchBookingReportDTO.getContextPath() + "/images/icons/n.png");
    no.scalePercent(60);
    no.scaleAbsoluteWidth(18);
    PdfPCell noCell = new PdfPCell();
    noCell.setBorder(0);
    noCell.addElement(new Chunk(no, 32, -0));

    hazardsTable.addCell(makeCellleftNoBorderWithBoldFont("HAZARDOUS"));
    if (bookingFcl.getHazmat() != null && "Y".equalsIgnoreCase(bookingFcl.getHazmat())) {
        hazardsTable.addCell(yesCell);
        hazardsTable.addCell(makeCell(new Phrase("N", fontforYandN), 1));
    } else {
        hazardsTable.addCell(makeCell(new Phrase("Y", fontforYandN), 1));
        hazardsTable.addCell(noCell);
    }
    hazardsTable.addCell(makeCellleftNoBorderWithBoldFont("AES"));
    hazardsTable.addCell(makeCell(new Phrase("Y", fontforYandN), Element.ALIGN_CENTER));
    hazardsTable.addCell(makeCell(new Phrase("N", fontforYandN), Element.ALIGN_CENTER));
    hazardsTable.addCell(makeCellleftNoBorderWithBoldFont("DIRECT CONSIGMENT"));
    if (bookingFcl.getDirectConsignmntCheck() != null
            && "on".equalsIgnoreCase(bookingFcl.getDirectConsignmntCheck())) {
        hazardsTable.addCell(yesCell);
        hazardsTable.addCell(makeCell(new Phrase("N", fontforYandN), 1));
    } else {
        hazardsTable.addCell(makeCell(new Phrase("Y", fontforYandN), 1));
        hazardsTable.addCell(noCell);
    }
    hazardsTable.addCell(makeCellleftNoBorderWithBoldFont("AFR"));
    hazardsTable.addCell(makeCell(new Phrase("Y", fontforYandN), Element.ALIGN_CENTER));
    hazardsTable.addCell(makeCell(new Phrase("N", fontforYandN), Element.ALIGN_CENTER));

    cell = makeCellleftNoBorder("");
    cell.setBorderWidthRight(0.6f);
    cell.setBorderWidthBottom(0.6f);
    cell.setBorderWidthLeft(0.6f);
    cell.addElement(hazardsTable);

    hazardsMainTable.addCell(cell);
    document.add(hazardsMainTable);

    PdfPTable docsMainTable = makeTable(2);
    docsMainTable.setWidths(new float[] { 30, 70 });
    docsMainTable.setWidthPercentage(100);

    PdfPTable docsTable = makeTable(2);
    docsTable.setWidths(new float[] { 50, 50 });
    docsTable.setWidthPercentage(100);

    Image img = Image.getInstance(searchBookingReportDTO.getContextPath() + "/images/icons/uncheckedBox.png");
    img.scalePercent(50);
    img.scaleAbsoluteWidth(18);
    PdfPCell pCell = new PdfPCell();
    pCell.setBorder(0);
    pCell.addElement(new Chunk(img, 25, -0));

    //        Image checkedimg = Image.getInstance(searchBookingReportDTO.getContextPath() + "/images/icons/check.png");
    //        checkedimg.scalePercent(60);
    //        checkedimg.scaleAbsoluteWidth(18);
    //        PdfPCell checkedCell = new PdfPCell();
    //        checkedCell.setBorder(0);
    //        checkedCell.addElement(new Chunk(checkedimg, 25, -0));
    docsTable.addCell(makeCellleftNoBorderWithBoldFont("Docs"));
    docsTable.addCell(pCell);

    docsTable.addCell(makeCellNoBorders("       "));
    docsTable.addCell(makeCellNoBorders("       "));

    docsTable.addCell(makeCellleftNoBorderWithBoldFont("COB"));
    docsTable.addCell(pCell);

    docsTable.addCell(makeCellNoBorders("       "));
    docsTable.addCell(makeCellNoBorders("       "));

    docsTable.addCell(makeCellleftNoBorderWithBoldFont("MBL"));
    docsTable.addCell(pCell);

    docsTable.addCell(makeCellNoBorders("       "));
    docsTable.addCell(makeCellNoBorders("       "));

    docsTable.addCell(makeCellleftNoBorderWithBoldFont("Manifisted"));
    docsTable.addCell(pCell);

    cell = makeCellleftNoBorder("");
    cell.setBorderWidthBottom(0.6f);
    cell.setBorderWidthLeft(0.6f);
    cell.addElement(docsTable);
    docsMainTable.addCell(cell);

    PdfPTable noteTable = makeTable(1);
    noteTable.setWidths(new float[] { 100 });
    noteTable.setWidthPercentage(100);
    noteTable.addCell(makeCellCenterNoBorder("Notes"));
    noteTable.addCell(makeCellNoBorders("       "));
    noteTable.addCell(makeCellleftwithUnderLine("            "));
    noteTable.addCell(makeCellNoBorders("       "));
    noteTable.addCell(makeCellleftwithUnderLine("            "));
    noteTable.addCell(makeCellNoBorders("       "));
    noteTable.addCell(makeCellleftwithUnderLine("            "));
    noteTable.addCell(makeCellNoBorders("       "));
    noteTable.addCell(makeCellleftwithUnderLine("            "));
    noteTable.addCell(makeCellNoBorders("       "));

    cell = makeCellleftNoBorder("");
    cell.setBorderWidthBottom(0.6f);
    cell.setBorderWidthRight(0.6f);
    cell.addElement(noteTable);
    docsMainTable.addCell(cell);
    document.add(docsMainTable);

}

From source file:com.jk.framework.desktop.swing.dao.TableModelPdfBuilder.java

License:Apache License

/**
 * Load data table./* ww  w  . j a  v a2s . c o m*/
 *
 * @param pdfPTable
 *            the pdf P table
 * @param font
 *            the font
 * @throws DocumentException
 *             the document exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public void loadDataTable(final PdfPTable pdfPTable, Font font) throws DocumentException, IOException {
    font = getFont();
    for (int row = 0; row < this.model.getRowCount(); row++) {
        for (int column = 0; column < this.model.getColumnCount(); column++) {
            if (this.model.isVisible(column)) {
                final PdfPCell cell = new PdfPCell(
                        new Phrase((String) this.model.getValueAt(row, column), font));
                cell.setNoWrap(true);
                cell.setRunDirection(getRunDirection());
                // TODO : make the alignment according to the colunm
                // datatype
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                pdfPTable.addCell(cell);
            }
        }
    }
}

From source file:it.eng.spagobi.engines.documentcomposition.exporterUtils.PdfCreator.java

License:Mozilla Public License

public FileOutputStream createPdfFile(FileOutputStream fileOutputStream,
        Map<String, DocumentContainer> documentsMap, boolean defaultStyle)
        throws MalformedURLException, IOException, DocumentException {

    logger.debug("IN");

    Document document = new Document(PageSize.A4.rotate());
    Rectangle rect = document.getPageSize();
    docWidth = rect.getWidth();//from   w  w  w  .  j av a2 s .  c  o  m
    docHeight = rect.getHeight();

    logger.debug("document size width: " + docWidth + " height: " + docHeight);

    //PdfWriter writer=PdfWriter.getInstance(document,new FileOutputStream("C:/comp/SpagoBIProva.pdf"));
    PdfWriter writer = PdfWriter.getInstance(document, fileOutputStream);
    document.open();

    int documentsNumber = documentsMap.keySet().size();
    int columnnsNumber = 2;

    if (defaultStyle == true) {
        logger.debug("use default style");
        int cellsCounter = 0;

        PdfPTable table = new PdfPTable(columnnsNumber);
        table.setWidthPercentage(100);

        for (Iterator iterator = documentsMap.keySet().iterator(); iterator.hasNext();) {
            String label = (String) iterator.next();
            DocumentContainer docContainer = documentsMap.get(label);
            byte[] content = docContainer.getContent();
            if (content != null) {
                Image img = null;
                try {
                    img = Image.getInstance(content);
                    table.addCell(img);
                } catch (Exception e) {
                    logger.debug("Trying to evaluate response as a PDF file... ");
                    table.addCell("");
                    //                  try {
                    //                     PdfReader reader = new PdfReader(content);
                    //                     PdfImportedPage page = writer.getImportedPage(reader, 1);
                    //                     writer.addPage(page);
                    //                     table.addCell("");
                    //                  } catch (Exception x) {
                    //                     logger.error("Error in inserting image for document " + label, e);
                    //                     logger.error("Error in inserting pdf file for document " + label, x);
                    //                     table.addCell("");
                    //                  }
                }
            }
            cellsCounter++;
        }

        // if cell counter is not pair make it pair
        if (cellsCounter % 2 != 0) {
            table.addCell("");
        }
        document.add(table);

    } else { // ************* NO DEFAULT STYLE *****************
        logger.debug("No default style");

        // I want to calculate total height of scaled heights!!
        //int totalScaledHeight=calculateTotaleScaledHeights(documentsMap, defaultStyle);

        // run on all documents
        for (Iterator iterator = documentsMap.keySet().iterator(); iterator.hasNext();) {
            String label = (String) iterator.next();
            logger.debug("document with label " + label);

            DocumentContainer docContainer = documentsMap.get(label);
            MetadataStyle style = docContainer.getStyle();

            // one table for each image, set at absolute position
            PdfPTable table = new PdfPTable(1);

            // width and height specified for the container by style attribute
            int widthStyle = style.getWidth();
            int heightStyle = style.getHeight();
            logger.debug("style for document width: " + widthStyle + " height: " + heightStyle);

            // width and height for the table scaled to the document size
            int tableWidth = calculatePxSize(docWidth, widthStyle, videoWidth);
            int tableHeight = calculatePxSize(docHeight, heightStyle, videoHeight);

            logger.debug("table for document width: " + tableWidth + " height: " + tableHeight);

            // x and y position as specified for the container by the style attribute
            int yStyle = style.getY();
            int xStyle = style.getX();
            // width and height scaled to the document size
            int xPos = (calculatePxPos(docWidth, xStyle, videoWidth));
            int yPos = (int) docHeight - (calculatePxPos(docHeight, yStyle, videoHeight));
            logger.debug("Table position at x: " + xPos + " y: " + yPos);

            // get the image
            byte[] content = docContainer.getContent();
            if (content != null) {
                Image img = null;
                try {
                    img = Image.getInstance(content);
                } catch (Exception e) {
                    logger.debug("Trying to evaluate response as a PDF file... ");
                    try {
                        PdfReader reader = new PdfReader(content);
                        PdfContentByte cb = writer.getDirectContent();
                        PdfImportedPage page = writer.getImportedPage(reader, 1);
                        float[] tm = getTransformationMatrix(page, xPos, yPos, tableWidth, tableHeight);
                        cb.addTemplate(page, tm[0], tm[1], tm[2], tm[3], tm[4], tm[5]);
                    } catch (Exception x) {
                        logger.error("Error in inserting image for document " + label, e);
                        logger.error("Error in inserting pdf file for document " + label, x);
                    }
                    continue;
                }

                //if it is a REPORT and has more than one page, too large, you have to resize the image, but how to understand it?
                // if image size is more than double of the container size cut the first part,otherwise scale it
                if (docContainer.getDocumentType().equals("REPORT")) {
                    boolean cutImageWIdth = isToCutWidth(img, tableWidth);
                    boolean cutImageHeight = isToCutHeight(img, tableWidth);

                    if (cutImageWIdth == true || cutImageHeight == true) {
                        logger.debug(
                                "Report will be cut to width " + tableWidth + " and height " + tableHeight);
                        try {
                            img = cutImage(content, cutImageHeight, cutImageWIdth, tableHeight, tableWidth,
                                    (int) img.getWidth(), (int) img.getHeight());
                        } catch (Exception e) {
                            logger.error(
                                    "Error in image cut, cutt will be ignored and image will be drawn anyway ",
                                    e);
                        }
                    }
                }

                // this is percentage to resize
                // The image must be size within the cell               
                int percToResize = percentageToResize((int) img.getWidth(), (int) img.getHeight(), tableWidth,
                        tableHeight);
                logger.debug("image will be scaled of percentage " + percToResize);
                img.scalePercent(percToResize);

                PdfPCell cell = new PdfPCell(img);
                cell.setNoWrap(true);
                cell.setFixedHeight(tableHeight);
                cell.setBorderWidth(0);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setVerticalAlignment(Element.ALIGN_CENTER);
                table.addCell(cell);

                //table.setWidthPercentage(tableWidthPerc);
                table.setTotalWidth(tableWidth);
                table.setLockedWidth(true);
            } else {
                // TODO: setALT!
            }
            logger.debug("Add table");
            table.writeSelectedRows(0, -1, xPos, yPos, writer.getDirectContent());
            logger.debug("Document added");
        }

    }
    document.close();
    logger.debug("OUT");
    return fileOutputStream;
}