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

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

Introduction

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

Prototype

public void setTotalWidth(float columnWidth[]) throws DocumentException 

Source Link

Document

Sets the full width of the table from the absolute column width.

Usage

From source file:gov.medicaid.services.util.PDFHelper.java

License:Apache License

/**
 * Sets the given table to take an entire page with.
 *
 * @param table the table to make full width
 *///from   ww w  . j av  a2s. c o m
public static void setTableAsFullPage(PdfPTable table) {
    table.getDefaultCell().setBorder(0);
    table.setTotalWidth(72 * 7);
    table.setLockedWidth(true);
}

From source file:is.idega.idegaweb.egov.printing.business.DocumentBusinessBean.java

License:Open Source License

public void createCommuneFooter(PdfWriter writer) throws Exception {

    PdfContentByte cb = writer.getDirectContent();
    Font nameFont = getDefaultParagraphFont();
    nameFont.setSize(9);//from   ww  w. j a  v  a 2 s .  c o  m
    Font textFont = getDefaultTextFont();
    textFont.setSize(9);

    PdfPTable table = new PdfPTable(4);
    table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
    table.getDefaultCell().setNoWrap(true);

    IWBundle iwb = getIWApplicationContext().getIWMainApplication()
            .getBundle(is.idega.idegaweb.egov.message.business.MessageConstants.IW_BUNDLE_IDENTIFIER);

    table.addCell(new Phrase(iwb.getProperty("commune.name_mailaddr", "Mailaddress"), nameFont));
    table.addCell(new Phrase(iwb.getProperty("commune.name_visitaddr", "Visitaddress"), nameFont));
    table.addCell(new Phrase(iwb.getProperty("commune.name_contact", "Contact"), nameFont));
    table.addCell(new Phrase(iwb.getProperty("commune.name_org_nr", "Organizationsnr"), nameFont));

    table.addCell(new Phrase(iwb.getProperty("commune.mail_name", "Mail name"), getTextFont()));
    table.addCell(new Phrase(iwb.getProperty("commune.visit_name", "Visit name"), textFont));
    table.addCell(new Phrase(iwb.getProperty("commune.website", "www.some-place.com"), textFont));
    table.addCell(new Phrase(iwb.getProperty("commune.org_number", "XXXXXX-XXXX"), textFont));

    table.addCell(new Phrase(iwb.getProperty("commune.mail_zip", "Zip code"), textFont));
    table.addCell(new Phrase(iwb.getProperty("commune.visit_streetaddr", "Street and number,"), textFont));
    table.addCell(new Phrase(iwb.getProperty("commune.support_email", "email@someplace.com"), textFont));
    table.addCell(new Phrase(" ", textFont));

    table.addCell(new Phrase(" ", textFont));
    table.addCell(new Phrase(iwb.getProperty("commune.visit_zip", "Visit zip"), textFont));
    table.addCell(new Phrase(iwb.getProperty("commune.office_phone", "office phone"), textFont));
    table.addCell(new Phrase(" ", textFont));

    int distFromBottomMM = 30;
    int[] widths = { 20, 20, 30, 20 };
    table.setWidths(widths);
    table.setTotalWidth(getPointsFromMM(210 - 25 - 20));
    table.writeSelectedRows(0, -1, getPointsFromMM(25), getPointsFromMM(distFromBottomMM), cb);

    PdfContentByte linebyte = new PdfContentByte(writer);
    // we add some crosses to visualize the destinations

    linebyte.moveTo(getPointsFromMM(25), getPointsFromMM(distFromBottomMM + 2));
    linebyte.lineTo(getPointsFromMM(210 - 25), getPointsFromMM(distFromBottomMM + 2));

    linebyte.stroke();

    // we add the template on different positions
    cb.add(linebyte);
}

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

License:Mozilla Public License

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

    logger.debug("IN");

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

From source file:jdbreport.model.io.pdf.itext2.PdfWriter.java

License:Apache License

private PdfPTable createPdfTable(int columnCount, float[] widths, Rectangle pageSize) throws DocumentException {
    PdfPTable table;
    table = new PdfPTable(columnCount);
    table.setHorizontalAlignment(PdfPTable.ALIGN_LEFT);
    table.setTotalWidth(widths);
    float widthPercentage = table.getTotalWidth() / (pageSize.getRight() - pageSize.getLeft()) * 100f;
    table.setWidthPercentage(widthPercentage);
    return table;
}

