Example usage for com.itextpdf.text.pdf PdfPCell setBackgroundColor

List of usage examples for com.itextpdf.text.pdf PdfPCell setBackgroundColor

Introduction

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

Prototype


public void setBackgroundColor(final BaseColor backgroundColor) 

Source Link

Document

Sets the backgroundcolor of the rectangle.

Usage

From source file:de.alpharogroup.swing.img.ImageExtensions.java

License:Open Source License

/**
 * Factory method for create a new {@link PdfPTable} with the given count of columns and the
 * column header names/*from w w w . j a  va2  s  .c om*/
 *
 * @param numColumns
 *            the count of columns of the table
 * @param headerNames
 *            the column header names
 * @return the new {@link PdfPTable}
 */
public static PdfPTable newPdfPTable(int numColumns, List<String> headerNames) {
    PdfPTable table = new PdfPTable(numColumns);
    headerNames.stream().forEach(columnHeaderName -> {
        PdfPCell header = new PdfPCell();
        header.setBackgroundColor(BaseColor.LIGHT_GRAY);
        header.setBorderWidth(2);
        header.setPhrase(new Phrase(columnHeaderName));
        table.addCell(header);
    });
    return table;
}

From source file:de.domjos.schooltools.core.utils.fileUtils.PDFBuilder.java

License:Open Source License

public void addTable(List<String> headers, float[] headerWidth, List<List<Map.Entry<String, BaseColor>>> cells)
        throws Exception {
    PdfPTable table = new PdfPTable(headers.size());
    if (headerWidth != null) {
        table.setWidths(headerWidth);/*from   w  w  w .  java2s .  c o  m*/
    }

    for (String header : headers) {
        PdfPCell cell = new PdfPCell(
                new Phrase(header, new Font(Font.FontFamily.HELVETICA, 18, Font.BOLDITALIC)));
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
        table.addCell(cell);
    }

    for (List<Map.Entry<String, BaseColor>> row : cells) {
        for (Map.Entry<String, BaseColor> cellItem : row) {
            PdfPCell cell = new PdfPCell(
                    new Phrase(cellItem.getKey(), new Font(Font.FontFamily.HELVETICA, 14, Font.NORMAL)));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setBackgroundColor(cellItem.getValue());
            table.addCell(cell);
        }
    }

    this.document.add(table);
}

From source file:de.jost_net.JVerein.io.Reporter.java

License:Open Source License

/**
 * Erzeugt eine Zelle der Tabelle./*from  w w  w .j a  v a2 s .c  om*/
 * 
 * @param text
 *          der anzuzeigende Text.
 * @param align
 *          die Ausrichtung.
 * @param backgroundcolor
 *          die Hintergundfarbe.
 * @return die erzeugte Zelle.
 */
private PdfPCell getDetailCell(String text, int align, BaseColor backgroundcolor, boolean silbentrennung) {
    PdfPCell cell = null;
    if (silbentrennung) {
        cell = new PdfPCell(new Phrase(new Chunk(notNull(text), getFreeSans(8)).setHyphenation(hyph)));
    } else {
        cell = new PdfPCell(new Phrase(new Chunk(notNull(text), getFreeSans(8))));
    }
    cell.setHorizontalAlignment(align);
    cell.setBackgroundColor(backgroundcolor);
    return cell;
}

From source file:de.jost_net.JVerein.io.Reporter.java

License:Open Source License

private PdfPCell getDetailCell(String text, int align, BaseColor backgroundcolor, int colspan) {
    PdfPCell cell = new PdfPCell(new Phrase(new Chunk(notNull(text), getFreeSans(8)).setHyphenation(hyph)));
    cell.setHorizontalAlignment(align);//from   ww w  . ja v a 2  s  . c o  m
    cell.setBackgroundColor(backgroundcolor);
    cell.setColspan(colspan);
    return cell;
}

From source file:Documentos.ReportesPDF.java

