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

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

Introduction

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

Prototype

public void addCell(Phrase phrase) 

Source Link

Document

Adds a cell element.

Usage

From source file:com.crm.webapp.util.PDFCustomExporter.java

License:Apache License

protected void addColumnFacets(DataTable table, PdfPTable pdfTable, ColumnType columnType) {
    for (UIColumn col : table.getColumns()) {
        if (!col.isRendered()) {
            continue;
        }/*from   w  w w.ja va 2  s.c  om*/

        if (col instanceof DynamicColumn) {
            ((DynamicColumn) col).applyModel();
        }

        PdfPCell cell = null;
        if (col.isExportable()) {
            if (col.getHeaderText() != null && columnType.name().equalsIgnoreCase("header")) {
                cell = new PdfPCell(new Paragraph(col.getHeaderText(), this.facetFont));
                if (facetBackground != null) {
                    cell.setBackgroundColor(facetBackground);
                }

                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                pdfTable.addCell(cell);
            } else if (col.getFooterText() != null && columnType.name().equalsIgnoreCase("footer")) {
                cell = new PdfPCell(new Paragraph(col.getFooterText(), this.facetFont));
                if (facetBackground != null) {
                    cell.setBackgroundColor(facetBackground);
                }

                pdfTable.addCell(cell);
            } else {
                UIComponent component = (UIComponent) col;

                //Adding RowIndex for Custom Exporter
                if (component.getId().equalsIgnoreCase("subject")) {
                    String value = "Index";
                    PdfPCell cellIndex = new PdfPCell(new Paragraph(value));
                    //addColumnAlignments(component, cell);

                    if (facetBackground != null) {
                        cellIndex.setBackgroundColor(facetBackground);
                    }

                    cellIndex.setHorizontalAlignment(Element.ALIGN_CENTER);

                    pdfTable.addCell(cellIndex);
                }

                addColumnValue(pdfTable, col.getFacet(columnType.facet()), this.facetFont, columnType.name());
            }
        }
    }
}

From source file:com.crm.webapp.util.PDFCustomExporter.java

License:Apache License

protected void addColumnFacets(SubTable table, PdfPTable pdfTable, ColumnType columnType) {
    for (UIColumn col : table.getColumns()) {
        if (!col.isRendered()) {
            continue;
        }//from   w ww .  java2s  . c o m

        if (col instanceof DynamicColumn) {
            ((DynamicColumn) col).applyModel();
        }

        PdfPCell cell = null;
        if (col.isExportable()) {
            if (col.getHeaderText() != null && columnType.name().equalsIgnoreCase("header")) {
                cell = new PdfPCell(new Paragraph(col.getHeaderText(), this.facetFont));
                if (facetBackground != null) {
                    cell.setBackgroundColor(facetBackground);
                }

                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                pdfTable.addCell(cell);
            } else if (col.getFooterText() != null && columnType.name().equalsIgnoreCase("footer")) {
                cell = new PdfPCell(new Paragraph(col.getFooterText(), this.facetFont));
                if (facetBackground != null) {
                    cell.setBackgroundColor(facetBackground);
                }

                pdfTable.addCell(cell);
            } else {
                addColumnValue(pdfTable, col.getFacet(columnType.facet()), this.facetFont, columnType.name());
            }
        }
    }
}

From source file:com.crm.webapp.util.PDFCustomExporter.java

License:Apache License

protected void addColumnValue(PdfPTable pdfTable, UIComponent component, Font font, String columnType) {
    String value = component == null ? "" : exportValue(FacesContext.getCurrentInstance(), component);
    PdfPCell cell = new PdfPCell(new Paragraph(value, font));
    //addColumnAlignments(component, cell);

    if (facetBackground != null) {
        cell.setBackgroundColor(facetBackground);
    }//from w  ww .j a v  a  2 s. c o m

    if (columnType.equalsIgnoreCase("header")) {
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    }

    pdfTable.addCell(cell);
}

From source file:com.crm.webapp.util.PDFCustomExporter.java

License:Apache License