From source file:jm.web.Addons.java

License:GNU General Public License

public static void setEncabezado(PdfWriter writer, Document document, String texto) {
    if (writer.getPageNumber() > 1) {
        try {//  ww w .ja  v a2 s . c om
            PdfPTable encabezado = new PdfPTable(1);
            encabezado.setTotalWidth(document.right() - document.left() - 120);
            encabezado.addCell(Addons.setCeldaPDF(texto, Font.HELVETICA, 9, Font.BOLD, Element.ALIGN_LEFT, 0));
            encabezado.writeSelectedRows(0, -1, 60, document.top() + 25, writer.getDirectContent());

            PdfContentByte cb = writer.getDirectContent();
            cb.setLineWidth(2);
            cb.moveTo(60, document.top() + 10);
            cb.lineTo(document.right() - document.left() - 58, document.top() + 10);
        } catch (Exception e) {
            throw new ExceptionConverter(e);
        }
    }
}

From source file:jm.web.Addons.java

License:GNU General Public License

public static void setPie(PdfWriter writer, Document document, String rep_pie) {
    try {//from  w  ww . j a  v a 2 s  .  c  om
        PdfContentByte cb = writer.getDirectContent();
        /*cb.setLineWidth(2);
        cb.moveTo(60, document.bottomMargin()-5);
        cb.lineTo(document.right() - document.left()-70, document.bottomMargin()-5);
        */
        PdfPTable pie = new PdfPTable(1);
        pie.setTotalWidth(document.right() - document.left() - 120);
        pie.addCell(Addons.setCeldaPDF(rep_pie, Font.HELVETICA, 9, Font.BOLD, Element.ALIGN_CENTER, 0));
        pie.addCell(Addons.setCeldaPDF("Pg " + String.valueOf(writer.getPageNumber()), Font.HELVETICA, 9,
                Font.BOLD, Element.ALIGN_RIGHT, 0));
        pie.addCell(Addons.setCeldaPDF(
                "Reporte diseado por: Jorge Mueses Cevallos.      Mvil: 095204832     mail:jorge_mueses@yahoo.com",
                Font.HELVETICA, 5, Font.BOLD, Element.ALIGN_LEFT, 0));
        pie.writeSelectedRows(0, -1, 60, document.bottomMargin() - 10, cb);
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

From source file:net.nosleep.superanalyzer.Share.java

License:Open Source License

public static void saveAnalysisPdf(JFrame window, Analysis analysis, JProgressBar progressBar) {

    File pdfFile = askForFile(window, "pdf");
    if (pdfFile == null)
        return;/*from   w  w w.  ja v a2  s. c  o  m*/

    Misc.printMemoryInfo("pdfstart");

    DateFormat dateFormat = new SimpleDateFormat().getDateInstance(DateFormat.SHORT);
    String infoString = Misc.getString("CREATED_ON") + " "
            + dateFormat.format(Calendar.getInstance().getTime());

    int viewCount = 15;
    int viewsDone = 0;

    progressBar.setMinimum(0);
    progressBar.setMaximum(viewCount);

    Dimension d = new Dimension(500, 400);

    try {

        String tmpPath = System.getProperty("java.io.tmpdir") + "/image.png";

        // create the pdf document object
        Document document = new Document();

        // create a writer that listens to the document
        // and directs a PDF-stream to a file
        PdfWriter.getInstance(document, new FileOutputStream(pdfFile));

        // we open the document
        document.open();

        Font titleFont = FontFactory.getFont(FontFactory.HELVETICA, 18, Font.NORMAL,
                new Color(0x00, 0x00, 0x00));

        Paragraph p = new Paragraph(Misc.getString("MY_MUSIC_COLLECTION"), titleFont);
        p.setSpacingAfter(4);
        document.add(p);

        Font subtitleFont = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL,
                new Color(0x88, 0x88, 0x88));

        p = new Paragraph("The Super Analyzer by Nosleep Software", subtitleFont);
        p.setSpacingAfter(-2);
        document.add(p);

        p = new Paragraph(infoString, subtitleFont);
        p.setSpacingAfter(30);
        document.add(p);

        PdfPTable table = new PdfPTable(2);
        table.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
        table.setTotalWidth(500f);
        table.setLockedWidth(true);

        Font statNameFont = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL,
                new Color(0x66, 0x66, 0x66));

        Font statValueFont = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL,
                new Color(0x00, 0x00, 0x00));

        Vector<StringTriple> statPairs = SummaryView.createStatPairs(analysis);
        Paragraph statParagraph = new Paragraph();

        Font summaryTitleFont = FontFactory.getFont(FontFactory.HELVETICA, 11, Font.BOLD,
                new Color(0x00, 0x00, 0x00));
        Paragraph titleParagraph = new Paragraph(Misc.getString("SUMMARY"), summaryTitleFont);
        statParagraph.add(titleParagraph);

        Paragraph spaceParagraph = new Paragraph("", statNameFont);
        statParagraph.add(spaceParagraph);

        for (int i = 0; i < statPairs.size(); i++) {
            Paragraph statLine = new Paragraph();
            StringTriple triple = statPairs.elementAt(i);
            Phrase namePhrase = new Phrase(triple.Name + ": ", statNameFont);
            Phrase valuePhrase = new Phrase(triple.Value, statValueFont);
            statLine.add(namePhrase);
            statLine.add(valuePhrase);
            statParagraph.add(statLine);
        }
        table.addCell(statParagraph);

        viewsDone++;
        progressBar.setValue(viewsDone);

        GenreView genreView = new GenreView(analysis);
        genreView.saveImage(new File(tmpPath), d);
        genreView = null;

        Image img = Image.getInstance(tmpPath);
        table.addCell(img);

        viewsDone++;
        progressBar.setValue(viewsDone);

        LikesView likesView = new LikesView(analysis);
        likesView.saveImage(new File(tmpPath), d);
        likesView = null;

        img = Image.getInstance(tmpPath);
        table.addCell(img);

        viewsDone++;
        progressBar.setValue(viewsDone);

        YearView yearView = new YearView(analysis);
        yearView.saveImage(new File(tmpPath), d);
        yearView = null;

        img = Image.getInstance(tmpPath);
        table.addCell(img);

        viewsDone++;
        progressBar.setValue(viewsDone);

        RatingView ratingView = new RatingView(analysis);
        ratingView.saveImage(new File(tmpPath), d);
        ratingView = null;

        img = Image.getInstance(tmpPath);
        table.addCell(img);

        viewsDone++;
        progressBar.setValue(viewsDone);

        TimeView timeView = new TimeView(analysis);
        timeView.saveImage(new File(tmpPath), d);
        timeView = null;

        img = Image.getInstance(tmpPath);
        table.addCell(img);

        viewsDone++;
        progressBar.setValue(viewsDone);

        QualityView qualityView = new QualityView(analysis);
        qualityView.saveImage(new File(tmpPath), d);
        qualityView = null;

        img = Image.getInstance(tmpPath);
        table.addCell(img);

        viewsDone++;
        progressBar.setValue(viewsDone);

        PlayCountView playCountView = new PlayCountView(analysis);
        playCountView.saveImage(new File(tmpPath), d);
        playCountView = null;

        img = Image.getInstance(tmpPath);
        table.addCell(img);

        viewsDone++;
        progressBar.setValue(viewsDone);

        MostPlayedAAView mostPlayedAAView = new MostPlayedAAView(analysis);

        mostPlayedAAView.saveImage(new File(tmpPath), d);
        img = Image.getInstance(tmpPath);
        table.addCell(img);

        mostPlayedAAView.saveImageExtra(new File(tmpPath), d);
        img = Image.getInstance(tmpPath);
        table.addCell(img);

        mostPlayedAAView = null;

        viewsDone++;
        progressBar.setValue(viewsDone);

        MostPlayedDGView mostPlayedDGView = new MostPlayedDGView(analysis);

        mostPlayedDGView.saveImage(new File(tmpPath), d);
        img = Image.getInstance(tmpPath);
        table.addCell(img);

        mostPlayedDGView.saveImageExtra(new File(tmpPath), d);
        img = Image.getInstance(tmpPath);
        table.addCell(img);

        mostPlayedDGView = null;

        viewsDone++;
        progressBar.setValue(viewsDone);

        EncodingKindView encodingKindView = new EncodingKindView(analysis);
        encodingKindView.saveImage(new File(tmpPath), d);
        encodingKindView = null;

        img = Image.getInstance(tmpPath);
        table.addCell(img);

        viewsDone++;
        progressBar.setValue(viewsDone);

        GrowthView growthView = new GrowthView(analysis);
        growthView.saveImage(new File(tmpPath), d);
        growthView = null;

        img = Image.getInstance(tmpPath);
        table.addCell(img);

        viewsDone++;
        progressBar.setValue(viewsDone);

        WordView wordView = new WordView(analysis);
        wordView.saveImage(new File(tmpPath), d);
        wordView = null;

        img = Image.getInstance(tmpPath);
        table.addCell(img);

        table.addCell("");

        viewsDone++;
        progressBar.setValue(viewsDone);
        Misc.printMemoryInfo("pdfend");

        document.add(table);

        // step 5: we close the document
        document.close();

    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }
}

