Example usage for com.itextpdf.text.pdf PdfPTable setLockedWidth

List of usage examples for com.itextpdf.text.pdf PdfPTable setLockedWidth

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf PdfPTable setLockedWidth.

Prototype

public void setLockedWidth(final boolean lockedWidth) 

Source Link

Document

Uses the value in setTotalWidth() in Document.add().

Usage

From source file:com.wabacus.system.component.application.report.abstractreport.AbsReportType.java

License:Open Source License

protected void showTitleOnPdf() throws Exception {
    PdfPTable tableTitle = new PdfPTable(1);
    tableTitle.setTotalWidth(pdfwidth);/*from  w w  w .  j  a va2  s  . co  m*/
    tableTitle.setLockedWidth(true);//
    int titlefontsize = 0;
    if (this.pdfbean != null)
        titlefontsize = this.pdfbean.getTitlefontsize();
    if (titlefontsize <= 0)
        titlefontsize = 10;
    Font headFont = new Font(PdfAssistant.getInstance().getBfChinese(), titlefontsize, Font.BOLD);
    PdfPCell cell = new PdfPCell(
            new Paragraph(rbean.getTitle(rrequest) + "  " + rbean.getSubtitle(rrequest), headFont));
    cell.setColspan(1);
    cell.setBorder(0);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    tableTitle.addCell(cell);
    document.add(tableTitle);
}

From source file:com.xumpy.itext.services.HeaderFooter.java