protected void addColumnValue(PdfPTable pdfTable, List<UIComponent> components, Font font, String columnType) {
    StringBuilder builder = new StringBuilder();

    for (UIComponent component : components) {
        if (component.isRendered()) {
            String value = exportValue(FacesContext.getCurrentInstance(), component);

            if (value != null) {
                builder.append(value);//  w w  w .  j  av a2s .  c  o  m
            }
        }
    }

    PdfPCell cell = new PdfPCell(new Paragraph(builder.toString(), font));

    //addColumnAlignments(components, cell);
    if (columnType.equalsIgnoreCase("header")) {
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    }

    pdfTable.addCell(cell);
}

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

License:Open Source License

/**
 * Gets the cell height.//from ww w. j  a va2s .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.efficio.fieldbook.web.demo.controller.BarCodeController.java

License:Open Source License

/**
 * Upload file./*  w w w .  jav  a 2s  . c om*/
 *
 * @param uploadForm the upload form
 * @param result the result
 * @param model the model
 * @return the string
 */
@ResponseBody
@RequestMapping(method = RequestMethod.POST)
public String uploadFile(@ModelAttribute("barCodeForm") BarCodeForm barCodeForm, BindingResult result,
        Model model, HttpServletResponse response) {
    int width = 60;
    int height = 48;
    String delimeter = "|";
    StringBuilder barCodeString = new StringBuilder();

    barCodeString.append(barCodeForm.getEntryNo()).append(delimeter).append(barCodeForm.getGid())
            .append(delimeter).append(barCodeForm.getDesignation()).append(delimeter)
            .append(barCodeForm.getName()).append(delimeter).append(barCodeForm.getRep()).append(delimeter)
            .append(barCodeForm.getColumn()).append(delimeter).append(barCodeForm.getRange());

    BitMatrix bitMatrix;
    try {
        String barCodeLabel = "3|SM114-1A-1-1-1B";
        //barCodeLabel = barCodeString.toString();
        bitMatrix = new Code128Writer().encode(barCodeLabel, BarcodeFormat.CODE_128, width, height, null);
        String imageLocation = Math.random() + ".png"; //"src/test/resources/barcode/zxing_barcode.png";
        MatrixToImageWriter.writeToStream(bitMatrix, "png", new FileOutputStream(new File(imageLocation)));

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

        response.setHeader("Content-disposition", "attachment; filename=" + fileName);

        File xls = new File(fileName); // the selected name + current date
        FileInputStream in;

        try {

            Image image1 = Image.getInstance(imageLocation);
            //image1.scalePercent(50);
            //image1.setAbsolutePosition(10f, 10f);
            //document.add(image1);

            //PageSize.A4
            Document document = new Document(PageSize.LETTER);
            // step 2
            PdfWriter.getInstance(document, new FileOutputStream(fileName));
            // step 3
            document.open();
            // step 4
            // we'll use 4 images in this example
            /*
            Image[] img = {
                 Image.getInstance(String.format(RESOURCE, "0120903")),
                 Image.getInstance(String.format(RESOURCE, "0290334")),
                 Image.getInstance(String.format(RESOURCE, "0376994")),
                 Image.getInstance(String.format(RESOURCE, "0348150"))
            };*/

            PdfPTable table = new PdfPTable(4);
            table.setWidthPercentage(100);
            // first movie
            table.getDefaultCell().setVerticalAlignment(Element.ALIGN_BOTTOM);
            Phrase phrase = new Phrase();
            phrase.add("Entry # " + barCodeForm.getEntryNo());
            phrase.add("\n");
            phrase.add("Designation " + barCodeForm.getDesignation());
            phrase.add("\n");
            phrase.add("Rep " + barCodeForm.getRep());
            phrase.add("\n");
            phrase.add("GID " + barCodeForm.getGid());
            phrase.add("\n");
            phrase.add("Trial/Nursery Name " + barCodeForm.getName());
            phrase.add("\n");
            phrase.add("Col " + barCodeForm.getColumn());
            phrase.add("\n");
            phrase.add("Range " + barCodeForm.getRange());
            table.addCell(phrase);
            // we add the image with addCell()
            table.addCell(image1);

            table.getDefaultCell().setVerticalAlignment(Element.ALIGN_BOTTOM);
            table.addCell("X-Men: The Last Stand");
            // we add the image with addCell()
            table.addCell(image1);

            table.getDefaultCell().setVerticalAlignment(Element.ALIGN_BOTTOM);
            table.addCell("X-Men: The Last Stand");
            // we add the image with addCell()
            table.addCell(image1);

            // we complete the table (otherwise the last row won't be rendered)
            table.completeRow();
            document.add(table);

            document.close();

            in = new FileInputStream(xls);
            OutputStream out = response.getOutputStream();

            byte[] buffer = new byte[BUFFER_SIZE]; // use bigger if you want
            int length = 0;

            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }
            in.close();
            out.close();
        } catch (FileNotFoundException e) {
            LOG.error(e.getMessage(), e);
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }

        return "";

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

    return show(barCodeForm, model);
}