public void agregarTabla(Paragraph parrafo) {
    //Anchos de las columnas
    PdfPTable tabla = new PdfPTable(anchosFilas);
    // Porcentaje que ocupa a lo ancho de la pagina del PDF
    tabla.setWidthPercentage(90);/*w  w  w. j  av  a 2s.  c o  m*/
    //Alineacion horizontal centrada
    tabla.setHorizontalAlignment(Element.ALIGN_CENTER);
    //agregar celda que ocupa las  columnas de los rotulos
    PdfPCell cell0 = new PdfPCell(new Paragraph("Repostera AnaIs"));
    cell0.setColspan(anchosFilas.length);
    cell0.setBackgroundColor(new BaseColor(66, 139, 202));
    //Centrar contenido de celda
    cell0.setHorizontalAlignment(Element.ALIGN_CENTER);
    PdfPCell cell = new PdfPCell(new Paragraph(tituloReporte()));
    cell.setColspan(anchosFilas.length);
    cell.setBackgroundColor(new BaseColor(49, 176, 213));
    //Centrar contenido de celda
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    //Color de fondo de la celda     
    tabla.addCell(cell0);
    tabla.addCell(cell);
    // Mostrar los rotulos de las columnas
    for (int i = 0; i < rotulosColumnas.length; i++) {
        cell = new PdfPCell(new Paragraph(rotulosColumnas[i]));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setBackgroundColor(new BaseColor(248, 248, 248));
        tabla.addCell(cell);
    }
    switch (numReport) {
    case 1:
        DataBase.DataBasePDF.pdfVendedores(cell, tabla);
        break;
    case 2:
        DataBase.DataBasePDF.pdfProveedores(cell, tabla);
        break;
    case 3:
        DataBase.DataBasePDF.pdfClientes(cell, tabla);
        break;
    case 4:
        DataBase.DataBasePDF.pdfVentas(cell, tabla);
        break;
    case 5:
        DataBase.DataBasePDF.pdfProductos(cell, tabla);
        break;
    case 6:
        DataBase.DataBasePDF.pdfPedidos(cell, tabla);
        break;
    }

    //Agregar la tabla con los datos al parrafo que nos llego como entrada
    parrafo.add(tabla);
}

From source file:edu.cornell.mannlib.vitro.webapp.visualization.visutils.PDFDocument.java

License:Open Source License

private void setTableFooterStyle(BaseColor footerBackgroundColor, PdfPCell cell) {
    cell.setBorderWidth(0.0f);/*from w ww . ja v a2 s  . c  o m*/
    cell.setBackgroundColor(footerBackgroundColor);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setPaddingTop(5f);
    cell.setPaddingRight(10f);
    cell.setPaddingBottom(5f);
    cell.setPaddingLeft(10f);
}

From source file:edu.cornell.mannlib.vitro.webapp.visualization.visutils.PDFDocument.java

License:Open Source License

private void setTableBodyStyle(BaseColor bodyBackgroundColor, PdfPCell cell) {
    cell.setBorderWidth(0.0f);//from  ww  w.  j  av  a 2s .c  o m
    cell.setBackgroundColor(bodyBackgroundColor);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setPaddingTop(5f);
    cell.setPaddingRight(10f);
    cell.setPaddingBottom(5f);
    cell.setPaddingLeft(10f);
}

From source file:edu.cornell.mannlib.vitro.webapp.visualization.visutils.PDFDocument.java

License:Open Source License

private void setTableHeaderStyle(BaseColor headerBackgroundColor, PdfPCell cell) {
    cell.setBorderWidth(0.0f);/*from   w ww. java  2  s . co  m*/
    cell.setBackgroundColor(headerBackgroundColor);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setPaddingTop(5f);
    cell.setPaddingRight(10f);
    cell.setPaddingBottom(5f);
    cell.setPaddingLeft(10f);
}

From source file:edu.cornell.mannlib.vitro.webapp.visualization.visutils.PDFDocument.java

License:Open Source License

private void setTableCaptionStyle(BaseColor summaryBackgroundColor, PdfPCell cell) {
    cell.setBorderWidth(0.0f);/* ww w. j  a  v a 2 s .co  m*/
    cell.setBackgroundColor(summaryBackgroundColor);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setPaddingTop(5.0f);
    cell.setPaddingRight(10.0f);
    cell.setPaddingBottom(5.0f);
    cell.setPaddingLeft(10.0f);
    cell.setColspan(2);
}

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

License:Open Source License