From source file:nl.knaw.dans.common.lang.pdf.PdfPageLayouter.java

License:Apache License

public void onEndPage(final PdfWriter writer, final Document document) {
    final float bottom = document.bottom();
    final float centerX = getCenterX(document);
    final PdfContentByte canvas = writer.getDirectContent();
    final int rotation = 0;

    final PdfPTable table = new PdfPTable(5);
    table.setTotalWidth(PAGE_NUMBER_TABLE_WIDTH);
    table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
    table.getDefaultCell().setBorder(0);

    table.addCell(TO_FIRST);//ww w .  j  a v  a 2s.  c  o m
    table.addCell(TO_PREV);
    table.addCell(new Phrase(new Chunk("" + document.getPageNumber(), FONT)));
    table.addCell(TO_NEXT);
    table.addCell(TO_LAST);

    table.writeSelectedRows(0, -1, centerX - (table.getTotalWidth() / 2), bottom - FOOTER_POSITION, canvas);
    if (footerPhrase == null)
        return;
    showTextAligned(canvas, Element.ALIGN_CENTER, new Phrase(footerPhrase), centerX, bottom - FOOTER_POSITION,
            rotation);
}

From source file:org.cgiar.ccafs.ap.summaries.projects.pdf.CaseStudieSummaryPDF.java

