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.qcadoo.plugins.qcadooExport.internal.ExportToPDFController.java

License:Open Source License

@Monitorable(threshold = 500)
@ResponseBody//from   w w  w . j ava 2  s  . c om
@RequestMapping(value = { CONTROLLER_PATH }, method = RequestMethod.POST)
public Object generatePdf(@PathVariable(PLUGIN_IDENTIFIER_VARIABLE) final String pluginIdentifier,
        @PathVariable(VIEW_NAME_VARIABLE) final String viewName, @RequestBody final JSONObject body,
        final Locale locale) {
    try {
        changeMaxResults(body);
        ViewDefinitionState state = crudService.invokeEvent(pluginIdentifier, viewName, body, locale);
        GridComponent grid = (GridComponent) state.getComponentByReference("grid");
        Document document = new Document(PageSize.A4.rotate());
        String date = DateFormat.getDateInstance().format(new Date());
        File file = fileService.createExportFile("export_" + grid.getName() + "_" + date + ".pdf");
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        PdfWriter writer = PdfWriter.getInstance(document, fileOutputStream);

        writer.setPageEvent(new PdfPageNumbering(footerResolver.resolveFooter(locale)));

        document.setMargins(40, 40, 60, 60);

        document.addTitle("export.pdf");
        pdfHelper.addMetaData(document);
        writer.createXmpMetadata();
        document.open();

        String title = translationService.translate(
                pluginIdentifier + "." + viewName + ".window.mainTab." + grid.getName() + ".header", locale);

        Date generationDate = new Date();

        pdfHelper.addDocumentHeader(document, "", title,
                translationService.translate("qcadooReport.commons.generatedBy.label", locale), generationDate);

        int columns = 0;
        List<String> exportToPDFTableHeader = new ArrayList<String>();
        for (String name : grid.getColumnNames().values()) {
            exportToPDFTableHeader.add(name);
            columns++;
        }
        PdfPTable table = pdfHelper.createTableWithHeader(columns, exportToPDFTableHeader, false);

        List<Map<String, String>> rows;
        if (grid.getSelectedEntitiesIds().isEmpty()) {
            rows = grid.getColumnValuesOfAllRecords();
        } else {
            rows = grid.getColumnValuesOfSelectedRecords();
        }

        for (Map<String, String> row : rows) {
            for (String value : row.values()) {
                table.addCell(new Phrase(value, FontUtils.getDejavuRegular7Dark()));
            }
        }
        document.add(table);
        document.close();

        state.redirectTo(fileService.getUrl(file.getAbsolutePath()) + "?clean", true, false);
        return crudService.renderView(state);
    } catch (JSONException e) {
        throw new IllegalStateException(e.getMessage(), e);
    } catch (FileNotFoundException e) {
        throw new IllegalStateException(e.getMessage(), e);
    } catch (DocumentException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}

From source file:com.qcadoo.report.internal.PdfHelperImpl.java

License:Open Source License

@Override
public void addDocumentHeader(final Document document, final String name, final String documenTitle,
        final String documentAuthor, final Date date, final String username) throws DocumentException {
    SimpleDateFormat df = new SimpleDateFormat(DateUtils.L_DATE_TIME_FORMAT, getLocale());
    LineSeparator line = new LineSeparator(3, 100f, ColorUtils.getLineDarkColor(), Element.ALIGN_LEFT, 0);
    document.add(Chunk.NEWLINE);/*from  w w w  . j  av  a  2s .  c o m*/
    Paragraph title = new Paragraph(new Phrase(documenTitle, FontUtils.getDejavuBold17Light()));
    title.add(new Phrase(" " + name, FontUtils.getDejavuBold17Dark()));
    title.setSpacingAfter(7f);
    document.add(title);
    document.add(line);
    PdfPTable userAndDate = new PdfPTable(2);
    userAndDate.setWidthPercentage(100f);
    userAndDate.setHorizontalAlignment(Element.ALIGN_LEFT);
    userAndDate.getDefaultCell().setBorderWidth(0);
    Paragraph userParagraph = new Paragraph(new Phrase(documentAuthor, FontUtils.getDejavuRegular9Light()));
    userParagraph.add(new Phrase(" " + username, FontUtils.getDejavuRegular9Dark()));
    Paragraph dateParagraph = new Paragraph(df.format(date), FontUtils.getDejavuRegular9Light());
    userAndDate.addCell(userParagraph);
    userAndDate.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
    userAndDate.addCell(dateParagraph);
    userAndDate.setSpacingAfter(14f);
    document.add(userAndDate);
}

From source file:com.qcadoo.report.internal.PdfHelperImpl.java

License:Open Source License

@Override
public void addDocumentHeader(final Document document, final String name, final String documenTitle,
        final String documentAuthor, final Date date) throws DocumentException {
    SimpleDateFormat df = new SimpleDateFormat(DateUtils.L_DATE_TIME_FORMAT, getLocale());
    LineSeparator line = new LineSeparator(2, 100f, ColorUtils.getLineDarkColor(), Element.ALIGN_LEFT, 0);
    document.add(Chunk.NEWLINE);/*from   ww  w .j  a v  a  2s .  co m*/
    Paragraph title = new Paragraph(new Phrase(documenTitle, FontUtils.getDejavuBold17Light()));
    title.add(new Phrase(" " + name, FontUtils.getDejavuBold17Dark()));
    title.setSpacingAfter(7f);
    document.add(title);
    document.add(line);
    PdfPTable userAndDate = new PdfPTable(2);
    userAndDate.setWidthPercentage(100f);
    userAndDate.setHorizontalAlignment(Element.ALIGN_LEFT);
    userAndDate.getDefaultCell().setBorderWidth(0);
    Paragraph userParagraph = new Paragraph(new Phrase(documentAuthor, FontUtils.getDejavuRegular9Light()));
    userParagraph.add(new Phrase(" " + getDocumentAuthor(), FontUtils.getDejavuRegular9Dark()));
    Paragraph dateParagraph = new Paragraph(df.format(date), FontUtils.getDejavuRegular9Light());
    userAndDate.addCell(userParagraph);
    userAndDate.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
    userAndDate.addCell(dateParagraph);
    userAndDate.setSpacingAfter(14f);
    document.add(userAndDate);
}

From source file:com.qcadoo.report.internal.PdfHelperImpl.java

License:Open Source License

@Override
public void addDocumentHeaderThin(final Document document, final String name, final String documentTitle,
        final String documentAuthor, final Date date) throws DocumentException {
    SimpleDateFormat df = new SimpleDateFormat(DateUtils.L_DATE_TIME_FORMAT, getLocale());
    LineSeparator line = new LineSeparator(2, 100f, ColorUtils.getLineDarkColor(), Element.ALIGN_LEFT, 0);
    Paragraph title = new Paragraph(new Phrase(documentTitle, FontUtils.getDejavuBold14Light()));
    title.add(new Phrase(" " + name, FontUtils.getDejavuBold14Dark()));
    title.setSpacingAfter(7f);/*  w w  w .java 2  s .  co  m*/
    document.add(title);
    document.add(line);
    PdfPTable userAndDate = new PdfPTable(2);
    userAndDate.setWidthPercentage(100f);
    userAndDate.setHorizontalAlignment(Element.ALIGN_LEFT);
    userAndDate.getDefaultCell().setBorderWidth(0);
    Paragraph userParagraph = new Paragraph(new Phrase(documentAuthor, FontUtils.getDejavuRegular9Light()));
    userParagraph.add(new Phrase(" " + getDocumentAuthor(), FontUtils.getDejavuRegular9Dark()));
    Paragraph dateParagraph = new Paragraph(df.format(date), FontUtils.getDejavuRegular9Light());
    userAndDate.addCell(userParagraph);
    userAndDate.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
    userAndDate.addCell(dateParagraph);
    userAndDate.setSpacingAfter(10f);
    document.add(userAndDate);
}

From source file:com.qcadoo.report.internal.PdfHelperImpl.java

License:Open Source License

private void addTableCellAsTable(final PdfPTable table, final String label, final Object fieldValue,
        final String nullValue, final Font headerFont, final Font valueFont, final int columns,
        final int[] columnWidths) {
    PdfPTable cellTable = new PdfPTable(columns);

    if (columnWidths.length > 0) {
        try {/*from   w w  w  .  j  a v  a2s .c  o  m*/
            cellTable.setWidths(columnWidths);
        } catch (DocumentException e) {
            LOG.error(e.getMessage(), e);
        }
    }

    cellTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
    cellTable.addCell(new Phrase(label, headerFont));

    if (fieldValue == null) {
        cellTable.addCell(new Phrase(nullValue, valueFont));
    } else {
        cellTable.addCell(new Phrase(fieldValue.toString(), valueFont));
    }

    table.addCell(cellTable);
}

From source file:com.qcadoo.report.internal.PdfHelperImpl.java

License:Open Source License

private PdfPTable setTableProperties(final List<String> header, final boolean lastColumnAligmentToLeft,
        final PdfPTable table, final Map<String, HeaderAlignment> alignments) {
    table.setWidthPercentage(100f);/* ww w  .  ja  v a 2 s .co  m*/
    table.setHorizontalAlignment(Element.ALIGN_LEFT);
    table.setSpacingBefore(7.0f);
    // table.getDefaultCell().setBackgroundColor(ColorUtils.getBackgroundColor());
    table.getDefaultCell().setBorderColor(ColorUtils.getLineDarkColor());
    table.getDefaultCell().setBorderWidth(1.0f);
    table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
    table.getDefaultCell().setPadding(5.0f);
    table.getDefaultCell().disableBorderSide(Rectangle.RIGHT);

    if (alignments == null || alignments.isEmpty()) {
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
        int i = 0;
        for (String element : header) {
            i++;
            if (i == header.size()) {
                table.getDefaultCell().enableBorderSide(Rectangle.RIGHT);
            }
            table.addCell(new Phrase(element, FontUtils.getDejavuBold7Dark()));
            if (i == 1) {
                table.getDefaultCell().disableBorderSide(Rectangle.LEFT);
            }
        }
    } else {
        int i = 0;

        for (String element : header) {
            i++;
            HeaderAlignment alignment = alignments.get(element);
            if (HeaderAlignment.LEFT.equals(alignment)) {
                table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
            } else if (HeaderAlignment.RIGHT.equals(alignment)) {
                table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
            }
            if (i == header.size()) {
                table.getDefaultCell().enableBorderSide(Rectangle.RIGHT);
            }
            table.addCell(new Phrase(element, FontUtils.getDejavuBold7Dark()));
            if (i == 1) {
                table.getDefaultCell().disableBorderSide(Rectangle.LEFT);
            }
        }
    }
    table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
    table.getDefaultCell().setBackgroundColor(null);
    table.getDefaultCell().disableBorderSide(Rectangle.RIGHT);
    table.getDefaultCell().setBorderColor(ColorUtils.getLineLightColor());
    return table;
}

From source file:com.safetys.framework.jmesa.view.pdfp.PdfPView.java

License:Apache License

@SuppressWarnings("deprecation")
public PdfPTable render() {
    PdfPTable pdfpTable = new PdfPTable(getTable().getRow().getColumns().size());
    pdfpTable.setSpacingBefore(3);/* ww w.ja v a  2 s.c  om*/

    Row row = getTable().getRow();

    List<Column> columns = row.getColumns();

    // build table headers
    for (Iterator<Column> iter = columns.iterator(); iter.hasNext();) {
        Column column = iter.next();
        PdfPCell cell = new PdfPCell(new Paragraph(column.getTitle(), getHeaderCellFont()));
        cell.setPadding(3.0f);
        cell.setBackgroundColor(getHeaderBackgroundColor());
        pdfpTable.addCell(cell);
    }

    // build table body
    Collection<?> items = getCoreContext().getPageItems();
    int rowcount = 0;
    for (Object item : items) {
        rowcount++;
        columns = row.getColumns();
        for (Iterator<Column> iter = columns.iterator(); iter.hasNext();) {
            Column column = iter.next();
            String property = column.getProperty();
            Object value = column.getCellRenderer().getCellEditor().getValue(item, property, rowcount);
            PdfPCell cell = new PdfPCell(
                    new Paragraph(value == null ? "" : String.valueOf(value), getCellFont()));
            cell.setPadding(3.0f);

            if (isRowEven(rowcount)) {
                cell.setBackgroundColor(getEvenCellBackgroundColor());
            } else {
                cell.setBackgroundColor(getOddCellBackgroundColor());
            }

            pdfpTable.addCell(cell);
        }
    }

    return pdfpTable;
}

From source file:com.senacor.wbs.web.project.ProjectListPanel.java

License:Apache License

public ProjectListPanel(final String id, final List<Project> projects) {
    super(id);/*from   w  ww. j av a2  s  .  c  om*/
    this.locale = getLocale();
    SortableListDataProvider<Project> projectProvider = new SortableListDataProvider<Project>(projects) {
        @Override
        protected Locale getLocale() {
            return ProjectListPanel.this.getLocale();
        }

        public IModel model(final Object object) {
            return new CompoundPropertyModel(object);
        }
    };
    projectProvider.setSort("name", true);
    dataView = new DataView("projects", projectProvider, 4) {
        @Override
        protected void populateItem(final Item item) {
            Project project = (Project) item.getModelObject();
            PageParameters pageParameters = new PageParameters();
            pageParameters.put("projectId", project.getId());
            item.add(new BookmarkablePageLink("tasks", ProjectDetailsPage.class, pageParameters)
                    .add(new Label("id")));
            item.add(new Label("kuerzel"));
            item.add(new Label("titel", project.getName()));
            item.add(new Label("budget"));
            item.add(new Label("costPerHour"));
            item.add(new Label("start"));
            item.add(new Label("ende"));
            item.add(new Label("state"));
            // Alternieren der Farbe zwischen geraden und
            // ungeraden Zeilen
            item.add(new AttributeModifier("class", true, new AbstractReadOnlyModel() {
                @Override
                public Object getObject() {
                    return (item.getIndex() % 2 == 1) ? "even" : "odd";
                }
            }));
        }
    };
    add(dataView);
    Form localeForm = new Form("localeForm");
    ImageButton deButton = new ImageButton("langde", new ResourceReference(BaseWBSPage.class, "de.png")) {
        @Override
        public void onSubmit() {
            ProjectListPanel.this.locale = Locale.GERMANY;
        }
    };
    localeForm.add(deButton);
    ImageButton usButton = new ImageButton("langus", new ResourceReference(BaseWBSPage.class, "us.png")) {
        @Override
        public void onSubmit() {
            ProjectListPanel.this.locale = Locale.US;
        }
    };
    localeForm.add(usButton);
    add(localeForm);
    final IResourceStream pdfResourceStream = new AbstractResourceStreamWriter() {
        public void write(final OutputStream output) {
            Document document = new Document();
            try {
                PdfWriter.getInstance(document, output);
                document.open();
                // document.add(new
                // Paragraph("WBS-Projektliste"));
                // document.add(new Paragraph(""));
                PdfPTable table = new PdfPTable(new float[] { 1f, 1f, 2f, 1f });
                PdfPCell cell = new PdfPCell(new Paragraph("WBS-Projektliste"));
                cell.setColspan(4);
                cell.setGrayFill(0.8f);
                table.addCell(cell);
                table.addCell("ID");
                table.addCell("Krzel");
                table.addCell("Titel");
                table.addCell("Budget in PT");
                for (Project project : projects) {
                    table.addCell("" + project.getId());
                    table.addCell(project.getKuerzel());
                    table.addCell(project.getName());
                    table.addCell("" + project.getBudget());
                }
                document.add(table);
                document.close();
            } catch (DocumentException e) {
                throw new RuntimeException(e);
            }
        }

        public String getContentType() {
            return "application/pdf";
        }
    };
    WebResource projectsResource = new WebResource() {
        {
            setCacheable(false);
        }

        @Override
        public IResourceStream getResourceStream() {
            return pdfResourceStream;
        }

        @Override
        protected void setHeaders(final WebResponse response) {
            super.setHeaders(response);
            // response.setAttachmentHeader("projekte.pdf");
        }
    };
    WebResource projectsResourceDL = new WebResource() {
        {
            setCacheable(false);
        }

        @Override
        public IResourceStream getResourceStream() {
            return pdfResourceStream;
        }

        @Override
        protected void setHeaders(final WebResponse response) {
            super.setHeaders(response);
            response.setAttachmentHeader("projekte.pdf");
        }
    };
    ResourceLink pdfDownload = new ResourceLink("pdfDownload", projectsResourceDL);
    ResourceLink pdfPopup = new ResourceLink("pdfPopup", projectsResource);
    PopupSettings popupSettings = new PopupSettings(PopupSettings.STATUS_BAR);
    popupSettings.setWidth(500);
    popupSettings.setHeight(700);
    pdfPopup.setPopupSettings(popupSettings);
    Link pdfReqTarget = new Link("pdfReqTarget") {
        @Override
        public void onClick() {
            RequestCycle.get()
                    .setRequestTarget(new ResourceStreamRequestTarget(pdfResourceStream, "projekte.pdf"));
        }
    };
    add(pdfReqTarget);
    add(pdfDownload);
    add(pdfPopup);
    add(new OrderByBorder("orderByKuerzel", "kuerzel", projectProvider));
    add(new OrderByBorder("orderByName", "name", projectProvider));
    add(new OrderByBorder("orderByBudget", "budget", projectProvider));
    add(new OrderByBorder("orderByCostPerHour", "costPerHour", projectProvider));
    add(new OrderByBorder("orderByStart", "start", projectProvider));
    add(new OrderByBorder("orderByEnde", "ende", projectProvider));
    add(new OrderByBorder("orderByState", "state", projectProvider));
    add(new PagingNavigator("projectsNavigator", dataView));
}

From source file:com.silverpeas.kmelia.workflowextensions.SendInKmelia.java

License:Open Source License

private void generatePDFStepHeader(HistoryStep step, com.lowagie.text.Document document) {
    try {/*from   www  . j  a v a2s  .c o  m*/
        String activity = "";
        if (step.getResolvedState() != null) {
            State resolvedState = step.getProcessInstance().getProcessModel().getState(step.getResolvedState());
            activity = resolvedState.getLabel(getRole(), getLanguage());
        }

        String sAction = null;
        try {
            if ("#question#".equals(step.getAction())) {
                sAction = getString("processManager.question");
            } else if ("#response#".equals(step.getAction())) {
                sAction = getString("processManager.response");
            } else if ("#reAssign#".equals(step.getAction())) {
                sAction = getString("processManager.reAffectation");
            } else {
                Action action = step.getProcessInstance().getProcessModel().getAction(step.getAction());
                sAction = action.getLabel(getRole(), getLanguage());
            }
        } catch (WorkflowException we) {
            sAction = "##";
        }

        String actor = getBestUserDetail().getDisplayedName();

        String date = DateUtil.getOutputDateAndHour(step.getActionDate(), getLanguage());

        String header = "";
        if (StringUtil.isDefined(activity)) {
            header += activity + " - ";
        }
        header += sAction + " (" + actor + " - " + date + ")";

        Font fontHeader = new Font(Font.HELVETICA, 12, Font.NORMAL);

        PdfPCell pCell = new PdfPCell(new Phrase(header, fontHeader));
        pCell.setFixedHeight(28);
        pCell.setBackgroundColor(new Color(239, 239, 239));
        pCell.setVerticalAlignment(Element.ALIGN_MIDDLE);

        PdfPTable pTable = new PdfPTable(1);
        pTable.setWidthPercentage(100);
        pTable.addCell(pCell);

        document.add(pTable);
    } catch (Exception e) {
        SilverTrace.error("workflowEngine", "SendInKmelia.generatePDFStep()", "root.MSG_GEN_ERROR", e);
    }
}

From source file:com.silverpeas.kmelia.workflowextensions.SendInKmelia.java

License:Open Source License

private void generatePDFStepContent(HistoryStep step, com.lowagie.text.Document document) {
    try {/*from  ww w.j  a va2  s . c o  m*/
        Form form;
        if ("#question#".equals(step.getAction()) || "#response#".equals(step.getAction())) {
            // TODO
            form = null;
        } else {
            form = getProcessInstance().getProcessModel().getPresentationForm(step.getAction(), getRole(),
                    getLanguage());
        }

        XmlForm xmlForm = (XmlForm) form;
        if (xmlForm != null && step.getActionRecord() != null) {
            DataRecord data = step.getActionRecord();
            VersioningUtil versioningUtil = new VersioningUtil();

            // Force simpletext displayers because itext cannot display HTML Form fields (select,
            // radio...)
            float[] colsWidth = { 25, 75 };
            PdfPTable tableContent = new PdfPTable(colsWidth);
            tableContent.setWidthPercentage(100);

            PdfPCell cell = null;
            Field field;
            String fieldLabel;
            String fieldValue = "";
            Font fontLabel = new Font(Font.HELVETICA, 10, Font.BOLD);
            Font fontValue = new Font(Font.HELVETICA, 10, Font.NORMAL);
            List<FieldTemplate> fieldTemplates = xmlForm.getFieldTemplates();
            for (FieldTemplate fieldTemplate1 : fieldTemplates) {
                GenericFieldTemplate fieldTemplate = (GenericFieldTemplate) fieldTemplate1;

                fieldLabel = fieldTemplate.getLabel("fr");
                field = data.getField(fieldTemplate.getFieldName());
                String componentId = step.getProcessInstance().getProcessModel().getModelId();

                //          fieldValue = data.getField(fieldTemplate.getFieldName()).getValue();
                //wysiwyg field
                if ("wysiwyg".equals(fieldTemplate.getDisplayerName())) {
                    String file = WysiwygFCKFieldDisplayer.getFile(componentId,
                            getProcessInstance().getInstanceId(), fieldTemplate.getFieldName(), getLanguage());

                    //Extract the text content of the html code
                    Source source = new Source(file);
                    if (source != null) {
                        fieldValue = source.getTextExtractor().toString();
                    }
                }
                //Field file type
                else if (FileField.TYPE.equals(fieldTemplate.getDisplayerName())
                        && StringUtil.isDefined(field.getValue())) {
                    boolean fromCompoVersion = "yes".equals(getOrganizationController()
                            .getComponentParameterValue(componentId, "versionControl"));
                    //Versioning Used
                    if (fromCompoVersion) {
                        DocumentVersion documentVersion = versioningUtil
                                .getDocumentVersion(new DocumentVersionPK(Integer.parseInt(field.getValue())));
                        if (documentVersion != null) {
                            fieldValue = documentVersion.getLogicalName();
                        }
                    } else {
                        AttachmentDetail attDetail = AttachmentController
                                .searchAttachmentByPK(new AttachmentPK(field.getValue(), componentId));
                        if (attDetail != null) {
                            fieldValue = attDetail.getLogicalName(getLanguage());
                        }
                    }
                }
                //Field date type
                else if (fieldTemplate.getTypeName().equals("date")) {
                    fieldValue = DateUtil.getOutputDate(fieldValue, "fr");
                }
                //Others fields type
                else {
                    fieldTemplate.setDisplayerName("simpletext");
                    fieldValue = field.getValue(getLanguage());
                }

                cell = new PdfPCell(new Phrase(fieldLabel, fontLabel));
                cell.setBorderWidth(0);
                cell.setPaddingBottom(5);
                tableContent.addCell(cell);

                cell = new PdfPCell(new Phrase(fieldValue, fontValue));
                cell.setBorderWidth(0);
                cell.setPaddingBottom(5);
                tableContent.addCell(cell);
            }

            document.add(tableContent);
        }
    } catch (Exception e) {
        SilverTrace.error("workflowEngine", "SendInKmelia.generatePDFStep()", "root.MSG_GEN_ERROR", e);
    }
}