From source file:com.exam.server.ConvertPDF.java

private static void createTable(Section subCatPart, ArrayList<DeviceDTO> input) throws BadElementException {
    //                PdfPTable table = new PdfPTable(input.size()+1);
    PdfPTable table = new PdfPTable(6);
    System.out.println("size::" + input.size());

    // t.setBorderColor(BaseColor.GRAY);
    // t.setPadding(4);
    // t.setSpacing(4);
    // t.setBorderWidth(1);

    PdfPCell c1 = new PdfPCell(new Phrase("Part2 Id"));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);

    c1 = new PdfPCell(new Phrase("Id Company"));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);//from  w ww  . j  a  v a  2s . co m

    c1 = new PdfPCell(new Phrase("Address"));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);
    c1 = new PdfPCell(new Phrase("Data1"));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);
    c1 = new PdfPCell(new Phrase("Time1"));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);
    c1 = new PdfPCell(new Phrase("Time2"));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);
    table.setHeaderRows(1);

    for (int i = 0; i < input.size(); i++) {
        table.addCell("" + input.get(i).getPart2Id());
        table.addCell("" + input.get(i).getIdCompany());
        table.addCell(input.get(i).getAddress1());
        table.addCell(input.get(i).getData1());
        table.addCell(input.get(i).getTime1());
        table.addCell(input.get(i).getTime2());
    }

    subCatPart.add(table);

}

From source file:com.geek.tutorial.itext.acroform.TextFieldForm.java

License:Open Source License