License:Open Source License

/**
 * This method is used for add the main information table of project summary
 *///from ww  w . j av  a2 s.  c o  m
private void addMainInformationTable() {

    String startDate, endDate;
    if (project.getStartDate() != null) {
        startDate = new SimpleDateFormat("dd-MM-yyyy").format(project.getStartDate());
    } else {
        startDate = this.messageReturn(null);
    }

    if (project.getEndDate() != null) {
        endDate = new SimpleDateFormat("dd-MM-yyyy").format(project.getEndDate());
    } else {
        endDate = this.messageReturn(null);
    }

    Paragraph cellContent;

    // Add content
    try {
        PdfPTable table = new PdfPTable(4);

        // Set table widths
        table.setLockedWidth(true);
        table.setTotalWidth(480);
        table.setWidths(new int[] { 3, 5, 3, 5 });

        // First row
        cellContent = new Paragraph(this.getText("summaries.project.startDate") + "\n" + " (dd-MM-yyyy)",
                TABLE_BODY_BOLD_FONT);
        this.addTableBodyCell(table, cellContent, Element.ALIGN_RIGHT, 0);

        cellContent = new Paragraph(this.messageReturn(startDate), TABLE_BODY_FONT);
        this.addTableBodyCell(table, cellContent, Element.ALIGN_LEFT, 0);

        cellContent = new Paragraph(this.getText("summaries.project.endDate") + "\n" + " (dd-MM-yyyy)",
                TABLE_BODY_BOLD_FONT);
        this.addTableBodyCell(table, cellContent, Element.ALIGN_RIGHT, 0);

        cellContent = new Paragraph(this.messageReturn(endDate), TABLE_BODY_FONT);
        this.addTableBodyCell(table, cellContent, Element.ALIGN_LEFT, 0);

        // Second row
        cellContent = new Paragraph(this.getText("summaries.project.managementLiaison"), TABLE_BODY_BOLD_FONT);
        this.addTableBodyCell(table, cellContent, Element.ALIGN_RIGHT, 1);

        cellContent = new Paragraph(this.messageReturn(project.getLiaisonInstitution().getAcronym() + " - "
                + project.getLiaisonInstitution().getName()), TABLE_BODY_FONT);
        this.addTableBodyCell(table, cellContent, Element.ALIGN_LEFT, 1);

        cellContent = new Paragraph(this.getText("summaries.project.contactPerson"), TABLE_BODY_BOLD_FONT);
        this.addTableBodyCell(table, cellContent, Element.ALIGN_RIGHT, 1);

        cellContent = new Paragraph(this.messageReturn(project.getOwner().getComposedName()), TABLE_BODY_FONT);
        this.addTableBodyCell(table, cellContent, Element.ALIGN_LEFT, 1);

        // Third row
        cellContent = new Paragraph(this.getText("summaries.project.leadOrganization"), TABLE_BODY_BOLD_FONT);
        this.addTableBodyCell(table, cellContent, Element.ALIGN_RIGHT, 0);
        if (project.getLeader() == null || project.getLeader().getInstitution() == null) {
            cellContent = new Paragraph(this.getText("summaries.project.empty"), TABLE_BODY_FONT);
        } else {
            cellContent = new Paragraph(
                    this.messageReturn(
                            this.messageReturn(project.getLeader().getInstitution().getComposedName())),
                    TABLE_BODY_FONT);

        }
        this.addTableBodyCell(table, cellContent, Element.ALIGN_LEFT, 0);

        cellContent = new Paragraph(this.getText("summaries.project.projectLeader"), TABLE_BODY_BOLD_FONT);
        this.addTableBodyCell(table, cellContent, Element.ALIGN_RIGHT, 0);
        if (project.getLeaderPerson() == null || project.getLeaderPerson().getUser() == null) {
            cellContent = new Paragraph(this.getText("summaries.project.empty"), TABLE_BODY_FONT);
        } else {
            cellContent = new Paragraph(
                    this.messageReturn(project.getLeaderPerson().getUser().getComposedName()), TABLE_BODY_FONT);
        }

        this.addTableBodyCell(table, cellContent, Element.ALIGN_LEFT, 0);

        // Fourth row
        cellContent = (new Paragraph(this.getText("summaries.project.projectType"), TABLE_BODY_BOLD_FONT));
        this.addTableBodyCell(table, cellContent, Element.ALIGN_RIGHT, 1);

        cellContent = new Paragraph(this.messageReturn(project.getType().replaceAll("_", " ")),
                TABLE_BODY_FONT);
        this.addTableBodyCell(table, cellContent, Element.ALIGN_LEFT, 1);

        // Fiveth row
        Chunk imdb = null;
        Font hyperLink = new Font(FontFactory.getFont("openSans", 10, Color.BLUE));
        hyperLink.setStyle(Font.UNDERLINE);

        // -- Not Bilateral
        if (!project.isBilateralProject()) {
            cellContent = (new Paragraph(this.getText("summaries.project.detailed"), TABLE_BODY_BOLD_FONT));
            this.addTableBodyCell(table, cellContent, Element.ALIGN_RIGHT, 1);

            if (project.getWorkplanName() != null && !project.getWorkplanName().equals("")) {
                imdb = new Chunk(project.getWorkplanName(), hyperLink);
                try {
                    imdb.setAction(new PdfAction(new URL(this.messageReturn(project.getWorkplanURL()))));
                } catch (MalformedURLException exp) {
                    imdb = new Chunk(project.getWorkplanName(), TABLE_BODY_FONT);
                    LOG.error("There is an Malformed exception in " + project.getWorkplanName());
                }
            } else {
                imdb = new Chunk(this.getText("summaries.project.empty"), TABLE_BODY_FONT);
            }
        }

        // -- Bilateral
        else {
            cellContent = (new Paragraph(this.getText("summaries.project.ipContributions.proposal.space"),
                    TABLE_BODY_BOLD_FONT));
            this.addTableBodyCell(table, cellContent, Element.ALIGN_RIGHT, 1);

            if (project.getBilateralContractProposalName() != null
                    && !project.getBilateralContractProposalName().equals("")) {
                imdb = new Chunk(project.getBilateralContractProposalName(), hyperLink);
                try {
                    imdb.setAction(new PdfAction(new URL(this.messageReturn(project.getWorkplanURL()))));
                } catch (MalformedURLException exp) {
                    imdb = new Chunk(project.getBilateralContractProposalName(), TABLE_BODY_FONT);
                    LOG.error("There is an Malformed exception in bilateral contract: "
                            + project.getBilateralContractProposalName());
                }
            } else {
                imdb = new Chunk(this.getText("summaries.project.empty"), TABLE_BODY_FONT);
            }
        }

        cellContent = new Paragraph();
        cellContent.add(imdb);
        this.addTableBodyCell(table, cellContent, Element.ALIGN_LEFT, 1);

        document.add(table);
        document.add(Chunk.NEWLINE);
    } catch (DocumentException e) {
        LOG.error(
                "-- generatePdf() > There was an error adding the table with content for case study summary. ",
                e);
    }
}