@Override
public void onEndPage(PdfWriter writer, Document document) {
    PdfPTable header = new PdfPTable(3);
    try {/*from  w ww .  j  a  v a  2s  .c o  m*/
        header.setWidths(new int[] { 24, 24, 24 });
        header.setTotalWidth(527);
        header.setLockedWidth(true);
        header.getDefaultCell().setFixedHeight(20);
        header.getDefaultCell().setBorder(Rectangle.BOTTOM);
        for (PdfPCell cell : tableHeader) {
            cell.setBorder(Rectangle.NO_BORDER);
            header.addCell(cell);
        }
        header.writeSelectedRows(0, -1, 60, 803, writer.getDirectContent());
    } catch (DocumentException ex) {
        Logger.getLogger(HeaderFooter.class.getName()).log(Level.SEVERE, null, ex);
    }

    PdfPTable footer = new PdfPTable(3);
    try {
        footer.setWidths(new int[] { 24, 24, 24 });
        footer.setTotalWidth(527);
        footer.setLockedWidth(true);
        footer.getDefaultCell().setFixedHeight(20);
        footer.getDefaultCell().setBorder(Rectangle.BOTTOM);
        for (PdfPCell cell : tableFooter) {
            cell.setBorder(Rectangle.NO_BORDER);
            footer.addCell(cell);
        }
        footer.writeSelectedRows(0, -1, 60, 200, writer.getDirectContent());
    } catch (DocumentException ex) {
        Logger.getLogger(HeaderFooter.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:de.beimax.talenttree.PageGeneratorSimple.java

License:Open Source License

/**
 * get celled talent text/*from  w w  w. j a  va2s  .c  o m*/
 * @param key
 * @param talentBoxWidth
 * @param fontSize
 * @return
 * @throws Exception
 */
protected PdfPTable getTalentCell(String key, float talentBoxWidth, float fontSize) throws Exception {
    // get phrase
    Phrase phrase = parseTextProperty(key, fontSize, true);

    // table text
    PdfPTable table = new PdfPTable(1);
    table.setTotalWidth(talentBoxWidth - PDFGenerator.talentBoxStroke * 3);
    table.setLockedWidth(true);
    PdfPCell cell = new PdfPCell(phrase);
    cell.setBorder(0);
    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
    table.addCell(cell);
    table.completeRow();

    return table;
}

From source file:domain.Pdfmaker.java

public void makePdf() {
    Document doc = new Document();
    doc.setPageSize(PageSize.A4);/*  w w w.ja  v  a2 s  .c o m*/
    try {
        PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(test.getTitle() + ".pdf"));
        writer.setPdfVersion(PdfWriter.VERSION_1_7);
        doc.open();
        Font f = new Font(Font.FontFamily.TIMES_ROMAN, 15, Font.BOLD, new BaseColor(0, 0, 0));
        Paragraph title = new Paragraph("TEST TITLE", f);
        title.setAlignment(Element.ALIGN_CENTER);
        doc.addCreator("Arne De Bremme");
        //make table
        PdfPTable table = new PdfPTable(4);
        table.setTotalWidth(550f);
        table.setLockedWidth(true);
        table.setHeaderRows(1);

        Paragraph p = new Paragraph(test.getTitle());
        p.setAlignment(Element.ALIGN_CENTER);
        PdfPCell cell = new PdfPCell(p);
        cell.setGrayFill(0.7f);
        cell.setColspan(4);
        table.addCell(cell);
        table.addCell(test.getClassGroup().getGroupName());
        PdfPCell cell2 = new PdfPCell(new Paragraph(test.getDescription()));
        cell2.setColspan(2);
        cell2.setRowspan(2);
        table.addCell(cell2);
        PdfPCell cell3 = new PdfPCell(new Paragraph("DD " + test.getStartDate().getDay() + "/"
                + test.getStartDate().getMonth() + "/" + test.getStartDate().getYear()));
        cell3.setRowspan(2);
        table.addCell(cell3);
        table.addCell(new Paragraph("Test " + test.getTestId()));
        doc.add(table);
        doc.add(Chunk.NEWLINE);
        for (Exercise e : ex) {
            Paragraph par = new Paragraph();
            par.add("Vraag " + counter);
            par.add(Chunk.TABBING);
            par.add(Chunk.TABBING);
            par.add(Chunk.TABBING);
            par.add(Chunk.TABBING);
            par.add(e.getPunten() + "/");
            doc.add(par);
            doc.add(new Paragraph("Klimatogram " + e.getClimateChart().getLocation() + " " + e.getPunten()));
            Robot r = new Robot();
            Desktop.getDesktop().browse(new URI(
                    "http://climatechart.azurewebsites.net/ClimateChart/ShowExercises?selectedYear=1&continentId="
                            + e.getClimateChart().getCountry().getContinent().getId() + "&countryId="
                            + e.getClimateChart().getCountry().getContinent().getId() + "&climateId="
                            + e.getClimateChart().getId()));
            TimeUnit.SECONDS.sleep(6);
            BufferedImage bi = r.createScreenCapture(
                    new Rectangle(Toolkit.getDefaultToolkit().getScreenSize().width * 7 / 10,
                            Toolkit.getDefaultToolkit().getScreenSize().width * 8 / 14));
            File file = new File("screenCapture" + counter + ".jpg");
            ImageIO.write(bi, "jpg", file);
            Image img = Image.getInstance("screenCapture.jpg");
            img.scaleAbsolute(400, 300);
            doc.add(img);
            doc.add(Chunk.NEWLINE);
            doc.add(new Paragraph(e.getNaam()));
            doc.add(Chunk.NEXTPAGE);
            counter++;

        }

        doc.close();
        File filz = new File(test.getTitle() + ".pdf");
        Desktop.getDesktop().open(filz);
    } catch (Exception e) {

    }
}

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 {/*from w w  w .  j a v  a2  s . co 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;
}

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

License:Open Source License

public static PdfPTable setupTable(int paperWidthPoints, int marginsPoints, int labelWidthPoints, int columns,
        int subCellColumnCount, float relWidthTextCell, float relWidthBarcodeCell) throws DocumentException {
    PdfPTable table = new PdfPTable(subCellColumnCount);
    table.setLockedWidth(true); // force use of totalWidth in points, rather than percentWidth.
    float percentWidth = ((((float) paperWidthPoints) - (2f * ((float) marginsPoints)))
            / ((float) paperWidthPoints)) * 100f;
    //percentWidth = 100f;
    log.debug("Table Width Percent = " + percentWidth);
    table.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
    float[] cellWidthsRatio = new float[subCellColumnCount];
    int cellNumber = 0;
    for (int c = 0; c < columns; c++) {
        cellWidthsRatio[cellNumber] = relWidthTextCell; // width of text cell
        cellNumber++;//from  www .  ja  v a  2s.c  o  m
        if (subCellColumnCount > 1) {
            cellWidthsRatio[cellNumber] = relWidthBarcodeCell; // width of barcode cell
            cellNumber++;
        }
    }
    table.setTotalWidth(paperWidthPoints - 2 * marginsPoints);
    // must set total width before setting relative cell widths.
    table.setWidths(cellWidthsRatio);
    log.debug("Width:" + table.getTotalWidth());
    return table;
}

From source file:es.clinica.veterinaria.albaranes.AlbaranPdf.java

public PdfPTable createTable() throws DocumentException {
    // a table with three columns
    int iva = 0, iva2 = 0;
    DecimalFormat df = new DecimalFormat("0.00");
    PdfPTable table = new PdfPTable(5);
    table.setTotalWidth(new float[] { 55, 150, 200, 70, 70 });
    table.setLockedWidth(true);

    // the cell object
    // we add a cell with colspan 3
    PdfPCell cell = new PdfPCell(new Phrase("CANT."));
    cell.setColspan(1);/* www . j  av  a 2s. c  o  m*/
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
    cell.setPaddingTop(5);
    cell.setPaddingBottom(5);
    table.addCell(cell);

    cell = new PdfPCell(new Phrase("CONCEPTO"));
    cell.setColspan(1);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
    cell.setPaddingTop(5);
    cell.setPaddingBottom(5);
    table.addCell(cell);

    cell = new PdfPCell(new Phrase("DESCRIPCIN"));
    cell.setColspan(1);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
    cell.setPaddingTop(5);
    cell.setPaddingBottom(5);
    table.addCell(cell);

    cell = new PdfPCell(new Phrase("PRECIO"));
    cell.setColspan(1);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
    cell.setPaddingTop(5);
    cell.setPaddingBottom(5);
    table.addCell(cell);

    cell = new PdfPCell(new Phrase("IMPORTE"));
    cell.setColspan(1);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
    cell.setPaddingTop(5);
    cell.setPaddingBottom(5);
    table.addCell(cell);

    HashSet<VentaLinea> listVenta = getVenta().getVenta_lineas();

    for (VentaLinea vlinea : listVenta) {
        if (vlinea.getTipo() == 1) {
            if (vlinea.getProducto().getIva() != null) {
                iva2 = vlinea.getProducto().getIva().getValor();
                //                    System.out.println("IVA: " +iva2);
            }
        } else if (vlinea.getTipo() == 2) {
            if (vlinea.getServicio().getIva() != null) {
                iva2 = vlinea.getServicio().getIva().getValor();
                //                    System.out.println("IVA: " +iva2);
            }
        }

        //Para hacer el calculo nos vamos a quedar con el IVA mayor
        if (iva < iva2) {
            iva = iva2;
        }

        cell = new PdfPCell(new Phrase(vlinea.getCantidad() + "", small));
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setPaddingBottom(5);
        table.addCell(cell);

        table.addCell(new PdfPCell(new Phrase(vlinea.getNombre(), small)));

        String descripcion = vlinea.getDescripcion();
        if (descripcion == null || "null".equals(descripcion)) {
            table.addCell(new PdfPCell(new Phrase(" ", small)));
            //                System.out.println("null:" + descripcion);
        } else {
            table.addCell(new PdfPCell(new Phrase(descripcion, small)));
            //                System.out.println("!null:" + descripcion);
        }

        cell = new PdfPCell(new Phrase(df.format(vlinea.getPvp()) + " ", small));
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setPaddingBottom(5);
        table.addCell(cell);

        cell = new PdfPCell(new Phrase(df.format(vlinea.getPreciototalNoIVA()) + " ", small));
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setPaddingBottom(5);
        table.addCell(cell);
    }

    cell = new PdfPCell(new Phrase(" "));
    cell.setColspan(1);
    cell.setBorderWidthBottom(0);
    cell.setBorderWidthLeft(0);
    cell.setBorder(0);
    cell.setBorderColorLeft(BaseColor.WHITE);
    cell.setBorderColorBottom(BaseColor.WHITE);
    cell.setPaddingBottom(5);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);

    cell = new PdfPCell(new Phrase("SUMA"));
    cell.setColspan(1);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
    cell.setPaddingBottom(5);
    table.addCell(cell);

    cell = new PdfPCell(new Phrase(df.format(venta.getCostesinIva()) + " "));
    cell.setColspan(1);
    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
    cell.setPaddingBottom(5);
    table.addCell(cell);

    /* IVA */
    cell = new PdfPCell(new Phrase(" "));
    cell.setColspan(1);
    cell.setBorderWidthBottom(0);
    cell.setBorderWidthLeft(0);
    cell.setBorder(0);
    cell.setBorderColorLeft(BaseColor.WHITE);
    cell.setBorderColorBottom(BaseColor.WHITE);
    cell.setPaddingBottom(5);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);

    //        float costetotal = (float) (venta.getCoste() * (1+(iva*0.01)));

    cell = new PdfPCell(new Phrase("IVA " + iva + "%"));
    cell.setColspan(1);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
    cell.setPaddingBottom(5);
    table.addCell(cell);

    cell = new PdfPCell(new Phrase(df.format(venta.getIvas()) + " "));
    cell.setColspan(1);
    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
    cell.setPaddingBottom(5);
    table.addCell(cell);

    /* COSTE TOTAL */
    cell = new PdfPCell(new Phrase(" "));
    cell.setColspan(1);
    cell.setBorderWidthBottom(0);
    cell.setBorderWidthLeft(0);
    cell.setBorder(0);
    cell.setBorderColorLeft(BaseColor.WHITE);
    cell.setBorderColorBottom(BaseColor.WHITE);
    cell.setPaddingBottom(5);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);

    cell = new PdfPCell(new Phrase("TOTAL"));
    cell.setColspan(1);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
    cell.setPaddingBottom(5);
    table.addCell(cell);

    cell = new PdfPCell(new Phrase(df.format(venta.getCoste()) + " "));
    cell.setColspan(1);
    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
    cell.setPaddingBottom(5);
    table.addCell(cell);

    return table;
}