public TextFieldForm() throws Exception {
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("TextFieldForm.pdf"));
    document.open();/*from www  .  jav  a 2 s . co m*/

    PdfPTable table = new PdfPTable(2);
    table.getDefaultCell().setPadding(5f); // Code 1, will only affect empty field
    table.setHorizontalAlignment(Element.ALIGN_LEFT);
    PdfPCell cell;

    // Code 2, add name TextField      
    table.addCell("Name");
    TextField nameField = new TextField(writer, new Rectangle(0, 0, 200, 10), "nameField");
    nameField.setBackgroundColor(Color.WHITE);
    nameField.setBorderColor(Color.BLACK);
    nameField.setBorderWidth(1);
    nameField.setBorderStyle(PdfBorderDictionary.STYLE_SOLID);
    nameField.setText("");
    nameField.setAlignment(Element.ALIGN_LEFT);
    nameField.setOptions(TextField.REQUIRED);
    cell = new PdfPCell();
    cell.setMinimumHeight(10);
    cell.setCellEvent(new FieldCell(nameField.getTextField(), 200, writer));
    table.addCell(cell);

    // force upper case javascript
    writer.addJavaScript("var nameField = this.getField('nameField');" + "nameField.setAction('Keystroke',"
            + "'forceUpperCase()');" + "" + "function forceUpperCase(){"
            + "if(!event.willCommit)event.change = " + "event.change.toUpperCase();" + "}");

    // Code 3, add empty row
    table.addCell("");
    table.addCell("");

    // Code 4, add age TextField
    table.addCell("Age");
    TextField ageComb = new TextField(writer, new Rectangle(0, 0, 30, 10), "ageField");
    ageComb.setBorderColor(Color.BLACK);
    ageComb.setBorderWidth(1);
    ageComb.setBorderStyle(PdfBorderDictionary.STYLE_SOLID);
    ageComb.setText("12");
    ageComb.setAlignment(Element.ALIGN_RIGHT);
    ageComb.setMaxCharacterLength(2);
    ageComb.setOptions(TextField.COMB | TextField.DO_NOT_SCROLL);
    cell = new PdfPCell();
    cell.setMinimumHeight(10);
    cell.setCellEvent(new FieldCell(ageComb.getTextField(), 30, writer));
    table.addCell(cell);

    // validate age javascript
    writer.addJavaScript("var ageField = this.getField('ageField');"
            + "ageField.setAction('Validate','checkAge()');" + "function checkAge(){" + "if(event.value < 12){"
            + "app.alert('Warning! Applicant\\'s age can not" + " be younger than 12.');" + "event.value = 12;"
            + "}}");

    // add empty row
    table.addCell("");
    table.addCell("");

    // Code 5, add age TextField
    table.addCell("Comment");
    TextField comment = new TextField(writer, new Rectangle(0, 0, 200, 100), "commentField");
    comment.setBorderColor(Color.BLACK);
    comment.setBorderWidth(1);
    comment.setBorderStyle(PdfBorderDictionary.STYLE_SOLID);
    comment.setText("");
    comment.setOptions(TextField.MULTILINE | TextField.DO_NOT_SCROLL);
    cell = new PdfPCell();
    cell.setMinimumHeight(100);
    cell.setCellEvent(new FieldCell(comment.getTextField(), 200, writer));
    table.addCell(cell);

    // check comment characters length javascript
    writer.addJavaScript("var commentField = " + "this.getField('commentField');" + "commentField"
            + ".setAction('Keystroke','checkLength()');" + "function checkLength(){"
            + "if(!event.willCommit && " + "event.value.length > 100){" + "app.alert('Warning! Comment can not "
            + "be more than 100 characters.');" + "event.change = '';" + "}}");

    // add empty row
    table.addCell("");
    table.addCell("");

    // Code 6, add submit button   
    PushbuttonField submitBtn = new PushbuttonField(writer, new Rectangle(0, 0, 35, 15), "submitPOST");
    submitBtn.setBackgroundColor(Color.GRAY);
    submitBtn.setBorderStyle(PdfBorderDictionary.STYLE_BEVELED);
    submitBtn.setText("POST");
    submitBtn.setOptions(PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT);
    PdfFormField submitField = submitBtn.getField();
    submitField.setAction(PdfAction.createSubmitForm("http://www.geek-tutorials.com/java/itext/submit.php",
            null, PdfAction.SUBMIT_HTML_FORMAT));
    cell = new PdfPCell();
    cell.setMinimumHeight(15);
    cell.setCellEvent(new FieldCell(submitField, 35, writer));
    table.addCell(cell);

    // Code 7, add reset button
    PushbuttonField resetBtn = new PushbuttonField(writer, new Rectangle(0, 0, 35, 15), "reset");
    resetBtn.setBackgroundColor(Color.GRAY);
    resetBtn.setBorderStyle(PdfBorderDictionary.STYLE_BEVELED);
    resetBtn.setText("RESET");
    resetBtn.setOptions(PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT);
    PdfFormField resetField = resetBtn.getField();
    resetField.setAction(PdfAction.createResetForm(null, 0));
    cell = new PdfPCell();
    cell.setMinimumHeight(15);
    cell.setCellEvent(new FieldCell(resetField, 35, writer));
    table.addCell(cell);

    document.add(table);
    document.close();
}

From source file:com.geek.tutorial.itext.servlet.PDFServlet.java

License:Open Source License

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("application/pdf"); // Code 1
    Document document = new Document();
    try {/*from w  w w.j  a  va2 s  .  c om*/
        PdfWriter.getInstance(document, response.getOutputStream()); // Code 2
        document.open();

        // Code 3
        PdfPTable table = new PdfPTable(2);
        table.addCell("1");
        table.addCell("2");
        table.addCell("3");
        table.addCell("4");
        table.addCell("5");
        table.addCell("6");

        // Code 4
        document.add(table);
        document.close();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}

From source file:com.geek.tutorial.itext.table.PDFTable.java

License:Open Source License

public PDFTable() throws Exception {

    Document document = new Document();
    PdfWriter.getInstance(document, new FileOutputStream("table_example.pdf"));
    document.open();/*from   www. ja v  a 2 s. c o m*/

    PdfPTable table = new PdfPTable(3);
    //table.setTotalWidth(216f);
    //table.setLockedWidth(true);
    PdfPCell cell = new PdfPCell(new Paragraph("header with colspan 3"));
    cell.setColspan(3);
    table.addCell(cell);
    table.addCell("1.1");
    table.addCell("2.1");
    table.addCell("3.1");
    table.addCell("1.2");
    table.addCell("2.2");
    table.addCell("3.2");

    document.add(table);

    document.close();

}