From source file:org.cgiar.ccafs.ap.summaries.projects.pdf.CaseStudieSummaryPDF.java

License:Open Source License

/**
 * This method is used for add Outcomes in the project summary
 *//*  w ww  .j  a  v  a2  s . c o m*/
private void addProjectOutcomes(String number) {
    try {
        Paragraph outcomesBlock = new Paragraph();
        outcomesBlock.setAlignment(Element.ALIGN_JUSTIFIED);
        Paragraph title = new Paragraph(number + ". " + this.getText("summaries.project.outcome"),
                HEADING2_FONT);
        outcomesBlock.add(title);
        outcomesBlock.add(Chunk.NEWLINE);
        ;
        title = new Paragraph();
        title.setFont(HEADING3_FONT);
        title.add(number + ".1 " + this.getText("summaries.project.outcomeNarrative"));
        outcomesBlock.add(title);
        outcomesBlock.add(Chunk.NEWLINE);
        ;

        // Project outcome statement
        Paragraph body = new Paragraph();
        body.setFont(BODY_TEXT_BOLD_FONT);
        body.add(this.getText("summaries.project.outcomeStatement"));

        // body.setFont(BODY_TEXT_FONT);
        if (project.getOutcomes() == null || project.getOutcomes().get(String.valueOf(midOutcomeYear)) == null
                || project.getOutcomes().get(String.valueOf(midOutcomeYear)).getStatement() == null
                || project.getOutcomes().get(String.valueOf(midOutcomeYear)).getStatement().equals("")) {
            body.add(": ");
            body.setFont(BODY_TEXT_FONT);
            body.add(this.getText("summaries.project.empty"));
        } else {
            body.setFont(BODY_TEXT_FONT);
            body.add(Chunk.NEWLINE);
            body.add(this
                    .messageReturn(project.getOutcomes().get(String.valueOf(midOutcomeYear)).getStatement()));

        }
        body.add(Chunk.NEWLINE);
        ;
        outcomesBlock.add(body);

        try {
            document.newPage();
            // document.add(outcomesBlock);
        } catch (Exception e) {
            LOG.error("There was an error trying to add the project focuses to the project summary pdf", e);
        }

        Anchor anchor;

        ////////////////// Reporting
        PdfPTable table;

        // **********************************************************************************
        // *************************** Outcome Case Studies *************************************
        // **********************************************************************************

        if (project.isReporting()) {
            document.newPage();
            Paragraph cell;

            if (project.getCaseStudies().isEmpty()) {
                document.add(
                        new Paragraph(this.getText("summaries.project.reporting.outcome.not.case.studies")));
            } else {
                title = new Paragraph();
                title.add(Chunk.NEWLINE);
                // document.add(title);
            }
            List<Project> lst = projectManager.getAllProjectsBasicInfo(APConstants.REPORTING_SECTION);
            Collections.sort(lst, new Comparator<Project>() {

                @Override
                public int compare(Project s1, Project s2) {
                    Integer p1 = s1.getId();
                    Integer p2 = s2.getId();
                    return p1.compareTo(p2);
                }
            });
            for (Project project : lst) {
                project = projectManager.getProject(project.getId());
                if (project.isWorkplanRequired()) {
                    String workPlanURL = this.getWorkplanURL();
                    if (workPlanURL != null || project.getWorkplanName() != null) {
                        project.setWorkplanURL(workPlanURL + project.getWorkplanName());
                    }
                }
                // Get a route for the bilateral contract
                if (project.isBilateralProject()) {
                    String bilateralContractURL = this.getBilateralContractURL();
                    if (bilateralContractURL != null || project.getBilateralContractProposalName() != null) {
                        project.setWorkplanURL(
                                bilateralContractURL + project.getBilateralContractProposalName());
                    }
                }

                // Getting the information of the Regions program
                project.setRegions(
                        ipProgramManager.getProjectFocuses(project.getId(), APConstants.REGION_PROGRAM_TYPE));

                // Getting the information of the Flagships program
                project.setFlagships(
                        ipProgramManager.getProjectFocuses(project.getId(), APConstants.FLAGSHIP_PROGRAM_TYPE));

                List<ProjectPartner> projectPartnerList = this.partnerManager.getProjectPartners(project, 0);

                for (ProjectPartner projectPartner : projectPartnerList) {
                    projectPartner
                            .setPartnerPersons(this.partnerPersonManager.getPartnerPersons(projectPartner));
                    projectPartner.setPartnerContributors(
                            partnerManager.getProjectPartnerContributors(projectPartner));
                }
                project.setProjectPartners(projectPartnerList);
                this.project = project;

                List<CasesStudies> caseStudiesList = caseStudiesManager.getCaseStudysByProject(project.getId());

                List<IPIndicator> ipIndicatorList;
                IPIndicator ipIndicator;
                if (caseStudiesList != null) {
                    if (!caseStudiesList.isEmpty()) {
                        try {
                            this.addProjectTitle();
                            this.addMainInformationTable();
                        } catch (Exception e) {
                            System.out.println(project.getId());
                            e.printStackTrace();
                        }
                    }

                    for (CasesStudies caseStudie : caseStudiesList) {
                        ipIndicatorList = new ArrayList<IPIndicator>();
                        for (CaseStudieIndicators indicatorCaseStudie : caseStudie
                                .getCaseStudieIndicatorses()) {
                            ipIndicator = indicatorManager
                                    .getIndicatorFlgship(indicatorCaseStudie.getIdIndicator());
                            ipIndicatorList.add(ipIndicator);
                        }
                        caseStudie.setCaseStudyIndicators(ipIndicatorList);
                    }
                    project.setCaseStudies(caseStudiesList);

                    int counter = 0;
                    for (CasesStudies caseStudy : project.getCaseStudies()) {

                        counter++;
                        table = new PdfPTable(1);
                        table.setLockedWidth(true);
                        table.setTotalWidth(500);

                        // case study
                        cell = new Paragraph(
                                this.getText("summaries.project.reporting.outcome.case.study") + " #" + counter,
                                TABLE_HEADER_FONT);
                        this.addTableHeaderCell(table, cell);
                        // this.addCustomTableCell(table, cell, Element.ALIGN_LEFT, BODY_TEXT_FONT, Color.WHITE,
                        // table.getNumberOfColumns(), 0, false);

                        // Title
                        cell = new Paragraph(
                                this.getText("summaries.project.reporting.outcome.casestudy.title"),
                                TABLE_BODY_BOLD_FONT);
                        cell.setFont(TABLE_BODY_FONT);
                        cell.add(caseStudy.getTitle());
                        this.addTableBodyCell(table, cell, Element.ALIGN_LEFT, 1);

                        // Outcome statement
                        cell = new Paragraph(
                                this.getText("summaries.project.reporting.outcome.casestudy.outcomestatement"),
                                TABLE_BODY_BOLD_FONT);
                        cell.setFont(TABLE_BODY_FONT);
                        cell.add(caseStudy.getOutcomeStatement());
                        this.addTableBodyCell(table, cell, Element.ALIGN_LEFT, 1);

                        // Research outputs
                        cell = new Paragraph(
                                this.getText("summaries.project.reporting.outcome.casestudy.researchoutputs"),
                                TABLE_BODY_BOLD_FONT);
                        cell.setFont(TABLE_BODY_FONT);
                        cell.add(caseStudy.getResearchOutputs());
                        this.addTableBodyCell(table, cell, Element.ALIGN_LEFT, 1);

                        // Research partners
                        cell = new Paragraph(
                                this.getText("summaries.project.reporting.outcome.casestudy.researchPartners"),
                                TABLE_BODY_BOLD_FONT);
                        cell.setFont(TABLE_BODY_FONT);
                        cell.add(caseStudy.getResearchPartners());
                        this.addTableBodyCell(table, cell, Element.ALIGN_LEFT, 1);

                        // activities Contributed
                        cell = new Paragraph(
                                this.getText(
                                        "summaries.project.reporting.outcome.casestudy.activitiesContributed"),
                                TABLE_BODY_BOLD_FONT);
                        cell.setFont(TABLE_BODY_FONT);
                        cell.add(caseStudy.getActivities());
                        this.addTableBodyCell(table, cell, Element.ALIGN_LEFT, 1);

                        // Non Research Partners
                        cell = new Paragraph(
                                this.getText(
                                        "summaries.project.reporting.outcome.casestudy.nonResearchPartners"),
                                TABLE_BODY_BOLD_FONT);
                        cell.setFont(TABLE_BODY_FONT);
                        cell.add(caseStudy.getNonResearchPartneres());
                        this.addTableBodyCell(table, cell, Element.ALIGN_LEFT, 1);

                        // Output Users
                        cell = new Paragraph(
                                this.getText("summaries.project.reporting.outcome.casestudy.outputUsers"),
                                TABLE_BODY_BOLD_FONT);
                        cell.setFont(TABLE_BODY_FONT);
                        cell.add(caseStudy.getOutputUsers());
                        this.addTableBodyCell(table, cell, Element.ALIGN_LEFT, 1);

                        // Output Used
                        cell = new Paragraph(
                                this.getText("summaries.project.reporting.outcome.casestudy.outputWasUsed"),
                                TABLE_BODY_BOLD_FONT);
                        cell.setFont(TABLE_BODY_FONT);
                        cell.add(caseStudy.getOutputUsed());
                        this.addTableBodyCell(table, cell, Element.ALIGN_LEFT, 1);

                        // Evidence
                        cell = new Paragraph(
                                this.getText("summaries.project.reporting.outcome.casestudy.evidenceOutcome"),
                                TABLE_BODY_BOLD_FONT);
                        cell.setFont(TABLE_BODY_FONT);
                        cell.add(caseStudy.getEvidenceOutcome());
                        this.addTableBodyCell(table, cell, Element.ALIGN_LEFT, 1);

                        // References
                        cell = new Paragraph(
                                this.getText("summaries.project.reporting.outcome.casestudy.references"),
                                TABLE_BODY_BOLD_FONT);
                        cell.setFont(TABLE_BODY_FONT);
                        cell.add(caseStudy.getReferencesCase());
                        this.addTableBodyCell(table, cell, Element.ALIGN_LEFT, 1);

                        // Outcome indicators
                        cell = new Paragraph(
                                this.getText("summaries.project.reporting.outcome.casestudy.primaryOutcome",
                                        new String[] { String.valueOf(this.midOutcomeYear) }),
                                TABLE_BODY_BOLD_FONT);
                        cell.setFont(TABLE_BODY_FONT);
                        cell.add("\n");
                        for (IPIndicator _ipIndicator : caseStudy.getCaseStudyIndicators()) {
                            if (_ipIndicator.getOutcome() != null) {
                                cell.add(_ipIndicator.getOutcome().getDescription());
                            }
                            cell.add(" " + _ipIndicator.getDescription() + "\n");
                        }
                        this.addTableBodyCell(table, cell, Element.ALIGN_LEFT, 1);

                        // Explain link
                        cell = new Paragraph(
                                this.getText("summaries.project.reporting.outcome.casestudy.explainLink"),
                                TABLE_BODY_BOLD_FONT);
                        cell.setFont(TABLE_BODY_FONT);
                        cell.add(caseStudy.getExplainIndicatorRelation());
                        this.addTableBodyCell(table, cell, Element.ALIGN_LEFT, 1);

                        // year
                        cell = new Paragraph(this.getText("summaries.project.reporting.outcome.casestudy.year"),
                                TABLE_BODY_BOLD_FONT);
                        cell.setFont(TABLE_BODY_FONT);
                        cell.add(String.valueOf(caseStudy.getYear()));
                        this.addTableBodyCell(table, cell, Element.ALIGN_LEFT, 1);

                        // upload
                        cell = new Paragraph(
                                this.getText("summaries.project.reporting.outcome.casestudy.upload"),
                                TABLE_BODY_BOLD_FONT);
                        cell.setFont(TABLE_BODY_FONT);
                        if (caseStudy.getFile() == null || caseStudy.getFile().equals("")) {
                            cell.add(this.messageReturn(null));
                        } else {
                            anchor = new Anchor(caseStudy.getFile(), TABLE_BODY_FONT_LINK);
                            anchor.setReference(config.getDownloadURL() + "/projects/" + project.getId()
                                    + "/caseStudy/" + caseStudy.getFile());
                            cell.add(anchor);
                        }
                        this.addTableBodyCell(table, cell, Element.ALIGN_LEFT, 1);

                        document.add(table);
                        document.add(new Paragraph(Chunk.NEWLINE));

                    }
                }

                document.newPage();
            }
        }

    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}