From source file:es.clinica.veterinaria.facturas.FacturaPdf.java

public PdfPTable createTable() throws DocumentException {
    // a table with three columns
    int iva = 0, iva2 = 0;
    DecimalFormat df = new DecimalFormat("0.00");
    PdfPTable table = new PdfPTable(6);
    table.setTotalWidth(new float[] { 50, 65, 150, 150, 65, 70 });
    table.setLockedWidth(true);

    // the cell object
    // we add a cell with colspan 3
    PdfPCell cell = new PdfPCell(new Phrase("CANT."));
    cell.setColspan(1);//  w ww.  ja v a 2  s  .c o  m
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
    cell.setPaddingTop(5);
    cell.setPaddingBottom(5);
    table.addCell(cell);

    cell = new PdfPCell(new Phrase("FECHA"));
    cell.setColspan(1);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
    cell.setPaddingTop(5);
    cell.setPaddingBottom(5);
    table.addCell(cell);

    cell = new PdfPCell(new Phrase("CONCEPTO"));
    cell.setColspan(1);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
    cell.setPaddingTop(5);
    cell.setPaddingBottom(5);
    table.addCell(cell);

    cell = new PdfPCell(new Phrase("DESCRIPCIN"));
    cell.setColspan(1);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
    cell.setPaddingTop(5);
    cell.setPaddingBottom(5);
    table.addCell(cell);

    cell = new PdfPCell(new Phrase("PRECIO"));
    cell.setColspan(1);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
    cell.setPaddingTop(5);
    cell.setPaddingBottom(5);
    table.addCell(cell);

    cell = new PdfPCell(new Phrase("IMPORTE"));
    cell.setColspan(1);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
    cell.setPaddingTop(5);
    cell.setPaddingBottom(5);
    table.addCell(cell);

    HashSet<Venta> ventas = this.getFactura().getVentas();
    for (Venta venta : ventas) {
        HashSet<VentaLinea> listVenta = venta.getVenta_lineas();

        for (VentaLinea vlinea : listVenta) {
            if (vlinea.getTipo() == 1) {
                if (vlinea.getProducto().getIva() != null) {
                    iva2 = vlinea.getProducto().getIva().getValor();
                    //                    System.out.println("IVA: " +iva2);
                }
            } else if (vlinea.getTipo() == 2) {
                if (vlinea.getServicio().getIva() != null) {
                    iva2 = vlinea.getServicio().getIva().getValor();
                    //                    System.out.println("IVA: " +iva2);
                }
            }

            //Para hacer el calculo nos vamos a quedar con el IVA mayor
            if (iva < iva2) {
                iva = iva2;
            }

            cell = new PdfPCell(new Phrase(vlinea.getCantidad() + "", small));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setPaddingBottom(5);
            table.addCell(cell);

            cell = new PdfPCell(
                    new Phrase(new SimpleDateFormat("dd-MM-yyyy").format(vlinea.getFecha()), small));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setPaddingBottom(5);
            table.addCell(cell);

            if (vlinea.getTipo() == 2) { //Servicio
                table.addCell(new PdfPCell(new Phrase(vlinea.getNombre(), small)));

                String descripcion = vlinea.getDescripcion();
                if (descripcion == null || "null".equals(descripcion)) {
                    table.addCell(new PdfPCell(new Phrase(" ", small)));
                    //                System.out.println("null:" + descripcion);
                } else {
                    table.addCell(new PdfPCell(new Phrase(descripcion, small)));
                    //                System.out.println("!null:" + descripcion);
                }
            } else if (vlinea.getTipo() == 1) { //Producto
                //Si el producto es Tratamiento
                if (vlinea.getProducto().getFamilia().isTratamiento()) {
                    table.addCell(new PdfPCell(new Phrase("Tratamiento", small)));
                    table.addCell(new PdfPCell(new Phrase("", small)));
                } else {

                    table.addCell(new PdfPCell(new Phrase(vlinea.getNombre(), small)));

                    String descripcion = vlinea.getDescripcion();
                    if (descripcion == null || "null".equals(descripcion)) {
                        table.addCell(new PdfPCell(new Phrase(" ", small)));
                        //                System.out.println("null:" + descripcion);
                    } else {
                        table.addCell(new PdfPCell(new Phrase(descripcion, small)));
                        //                System.out.println("!null:" + descripcion);
                    }
                }
            }
            cell = new PdfPCell(new Phrase(df.format(vlinea.getPvp()) + " ", small));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setPaddingBottom(5);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(df.format(vlinea.getPreciototalNoIVA()) + " ", small));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setPaddingBottom(5);
            table.addCell(cell);
        }
    }

    cell = new PdfPCell(new Phrase(" "));
    cell.setColspan(1);
    cell.setBorderWidthBottom(0);
    cell.setBorderWidthLeft(0);
    cell.setBorder(0);
    cell.setBorderColorLeft(BaseColor.WHITE);
    cell.setBorderColorBottom(BaseColor.WHITE);
    cell.setPaddingBottom(5);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);

    cell = new PdfPCell(new Phrase("SUMA"));
    cell.setColspan(1);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
    cell.setPaddingBottom(5);
    table.addCell(cell);

    cell = new PdfPCell(new Phrase(df.format(factura.getCoste()) + " ", smallBold));
    cell.setColspan(1);
    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
    cell.setPaddingBottom(5);
    table.addCell(cell);

    /* IVA */
    cell = new PdfPCell(new Phrase(" "));
    cell.setColspan(1);
    cell.setBorderWidthBottom(0);
    cell.setBorderWidthLeft(0);
    cell.setBorder(0);
    cell.setBorderColorLeft(BaseColor.WHITE);
    cell.setBorderColorBottom(BaseColor.WHITE);
    cell.setPaddingBottom(5);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);

    float costetotal = (float) (factura.getCostetotal());

    cell = new PdfPCell(new Phrase("IVA " + iva + "%"));
    cell.setColspan(1);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
    cell.setPaddingBottom(5);
    table.addCell(cell);

    cell = new PdfPCell(new Phrase(df.format(factura.getIvas()) + " ", smallBold));
    cell.setColspan(1);
    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
    cell.setPaddingBottom(5);
    table.addCell(cell);

    /* COSTE TOTAL */
    cell = new PdfPCell(new Phrase(" "));
    cell.setColspan(1);
    cell.setBorderWidthBottom(0);
    cell.setBorderWidthLeft(0);
    cell.setBorder(0);
    cell.setBorderColorLeft(BaseColor.WHITE);
    cell.setBorderColorBottom(BaseColor.WHITE);
    cell.setPaddingBottom(5);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);
    table.addCell(cell);

    cell = new PdfPCell(new Phrase("TOTAL"));
    cell.setColspan(1);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
    cell.setPaddingBottom(5);
    table.addCell(cell);

    cell = new PdfPCell(new Phrase(df.format(costetotal) + " ", smallBold));
    cell.setColspan(1);
    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
    cell.setPaddingBottom(5);
    table.addCell(cell);

    return table;
}