@SuppressWarnings("hiding")
public static boolean printList(ArrayList<ContainerLabel> containers) throws PrintFailedException {
    log.debug("Invoked printList ");
    boolean result = false;
    ContainerLabel label = new ContainerLabel();
    if (containers.isEmpty()) {
        log.debug("No labels to print.");
    } else {//ww  w  . j  av a2 s  .  c  o  m
        LabelDefinitionType printDefinition = null;
        LabelDefinitionListType printDefs = PreCaptureSingleton.getInstance().getPrintFormatDefinitionList();
        List<LabelDefinitionType> printDefList = printDefs.getLabelDefinition();
        Iterator<LabelDefinitionType> il = printDefList.iterator();
        while (il.hasNext()) {
            LabelDefinitionType def = il.next();
            if (def.getTitle().equals(PreCaptureSingleton.getInstance().getProperties().getProperties()
                    .getProperty(PreCaptureProperties.KEY_SELECTED_PRINT_DEFINITION))) {
                printDefinition = def;
            }
        }
        if (printDefinition == null) {
            log.error("No selected print format defintion found.");
            //TODO change from message to error handling dialog that allows picking a print format.
            JOptionPane.showMessageDialog(null, "Unable to print.  No print format is selected.");
        } else {

            log.debug(printDefinition.getTitle());
            log.debug(printDefinition.getTextOrentation().toString());

            LabelEncoder encoder = new LabelEncoder(containers.get(0));
            try {
                Image image = encoder.getImage();
                Document document = new Document();
                PdfWriter.getInstance(document, new FileOutputStream(PreCaptureSingleton.getInstance()
                        .getProperties().getProperties().getProperty(PreCaptureProperties.KEY_LABELPRINTFILE)));
                // Convert units in print definition to points (72 points/inch, 28.346456 points/cm)

                int paperWidthPoints = 612; // 8.5"
                int paperHeightPoints = 792; // 11"
                int marginsPoints = 36; // 0.5"
                int labelWidthPoints = 540; // 7.5" 
                int labelHeightPoints = 720; // 10"
                int numColumns = 1; // goes with above

                numColumns = printDefinition.getColumns();
                float relWidthTextCell = printDefinition.getRelWidthTextCell();
                float relWidthBarcodeCell = printDefinition.getRelWidthBarcodeCell();
                log.debug("relWidthTextCell = " + relWidthTextCell);
                log.debug("relWidthBarcodeCell = " + relWidthBarcodeCell);

                if (printDefinition.getUnits().toString().toLowerCase().equals("inches")) {
                    paperWidthPoints = (int) Math.floor(printDefinition.getPaperWidth() * 72f);
                    paperHeightPoints = (int) Math.floor(printDefinition.getPaperHeight() * 72f);
                    marginsPoints = (int) Math.floor(printDefinition.getMargins() * 72f);
                    labelWidthPoints = (int) Math.floor(printDefinition.getLabelWidth() * 72f);
                    labelHeightPoints = (int) Math.floor(printDefinition.getLabelHeight() * 72f);
                }
                if (printDefinition.getUnits().toString().toLowerCase().equals("cm")) {
                    paperWidthPoints = (int) Math.floor(printDefinition.getPaperWidth() * 28.346456f);
                    paperHeightPoints = (int) Math.floor(printDefinition.getPaperHeight() * 28.346456f);
                    marginsPoints = (int) Math.floor(printDefinition.getMargins() * 28.346456f);
                    labelWidthPoints = (int) Math.floor(printDefinition.getLabelWidth() * 28.346456f);
                    labelHeightPoints = (int) Math.floor(printDefinition.getLabelHeight() * 28.346456f);
                }
                if (printDefinition.getUnits().toString().toLowerCase().equals("points")) {
                    paperWidthPoints = (int) Math.floor(printDefinition.getPaperWidth() * 1f);
                    paperHeightPoints = (int) Math.floor(printDefinition.getPaperHeight() * 1f);
                    marginsPoints = (int) Math.floor(printDefinition.getMargins() * 1f);
                    labelWidthPoints = (int) Math.floor(printDefinition.getLabelWidth() * 1f);
                    labelHeightPoints = (int) Math.floor(printDefinition.getLabelHeight() * 1f);
                }

                if (paperWidthPoints == 612 && paperHeightPoints == 792) {
                    document.setPageSize(PageSize.LETTER);
                } else {
                    document.setPageSize(new Rectangle(paperWidthPoints, paperHeightPoints));
                }
                document.setMargins(marginsPoints, marginsPoints, marginsPoints, marginsPoints);
                document.open();

                // Sanity check
                if (paperWidthPoints <= 0) {
                    paperWidthPoints = 612;
                }
                if (paperHeightPoints <= 0) {
                    paperHeightPoints = 792;
                }
                if (marginsPoints < 0) {
                    marginsPoints = 0;
                }
                if (labelWidthPoints <= 0) {
                    labelWidthPoints = 540;
                }
                if (labelHeightPoints <= 0) {
                    labelHeightPoints = 720;
                }
                if (paperWidthPoints + (marginsPoints * 2) < labelWidthPoints) {
                    labelWidthPoints = paperWidthPoints + (marginsPoints * 2);
                    log.debug("Adjusting label width to fit printable page width");
                }
                if (paperHeightPoints + (marginsPoints * 2) < labelHeightPoints) {
                    labelHeightPoints = paperHeightPoints + (marginsPoints * 2);
                    log.debug("Adjusting label height to fit printable page height");
                }

                // calculate how many columns will fit on the paper.
                int columns = (int) Math.floor((paperWidthPoints - (marginsPoints * 2)) / labelWidthPoints);
                // if specified column count is smaller, use the specified.
                if (numColumns < columns) {
                    columns = numColumns;
                    log.debug(
                            "Fewer columns specified in definition than will fit on page, using specified column count of "
                                    + numColumns);
                }

                // define two table cells per column, one for text one for barcode.
                int subCellColumnCount = columns * 2;

                // set the table, with an absolute width and relative widths of the cells in the table;
                PdfPTable table = setupTable(paperWidthPoints, marginsPoints, labelWidthPoints, columns,
                        subCellColumnCount, relWidthTextCell, relWidthBarcodeCell);
                // figure out the width of the cells containing the barcodes.
                float ratio = ((float) relWidthBarcodeCell)
                        / (((float) relWidthBarcodeCell) + ((float) relWidthTextCell));
                float barcodeCellWidthPoints = (float) Math.floor(labelWidthPoints * ratio);
                log.debug("Width of barcode cell in points: " + barcodeCellWidthPoints);

                //Rectangle pageSizeRectangle = new Rectangle(paperWidthPoints, paperHeightPoints);
                //table.setWidthPercentage(cellWidthsPoints, pageSizeRectangle);
                //table.setTotalWidth(cellWidthsPoints);

                // Calculate how many cells fit on a page (two cells per label).
                int labelsPerColumn = (int) Math
                        .floor((paperHeightPoints - (marginsPoints * 2)) / labelHeightPoints);
                int cellsPerPage = subCellColumnCount * labelsPerColumn;
                log.debug("Labels per column = " + labelsPerColumn);
                log.debug("Cells per page = " + cellsPerPage);

                Iterator<ContainerLabel> iterLabels = containers.iterator();

                int cellCounter = 0; // counts number of cells filled on a page.
                int counter = 0; // counts number of pre capture label data rows to print (each of which may request more than one copy).

                // TODO: Doesn't fit on page.

                while (iterLabels.hasNext()) {
                    // Loop through all of the container labels found to print 
                    label = iterLabels.next();
                    if (label != null) {
                        log.debug(label);
                        log.debug("Label: " + counter + " " + label.toString());
                        for (int toPrint = 0; toPrint < label.getNumberToPrint(); toPrint++) {
                            // For each container label, loop through the number of requested copies 
                            // Generate a text and a barcode cell for each, and add to array for page
                            int toPrintPlus = toPrint + 1; // for pretty counter in log.
                            log.debug("Copy " + toPrintPlus + " of " + label.getNumberToPrint());

                            PdfPCell cell = label.toPDFCell(printDefinition);
                            cell.setFixedHeight(labelHeightPoints);
                            // Colors to illustrate where the cells are on the layout
                            if (PreCaptureSingleton.getInstance().getProperties().getProperties()
                                    .getProperty(PreCaptureProperties.KEY_DEBUGLABEL).equals("true")) {
                                cell.setBackgroundColor(new BaseColor(255, 255, 30));
                            }

                            PdfPCell cell_barcode = new PdfPCell();
                            cell_barcode.setBorderColor(BaseColor.LIGHT_GRAY);
                            cell_barcode.disableBorderSide(PdfPCell.LEFT);
                            cell_barcode.setVerticalAlignment(PdfPCell.ALIGN_TOP);
                            cell_barcode.setHorizontalAlignment(Element.ALIGN_RIGHT);
                            cell_barcode.setFixedHeight(labelHeightPoints);
                            if (PreCaptureSingleton.getInstance().getProperties().getProperties()
                                    .getProperty(PreCaptureProperties.KEY_DEBUGLABEL).equals("true")) {
                                cell_barcode.setBackgroundColor(new BaseColor(255, 30, 255));
                            }

                            encoder = new LabelEncoder(label);
                            image = encoder.getImage();
                            image.setAlignment(Image.ALIGN_TOP);
                            //image.setAlignment(Image.ALIGN_LEFT);
                            image.setAlignment(Image.ALIGN_RIGHT);
                            image.scaleToFit(barcodeCellWidthPoints, labelHeightPoints);
                            cell_barcode.addElement(image);

                            table.addCell(cell);
                            table.addCell(cell_barcode);

                            cellCounter = cellCounter + 2; // we've added two cells to the page (two cells per label).
                            log.debug("Cells " + cellCounter + " of " + cellsPerPage + " cells per page.");

                            // If we have hit a full set of labels for the page, add them to the document
                            // in each column, filling left to right
                            if (cellCounter >= cellsPerPage - 1) {
                                log.debug("Page is full");
                                log.debug("Table has " + table.getNumberOfColumns() + " columns and "
                                        + table.getRows().size() + " rows ");
                                // Reset to begin next page
                                cellCounter = 0;
                                table.setLockedWidth(true);
                                document.add(table);
                                log.debug("Adding new page");
                                document.newPage();
                                table = setupTable(paperWidthPoints, marginsPoints, labelWidthPoints, columns,
                                        subCellColumnCount, relWidthTextCell, relWidthBarcodeCell);
                                log.debug("Setup new table");
                            }
                        } // end loop through toPrint (for a taxon/precapture label data row)
                        counter++; // Increment number of pre capture label data rows.
                    } // end if not null label
                } // end while results has next (for all taxa requested)
                  // get any remaining cells in pairs
                if (cellCounter > 0) {
                    log.debug("Adding remaining cells in partial page");
                    if (cellCounter <= cellsPerPage) {
                        for (int i = cellCounter; i <= cellsPerPage; i++) {
                            PdfPCell emptyCell = new PdfPCell();
                            emptyCell.setBorder(PdfPCell.NO_BORDER);
                            table.addCell(emptyCell);
                        }
                    }
                    log.debug("Table has " + table.getNumberOfColumns() + " columns and "
                            + table.getRows().size() + " rows ");
                    table.setLockedWidth(true);
                    document.add(table);
                }
                document.close();

                // send to printer
                PrintingUtility.sendPDFToPrinter(printDefinition, paperWidthPoints, paperHeightPoints);

                // Check to see if there was content in the document.
                if (counter == 0) {
                    result = false;
                } else {
                    // Printed to pdf ok.
                    result = true;
                }
            } catch (FileNotFoundException e) {
                log.debug(e.getMessage(), e);
                throw new PrintFailedException("File not found.");
            } catch (DocumentException e) {
                log.error(e.getMessage(), e);
                throw new PrintFailedException("Error building/printing PDF document. " + e.getMessage());
            } catch (OutOfMemoryError e) {
                System.out.println("Out of memory error. " + e.getMessage());
                System.out.println("Failed.  Too many labels.");
                throw new PrintFailedException("Ran out of memory, too many labels at once.");
            } catch (BarcodeCreationException e) {
                System.out.println("BarcodeCreationException. " + e.getMessage());
                System.out.println("Failed.  Couldn't create barcode.");
                throw new PrintFailedException(
                        "Unable to create barcode.  Probably too many characters to encode. " + e.getMessage());
            }
        }
        log.debug("printList Done. Success = " + result);
    }
    return result;
}