From source file:eu.trentorise.smartcampus.citizenportal.service.PdfCreator.java

private static void createTable(Section subCatPart) throws BadElementException {
    PdfPTable table = new PdfPTable(5);
    try {//from w ww . j av a2 s.c om
        table.setTotalWidth(new float[] { 70, 85, 250, 60, 60 });
        table.setLockedWidth(true);
    } catch (DocumentException e) {
        e.printStackTrace();
    }
    // t.setBorderColor(BaseColor.GRAY);
    // t.setPadding(4);
    // t.setSpacing(4);
    // t.setBorderWidth(1);
    PdfPCell c1 = new PdfPCell(new Phrase("Posizione", smallBold));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);
    c1 = new PdfPCell(new Phrase("Id Domanda", smallBold));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);
    c1 = new PdfPCell(new Phrase("Richiedente", smallBold));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);
    c1 = new PdfPCell(new Phrase("Comp.", smallBold));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);
    c1 = new PdfPCell(new Phrase("Punti", smallBold));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);
    table.setHeaderRows(1);

    if (listClass != null) {
        for (int i = 0; i < listClass.size(); i++) {
            // Cell for position
            table.addCell(String.valueOf(listClass.get(i).getPosition()));
            // Cell for practice id
            PdfPCell cId = new PdfPCell(new Phrase(listClass.get(i).getPracticeId()));
            cId.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cId);
            // Cell for ric_name
            table.addCell(listClass.get(i).getRicName());
            // Cell for fam_components
            PdfPCell cComps = new PdfPCell(new Phrase(String.valueOf(listClass.get(i).getFamComponents())));
            cComps.setHorizontalAlignment(Element.ALIGN_RIGHT);
            table.addCell(cComps);
            // Cell for score
            PdfPCell cScore = new PdfPCell(new Phrase(listClass.get(i).getScore()));

            cScore.setHorizontalAlignment(Element.ALIGN_RIGHT);
            table.addCell(cScore);
        }
    } else {
        for (int i = 0; i < listClassFinal.size(); i++) {
            // Cell for position
            table.addCell(String.valueOf(listClassFinal.get(i).getPosition()));
            // Cell for practice id
            PdfPCell cId = new PdfPCell(new Phrase(listClassFinal.get(i).getPracticeId()));
            cId.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cId);
            // Cell for ric_name
            table.addCell(listClassFinal.get(i).getRicName());
            // Cell for fam_components
            PdfPCell cComps = new PdfPCell(
                    new Phrase(String.valueOf(listClassFinal.get(i).getFamComponents())));
            cComps.setHorizontalAlignment(Element.ALIGN_RIGHT);
            table.addCell(cComps);
            // Cell for score
            PdfPCell cScore = new PdfPCell(new Phrase(listClassFinal.get(i).getScore()));
            cScore.setHorizontalAlignment(Element.ALIGN_RIGHT);
            table.addCell(cScore);
        }
    }
    subCatPart.add(table);
}

From source file:fll.web.playoff.ScoresheetGenerator.java

License:Open Source License

/**
 * Stores the goal cells that are inserted into the output after the team name
 * headers and before the scoring/initials blanks at the bottom of the
 * scoresheet./*from  w ww. j  a v  a 2 s . c om*/
 */
private void setChallengeInfo(final ChallengeDescription description) {
    setPageTitle(description.getTitle());

    if (null != description.getRevision()) {
        setRevisionInfo(description.getRevision());
    }

    if (null != description.getCopyright()) {
        m_copyright = description.getCopyright();
    } else {
        m_copyright = null;
    }

    final PerformanceScoreCategory performanceElement = description.getPerformance();
    // use ArrayList as we will be doing indexed access in the loop
    final List<AbstractGoal> goals = new ArrayList<>(performanceElement.getGoals());

    final float[] relativeWidths = new float[3];
    relativeWidths[0] = 4;
    relativeWidths[1] = 48;
    relativeWidths[2] = 48;
    m_goalsTable = new PdfPTable(relativeWidths);

    String prevCategory = null;
    for (int goalIndex = 0; goalIndex < goals.size(); ++goalIndex) {
        final AbstractGoal goal = goals.get(goalIndex);
        if (!goal.isComputed()) {
            final String category = goal.getCategory();

            // add category cell if needed
            boolean firstRowInCategory = false;
            if (!StringUtils.equals(prevCategory, category)) {
                if (!StringUtils.isEmpty(category)) {

                    // find out how many future goals have the same category
                    int categoryRowSpan = 1;
                    for (int otherIndex = goalIndex + 1; otherIndex < goals.size(); ++otherIndex) {
                        final AbstractGoal otherGoal = goals.get(otherIndex);
                        if (!otherGoal.isComputed()) {
                            if (StringUtils.equals(category, otherGoal.getCategory())) {
                                ++categoryRowSpan;
                            } else {
                                break;
                            }
                        }
                    }

                    final Paragraph catPara = new Paragraph(category, ARIAL_10PT_NORMAL);
                    final PdfPCell categoryCell = new PdfPCell(catPara);
                    categoryCell.setBorderWidthTop(1);
                    categoryCell.setBorderWidthBottom(0);
                    categoryCell.setBorderWidthLeft(0);
                    categoryCell.setBorderWidthRight(0);
                    categoryCell.setVerticalAlignment(Element.ALIGN_CENTER);
                    categoryCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                    categoryCell.setRotation(90);
                    categoryCell.setRowspan(categoryRowSpan);
                    m_goalsTable.addCell(categoryCell);
                }

                // first row in a new category, which may be empty
                firstRowInCategory = true;
            }

            // This is the text for the left hand "label" cell
            final String title = goal.getTitle();
            final Paragraph p = new Paragraph(title, ARIAL_10PT_NORMAL);
            final PdfPCell goalLabel = new PdfPCell(p);
            goalLabel.setHorizontalAlignment(Element.ALIGN_RIGHT);
            goalLabel.setVerticalAlignment(Element.ALIGN_CENTER);
            if (firstRowInCategory) {
                goalLabel.setBorderWidthTop(1);
                goalLabel.setBorderWidthBottom(0);
                goalLabel.setBorderWidthLeft(0);
                goalLabel.setBorderWidthRight(0);
            } else {
                goalLabel.setBorder(0);
            }
            goalLabel.setPaddingRight(9);
            goalLabel.setVerticalAlignment(Element.ALIGN_TOP);
            if (StringUtils.isEmpty(category)) {
                // category column and goal label column
                goalLabel.setColspan(2);
            }
            m_goalsTable.addCell(goalLabel);

            // define the value cell
            final double min = goal.getMin();
            final String minStr = FP.equals(min, Math.round(min), 1E-6) ? String.valueOf((int) min)
                    : String.valueOf(min);
            final double max = goal.getMax();
            final String maxStr = FP.equals(max, Math.round(max), 1E-6) ? String.valueOf((int) max)
                    : String.valueOf(max);

            // If element has child nodes, then we have an enumerated list
            // of choices. Otherwise it is either yes/no or a numeric field.
            final PdfPCell goalValue = new PdfPCell();
            final Chunk choices = new Chunk("", COURIER_10PT_NORMAL);
            if (goal.isEnumerated()) {
                // replace spaces with "no-break" spaces
                boolean first = true;
                final List<EnumeratedValue> values = goal.getSortedValues();
                for (final EnumeratedValue value : values) {
                    if (!first) {
                        choices.append(" /" + Utilities.NON_BREAKING_SPACE);
                    } else {
                        first = false;
                    }
                    choices.append(value.getTitle().toUpperCase().replace(' ', Utilities.NON_BREAKING_SPACE));
                }
                goalValue.addElement(choices);

            } else {
                if (goal.isYesNo()) {
                    // order of yes/no needs to match ScoreEntry.generateYesNoButtons
                    final Paragraph q = new Paragraph("NO / YES", COURIER_10PT_NORMAL);
                    goalValue.addElement(q);

                } else {
                    final String range = "(" + minStr + " - " + maxStr + ")";
                    final PdfPTable t = new PdfPTable(2);
                    t.setHorizontalAlignment(Element.ALIGN_LEFT);
                    t.setTotalWidth(1 * POINTS_PER_INCH);
                    t.setLockedWidth(true);
                    final Phrase r = new Phrase("", ARIAL_8PT_NORMAL);
                    t.addCell(new PdfPCell(r));
                    final Phrase q = new Phrase(range, ARIAL_8PT_NORMAL);
                    t.addCell(new PdfPCell(q));
                    goalValue.setPaddingTop(9);
                    goalValue.addElement(t);
                }
            }

            if (firstRowInCategory) {
                goalValue.setBorderWidthTop(1);
                goalValue.setBorderWidthBottom(0);
                goalValue.setBorderWidthLeft(0);
                goalValue.setBorderWidthRight(0);
            } else {
                goalValue.setBorder(0);
            }
            goalValue.setVerticalAlignment(Element.ALIGN_MIDDLE);

            m_goalsTable.addCell(goalValue);

            // setup for next loop
            prevCategory = category;
        } // if not computed goal

    } // foreach goal

}