Example usage for com.lowagie.text.pdf PdfPCell setBorder

List of usage examples for com.lowagie.text.pdf PdfPCell setBorder

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfPCell setBorder.

Prototype

public void setBorder(int border) 

Source Link

Document

Enables/Disables the border on the specified sides.

Usage

From source file:com.krawler.spring.hrms.printreport.PrintAppraisalReportDAOImp.java

License:Open Source License

public void createPDFPriview(HttpServletRequest request, HttpServletResponse response, JSONArray obj,
        Map<String, String> personalData) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Document document = new Document(PageSize.A4.rotate(), 25, 25, 25, 25);

    PdfWriter writer = null;/*from   w ww. j  av  a 2s  . com*/
    try {
        HashMap<String, Object> requestParams = new HashMap<String, Object>();

        boolean isQuestion = request.getParameter("question").equals("true") ? true : false;
        boolean promotion = request.getParameter("promotion").equals("false") ? false : true;
        Boolean isMyAppraisal = Boolean.parseBoolean(personalData.get("isMyAppraisal"));
        CompanyPreferences companyPreferences = (CompanyPreferences) hibernateTemplate
                .get(CompanyPreferences.class, sessionHandlerImplObj.getCompanyid(request));
        writer = PdfWriter.getInstance(document, baos);
        writer.setPageEvent(new EndPage());
        document.open();
        java.awt.Color tColor = new Color(9, 9, 9);
        //fontSmallBold.setColor(tColor);

        //heading
        PdfPTable headTable = new PdfPTable(1);
        headTable.setTotalWidth(90);
        headTable.setWidthPercentage(100);
        headTable.setSpacingBefore(20);
        PdfPCell headcell = new PdfPCell(
                new Paragraph(fontFamilySelector.process(messageSource.getMessage("hrms.common.AppraisalForm",
                        null, RequestContextUtils.getLocale(request)), FontContext.REGULAR_BOLD_HELVETICA)));
        headcell.setBackgroundColor(new Color(0xEEEEEE));
        headcell.setPadding(5);
        headTable.addCell(headcell);
        document.add(headTable);
        //heading

        //Details
        int flag = 0;
        String appDetailsParam[] = {
                messageSource.getMessage("hrms.performance.appraisal.cycle.name", null,
                        RequestContextUtils.getLocale(request)) + ":  ",
                messageSource.getMessage("hrms.common.employee.name", null,
                        RequestContextUtils.getLocale(request)) + ":  ",
                messageSource.getMessage("hrms.performance.appraisal.cycle.period", null,
                        RequestContextUtils.getLocale(request)) + ":  ",
                messageSource.getMessage("hrms.Masters.Designation", null,
                        RequestContextUtils.getLocale(request)) + ":  ",
                messageSource.getMessage("hrms.performance.performance.rating", null,
                        RequestContextUtils.getLocale(request)) + "*:  " };
        String appDetailsValue[] = { personalData.get("appcycname"), personalData.get("empname"),
                messageSource.getMessage("hrms.common.form", null, RequestContextUtils.getLocale(request))
                        + ": " + personalData.get("startdate") + " "
                        + messageSource.getMessage("hrms.common.to", null,
                                RequestContextUtils.getLocale(request))
                        + ": " + personalData.get("enddate"),
                personalData.get("desgname"), personalData.get("performance") };

        requestParams.clear();
        requestParams.put("companyid", sessionHandlerImplObj.getCompanyid(request));
        requestParams.put("checklink", "promotion");
        if (!hrmsCommonDAOObj.checkModule(requestParams).isSuccessFlag()) {
            flag = 1;
        }

        PdfPTable appDetailsTable = new PdfPTable(2);
        appDetailsTable.setWidthPercentage(100);
        appDetailsTable.setWidths(new float[] { 55, 75 });
        if (isMyAppraisal) {
            flag = 1;
        }

        for (int i = 0; i < (appDetailsParam.length - flag); i++) {
            PdfPCell pcell = new PdfPCell(new Paragraph(
                    fontFamilySelector.process(appDetailsParam[i], FontContext.MEDIUM_BOLD_HELVETICA)));
            pcell.setBorder(0);
            pcell.setPaddingTop(10);
            pcell.setPaddingLeft(15);
            pcell.setPaddingBottom(4);
            pcell.setBorderColor(new Color(0xF2F2F2));
            pcell.setHorizontalAlignment(Element.ALIGN_LEFT);
            pcell.setVerticalAlignment(Element.ALIGN_LEFT);
            appDetailsTable.addCell(pcell);

            PdfPCell pcell1 = new PdfPCell(new Paragraph(
                    fontFamilySelector.process(appDetailsValue[i], FontContext.SMALL_NORMAL_HELVETICA)));
            pcell1.setBorder(0);
            pcell1.setPaddingTop(10);
            pcell1.setPaddingLeft(15);
            pcell1.setPaddingBottom(4);
            pcell1.setBorderColor(new Color(0xF2F2F2));
            pcell1.setHorizontalAlignment(Element.ALIGN_LEFT);
            pcell1.setVerticalAlignment(Element.ALIGN_LEFT);
            appDetailsTable.addCell(pcell1);
        }

        requestParams.clear();
        requestParams.put("companyid", sessionHandlerImplObj.getCompanyid(request));
        requestParams.put("checklink", "overallcomments");
        if (hrmsCommonDAOObj.checkModule(requestParams).isSuccessFlag()) {
            PdfPCell pcell = new PdfPCell(new Paragraph(fontFamilySelector.process(
                    (isMyAppraisal
                            ? messageSource.getMessage("hrms.performance.self.overall.comment", null,
                                    RequestContextUtils.getLocale(request)) + ":  "
                            : messageSource.getMessage("hrms.performance.overall.appraiser.comments", null,
                                    RequestContextUtils.getLocale(request)) + ":  "),
                    FontContext.MEDIUM_BOLD_HELVETICA)));
            pcell.setBorder(0);
            pcell.setPaddingTop(10);
            pcell.setPaddingLeft(15);
            pcell.setPaddingBottom(4);
            pcell.setBorderColor(new Color(0xF2F2F2));
            pcell.setHorizontalAlignment(Element.ALIGN_LEFT);
            pcell.setVerticalAlignment(Element.ALIGN_LEFT);
            appDetailsTable.addCell(pcell);

            PdfPCell pcell1 = new PdfPCell(new Paragraph(fontFamilySelector.process(
                    (isMyAppraisal ? personalData.get("selfcomment") : personalData.get("empcomment")),
                    FontContext.SMALL_NORMAL_HELVETICA)));
            pcell1.setBorder(0);
            pcell1.setPaddingTop(10);
            pcell1.setPaddingLeft(15);
            pcell1.setPaddingBottom(4);
            pcell1.setBorderColor(new Color(0xF2F2F2));
            pcell1.setHorizontalAlignment(Element.ALIGN_LEFT);
            pcell1.setVerticalAlignment(Element.ALIGN_LEFT);
            appDetailsTable.addCell(pcell1);
        }

        requestParams.clear();
        requestParams.put("companyid", sessionHandlerImplObj.getCompanyid(request));
        requestParams.put("checklink", "promotion");
        if (!isMyAppraisal && hrmsCommonDAOObj.checkModule(requestParams).isSuccessFlag()) {
            PdfPCell pcell = new PdfPCell(new Paragraph(fontFamilySelector.process(
                    messageSource.getMessage("hrms.performance.promotion.recommendation", null,
                            RequestContextUtils.getLocale(request)) + ":  ",
                    FontContext.MEDIUM_BOLD_HELVETICA)));
            pcell.setBorder(0);
            pcell.setPaddingTop(10);
            pcell.setPaddingLeft(15);
            pcell.setPaddingBottom(4);
            pcell.setBorderColor(new Color(0xF2F2F2));
            pcell.setHorizontalAlignment(Element.ALIGN_LEFT);
            pcell.setVerticalAlignment(Element.ALIGN_LEFT);
            appDetailsTable.addCell(pcell);

            PdfPCell pcell1 = new PdfPCell(new Paragraph(fontFamilySelector.process(
                    (promotion
                            ? messageSource.getMessage("hrms.MasterData.Yes", null,
                                    RequestContextUtils.getLocale(request))
                            : messageSource.getMessage("hrms.MasterData.No", null,
                                    RequestContextUtils.getLocale(request))),
                    FontContext.SMALL_NORMAL_HELVETICA)));
            pcell1.setBorder(0);
            pcell1.setPaddingTop(10);
            pcell1.setPaddingLeft(15);
            pcell1.setPaddingBottom(4);
            pcell1.setBorderColor(new Color(0xF2F2F2));
            pcell1.setHorizontalAlignment(Element.ALIGN_LEFT);
            pcell1.setVerticalAlignment(Element.ALIGN_LEFT);
            appDetailsTable.addCell(pcell1);
        }

        if (promotion && !isMyAppraisal && hrmsCommonDAOObj.checkModule(requestParams).isSuccessFlag()) {
            String[] appDetaisPromotionParam = {
                    messageSource.getMessage("hrms.performance.new.department", null,
                            RequestContextUtils.getLocale(request)) + ":  ",
                    messageSource.getMessage("hrms.performance.new.designation", null,
                            RequestContextUtils.getLocale(request)) + ":  ",
                    messageSource.getMessage("hrms.performance.salary.increment", null,
                            RequestContextUtils.getLocale(request)) + "(%):  " };
            String[] appDetaisPromotionValue = {
                    personalData.get("newDept") != null ? personalData.get("newDept") : "",
                    personalData.get("newDesig") != null ? personalData.get("newDesig") : "",
                    personalData.get("salInc") != null ? personalData.get("salInc") : "" };
            for (int i = 0; i < appDetaisPromotionParam.length; i++) {
                PdfPCell pcell = new PdfPCell(new Paragraph(fontFamilySelector
                        .process(appDetaisPromotionParam[i], FontContext.MEDIUM_BOLD_HELVETICA)));
                pcell.setBorder(0);
                pcell.setPaddingTop(10);
                pcell.setPaddingLeft(15);
                pcell.setPaddingBottom(4);
                pcell.setBorderColor(new Color(0xF2F2F2));
                pcell.setHorizontalAlignment(Element.ALIGN_LEFT);
                pcell.setVerticalAlignment(Element.ALIGN_LEFT);
                appDetailsTable.addCell(pcell);

                PdfPCell pcell1 = new PdfPCell(new Paragraph(fontFamilySelector
                        .process(appDetaisPromotionValue[i], FontContext.SMALL_NORMAL_HELVETICA)));
                pcell1.setBorder(0);
                pcell1.setPaddingTop(10);
                pcell1.setPaddingLeft(15);
                pcell1.setPaddingBottom(4);
                pcell1.setBorderColor(new Color(0xF2F2F2));
                pcell1.setHorizontalAlignment(Element.ALIGN_LEFT);
                pcell1.setVerticalAlignment(Element.ALIGN_LEFT);
                appDetailsTable.addCell(pcell1);
            }
        }
        document.add(appDetailsTable);
        //Details

        //Comp
        requestParams.clear();
        requestParams.put("companyid", sessionHandlerImplObj.getCompanyid(request));
        requestParams.put("checklink", "competency");
        if (hrmsCommonDAOObj.checkModule(requestParams).isSuccessFlag()) {
            try {
                if (!isQuestion) {
                    JSONArray jsonComp = obj.getJSONArray(0);
                    if (!isMyAppraisal) {
                        String[] compParam = {
                                messageSource.getMessage("hrms.performance.competency", null,
                                        RequestContextUtils.getLocale(request)),
                                messageSource.getMessage("hrms.performance.competency.description", null,
                                        RequestContextUtils.getLocale(request)),
                                messageSource.getMessage("hrms.performance.weightage", null,
                                        RequestContextUtils.getLocale(request)),
                                messageSource.getMessage("hrms.performance.appraiser.rating", null,
                                        RequestContextUtils.getLocale(request)),
                                messageSource.getMessage("hrms.performance.appraiser.comment", null,
                                        RequestContextUtils.getLocale(request)) };
                        String[] colParam = { "cmptname", "cmptdesc", "cmptwt", "manrat", "mancompcomment" };
                        PdfPTable questionTable = null;
                        if (companyPreferences.isWeightage()) {
                            questionTable = new PdfPTable(5);
                            questionTable.setWidths(new float[] { 50, 60, 30, 30, 42 });
                        } else {
                            questionTable = new PdfPTable(4);
                            questionTable.setWidths(new float[] { 50, 60, 30, 42 });
                        }
                        questionTable.setWidthPercentage(100);
                        questionTable.setSpacingBefore(20);
                        questionTable.setHeaderRows(1);
                        for (int i = 0; i < compParam.length; i++) {
                            if (!(!companyPreferences.isWeightage() && i == 2)) {
                                PdfPCell pgcell = new PdfPCell(new Paragraph(fontFamilySelector
                                        .process(compParam[i], FontContext.MEDIUM_BOLD_HELVETICA)));
                                pgcell.setBorder(0);
                                pgcell.setBorder(PdfPCell.BOX);
                                pgcell.setPadding(4);
                                pgcell.setBorderColor(Color.GRAY);
                                pgcell.setHorizontalAlignment(Element.ALIGN_CENTER);
                                questionTable.addCell(pgcell);
                            }
                        }

                        for (int i = 0; i < jsonComp.length(); i++) {
                            for (int j = 0; j < colParam.length; j++) {
                                if (!(!companyPreferences.isWeightage() && j == 2)) {
                                    PdfPCell pcell = null;
                                    if (j != 3)
                                        pcell = new PdfPCell(
                                                new Paragraph(fontFamilySelector.process(
                                                        jsonComp.getJSONObject(i).has(colParam[j]) ? jsonComp
                                                                .getJSONObject(i).getString(colParam[j]) : "",
                                                        FontContext.SMALL_NORMAL_HELVETICA)));
                                    else {
                                        pcell = new PdfPCell(new Paragraph(fontFamilySelector.process(
                                                jsonComp.getJSONObject(i).has(colParam[j])
                                                        ? (jsonComp.getJSONObject(i).getString(colParam[j])
                                                                .equals("0")
                                                                        ? ""
                                                                        : jsonComp.getJSONObject(i)
                                                                                .getString(colParam[j]))
                                                        : "",
                                                FontContext.SMALL_NORMAL_HELVETICA)));
                                    }
                                    pcell.setBorder(PdfPCell.BOTTOM | PdfPCell.LEFT | PdfPCell.RIGHT);
                                    pcell.setBorderColor(Color.GRAY);
                                    pcell.setPadding(4);
                                    pcell.setHorizontalAlignment(Element.ALIGN_CENTER);
                                    pcell.setVerticalAlignment(Element.ALIGN_CENTER);
                                    questionTable.addCell(pcell);
                                }
                            }
                        }
                        document.add(questionTable);
                    } else {
                        String[] compParam = {
                                messageSource.getMessage("hrms.performance.competency", null,
                                        RequestContextUtils.getLocale(request)),
                                messageSource.getMessage("hrms.performance.competency.description", null,
                                        RequestContextUtils.getLocale(request)),
                                messageSource.getMessage("hrms.performance.weightage", null,
                                        RequestContextUtils.getLocale(request)),
                                messageSource.getMessage("hrms.performance.self.rating", null,
                                        RequestContextUtils.getLocale(request)),
                                messageSource.getMessage("hrms.performance.self.comments", null,
                                        RequestContextUtils.getLocale(request)) };
                        String[] colParam = { "cmptname", "cmptdesc", "cmptwt", "emprat", "empcompcomment" };
                        PdfPTable questionTable = null;
                        if (companyPreferences.isWeightage()) {
                            questionTable = new PdfPTable(5);
                            questionTable.setWidths(new float[] { 50, 60, 30, 30, 42 });
                        } else {
                            questionTable = new PdfPTable(4);
                            questionTable.setWidths(new float[] { 50, 60, 30, 42 });
                        }
                        questionTable.setWidthPercentage(100);
                        questionTable.setSpacingBefore(20);
                        questionTable.setHeaderRows(1);
                        for (int i = 0; i < compParam.length; i++) {
                            if (!(!companyPreferences.isWeightage() && i == 2)) {
                                PdfPCell pgcell = new PdfPCell(new Paragraph(fontFamilySelector
                                        .process(compParam[i], FontContext.MEDIUM_BOLD_HELVETICA)));
                                pgcell.setBorder(0);
                                pgcell.setBorder(PdfPCell.BOX);
                                pgcell.setPadding(4);
                                pgcell.setBorderColor(Color.GRAY);
                                pgcell.setHorizontalAlignment(Element.ALIGN_CENTER);
                                questionTable.addCell(pgcell);
                            }
                        }

                        for (int i = 0; i < jsonComp.length(); i++) {
                            for (int j = 0; j < colParam.length; j++) {
                                if (!(!companyPreferences.isWeightage() && j == 2)) {
                                    PdfPCell pcell;
                                    if (j != 3)
                                        pcell = new PdfPCell(
                                                new Paragraph(fontFamilySelector.process(
                                                        jsonComp.getJSONObject(i).has(colParam[j]) ? jsonComp
                                                                .getJSONObject(i).getString(colParam[j]) : "",
                                                        FontContext.SMALL_NORMAL_HELVETICA)));
                                    else
                                        pcell = new PdfPCell(new Paragraph(fontFamilySelector.process(
                                                jsonComp.getJSONObject(i).has(colParam[j])
                                                        ? (jsonComp.getJSONObject(i).getString(colParam[j])
                                                                .equals("0")
                                                                        ? ""
                                                                        : jsonComp.getJSONObject(i)
                                                                                .getString(colParam[j]))
                                                        : "",
                                                FontContext.SMALL_NORMAL_HELVETICA)));
                                    pcell.setBorder(PdfPCell.BOTTOM | PdfPCell.LEFT | PdfPCell.RIGHT);
                                    pcell.setBorderColor(Color.GRAY);
                                    pcell.setPadding(4);
                                    pcell.setHorizontalAlignment(Element.ALIGN_CENTER);
                                    pcell.setVerticalAlignment(Element.ALIGN_CENTER);
                                    questionTable.addCell(pcell);
                                }
                            }
                        }
                        document.add(questionTable);
                    }
                } else {//Questions
                    try {
                        JSONArray jsonQues = obj.getJSONArray(1);
                        JSONArray jsonAnsTemp = obj.getJSONArray(2);
                        JSONArray jsonAns = new JSONArray();

                        PdfPTable quesMainTable = new PdfPTable(1);
                        quesMainTable.setTotalWidth(90);
                        quesMainTable.setWidthPercentage(100);
                        quesMainTable.setSpacingBefore(20);
                        quesMainTable.setSkipFirstHeader(true);
                        PdfPCell quesHeadcell = new PdfPCell(new Paragraph(fontFamilySelector.process(
                                messageSource.getMessage("hrms.performance.qualitative.appraisal", null,
                                        RequestContextUtils.getLocale(request)),
                                FontContext.MEDIUM_BOLD_HELVETICA)));
                        quesHeadcell.setPadding(5);
                        quesMainTable.addCell(quesHeadcell);
                        document.add(quesMainTable);

                        PdfPTable[] quesTable = new PdfPTable[jsonQues.length()];

                        try {
                            for (int i = 0; i < jsonQues.length(); i++) {
                                String qid = (String) jsonQues.getJSONObject(i).get("qdescription");
                                for (int j = 0; j < jsonAnsTemp.length(); j++) {
                                    try {
                                        if (qid.equals((String) jsonAnsTemp.getJSONObject(j).get("question"))) {
                                            jsonAns.put(jsonAnsTemp.getJSONObject(j));
                                            break;
                                        }
                                    } catch (JSONException e) {
                                        jsonAns.put("");
                                    }
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        for (int i = 0; i < jsonQues.length(); i++) {
                            quesTable[i] = new PdfPTable(2);
                            quesTable[i].setWidthPercentage(90);
                            quesTable[i].setWidths(new float[] { 10, 80 });
                            quesTable[i].setSpacingBefore(20);
                            quesTable[i].setHeaderRows(1);

                            PdfPCell pgcell1 = new PdfPCell(new Paragraph(fontFamilySelector.process(
                                    messageSource.getMessage("hrms.performance.que", null,
                                            RequestContextUtils.getLocale(request)) + ".",
                                    FontContext.SMALL_NORMAL_HELVETICA)));
                            pgcell1.setBorder(0);
                            pgcell1.setBorder(PdfPCell.BOX);
                            pgcell1.setPadding(4);
                            pgcell1.setHorizontalAlignment(Element.ALIGN_CENTER);
                            quesTable[i].addCell(pgcell1);

                            PdfPCell pgcell2 = new PdfPCell(
                                    new Paragraph(
                                            fontFamilySelector
                                                    .process(
                                                            jsonQues.getJSONObject(i).has("qdesc") ? jsonQues
                                                                    .getJSONObject(i).getString("qdesc") : "",
                                                            FontContext.SMALL_NORMAL_HELVETICA)));
                            pgcell2.setBorder(0);
                            pgcell2.setBorder(PdfPCell.BOX);
                            pgcell2.setPadding(4);
                            pgcell2.setHorizontalAlignment(Element.ALIGN_LEFT);
                            quesTable[i].addCell(pgcell2);

                            int cnt = 0;
                            try {
                                cnt = jsonQues.getJSONObject(i).has("qans")
                                        ? Integer.parseInt(jsonQues.getJSONObject(i).getString("qans"))
                                        : 0;
                            } catch (NumberFormatException e) {
                                e.printStackTrace();
                            }
                            if (jsonAns.length() > 0) {
                                JSONArray arr = jsonAns.getJSONObject(i).getJSONArray("answer");
                                for (int j = 0; j < arr.length(); j++) {
                                    PdfPCell pcell1 = new PdfPCell(new Paragraph(fontFamilySelector
                                            .process((j + 1) + "", FontContext.SMALL_NORMAL_HELVETICA)));
                                    pcell1.setBorder(PdfPCell.BOTTOM | PdfPCell.LEFT | PdfPCell.RIGHT);
                                    pcell1.setBorderColor(Color.GRAY);
                                    pcell1.setPadding(4);
                                    pcell1.setHorizontalAlignment(Element.ALIGN_CENTER);
                                    pcell1.setVerticalAlignment(Element.ALIGN_CENTER);
                                    quesTable[i].addCell(pcell1);

                                    PdfPCell pcell2 = new PdfPCell(new Paragraph(fontFamilySelector.process(
                                            arr.getJSONObject(j).getString("" + j + ""),
                                            FontContext.SMALL_NORMAL_HELVETICA)));
                                    pcell2.setBorder(PdfPCell.BOTTOM | PdfPCell.LEFT | PdfPCell.RIGHT);
                                    pcell2.setBorderColor(Color.GRAY);
                                    pcell2.setPadding(4);
                                    pcell2.setHorizontalAlignment(Element.ALIGN_LEFT);
                                    pcell2.setVerticalAlignment(Element.ALIGN_CENTER);
                                    quesTable[i].addCell(pcell2);
                                }
                            } else {
                                for (int j = 0; j < cnt; j++) {
                                    PdfPCell pcell1 = new PdfPCell(new Paragraph(fontFamilySelector
                                            .process((j + 1) + "", FontContext.SMALL_NORMAL_HELVETICA)));
                                    pcell1.setBorder(PdfPCell.BOTTOM | PdfPCell.LEFT | PdfPCell.RIGHT);
                                    pcell1.setBorderColor(Color.GRAY);
                                    pcell1.setPadding(4);
                                    pcell1.setHorizontalAlignment(Element.ALIGN_CENTER);
                                    pcell1.setVerticalAlignment(Element.ALIGN_CENTER);
                                    quesTable[i].addCell(pcell1);

                                    PdfPCell pcell = new PdfPCell(new Paragraph(fontFamilySelector.process("",
                                            FontContext.SMALL_NORMAL_HELVETICA)));
                                    pcell.setBorder(PdfPCell.BOTTOM | PdfPCell.LEFT | PdfPCell.RIGHT);
                                    pcell.setBorderColor(Color.GRAY);
                                    pcell.setPadding(4);
                                    pcell.setHorizontalAlignment(Element.ALIGN_CENTER);
                                    pcell.setVerticalAlignment(Element.ALIGN_CENTER);
                                    quesTable[i].addCell(pcell);
                                }
                            }
                            PdfPCell pcell = new PdfPCell(new Paragraph(
                                    fontFamilySelector.process(" ", FontContext.SMALL_NORMAL_HELVETICA)));
                            pcell.setBorder(PdfPCell.BOTTOM | PdfPCell.LEFT | PdfPCell.RIGHT);
                            pcell.setBorderColor(Color.GRAY);
                            pcell.setPadding(4);
                            pcell.setHorizontalAlignment(Element.ALIGN_CENTER);
                            pcell.setVerticalAlignment(Element.ALIGN_CENTER);
                            //questionTable.addCell(pcell);

                            document.add(quesTable[i]);
                        }
                        //document.add(questionTable);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        //Comp

        //Goals
        requestParams.clear();
        requestParams.put("companyid", sessionHandlerImplObj.getCompanyid(request));
        requestParams.put("checklink", "goal");
        if (hrmsCommonDAOObj.checkModule(requestParams).isSuccessFlag()) {
            try {
                JSONArray jsonGoals = obj.getJSONArray(3);
                if (!isMyAppraisal) {
                    String goalParam[] = {
                            messageSource.getMessage("hrms.performance.goals", null,
                                    RequestContextUtils.getLocale(request)),
                            messageSource.getMessage("hrms.performance.percent.completed", null,
                                    RequestContextUtils.getLocale(request)),
                            messageSource.getMessage("hrms.performance.goal.weightage", null,
                                    RequestContextUtils.getLocale(request)),
                            messageSource.getMessage("hrms.performance.appraiser.rating", null,
                                    RequestContextUtils.getLocale(request)),
                            messageSource.getMessage("hrms.performance.appraiser.comment", null,
                                    RequestContextUtils.getLocale(request)) };
                    String colHeader[] = { "gname", "gcomplete", "gwth", "gmanrat", "mangoalcomment" };
                    PdfPTable goalTable = null;
                    if (companyPreferences.isWeightage()) {
                        goalTable = new PdfPTable(5);
                        goalTable.setWidths(new float[] { 50, 60, 30, 30, 42 });
                    } else {
                        goalTable = new PdfPTable(4);
                        goalTable.setWidths(new float[] { 50, 60, 30, 42 });
                    }
                    goalTable.setWidthPercentage(100);
                    goalTable.setSpacingBefore(20);
                    goalTable.setHeaderRows(1);
                    for (int i = 0; i < goalParam.length; i++) {
                        if (!(!companyPreferences.isWeightage() && i == 2)) {
                            PdfPCell pgcell = new PdfPCell(new Paragraph(fontFamilySelector
                                    .process(goalParam[i], FontContext.MEDIUM_BOLD_HELVETICA)));
                            pgcell.setBorder(0);
                            pgcell.setBorder(PdfPCell.BOX);
                            pgcell.setPadding(4);
                            pgcell.setBorderColor(Color.GRAY);
                            pgcell.setHorizontalAlignment(Element.ALIGN_CENTER);
                            goalTable.addCell(pgcell);
                        }
                    }

                    for (int i = 0; i < jsonGoals.length(); i++) {
                        for (int j = 0; j < colHeader.length; j++) {
                            if (!(!companyPreferences.isWeightage() && j == 2)) {
                                PdfPCell pcell;
                                if (j != 3)
                                    pcell = new PdfPCell(
                                            new Paragraph(
                                                    fontFamilySelector
                                                            .process(
                                                                    jsonGoals.getJSONObject(i).has(colHeader[j])
                                                                            ? jsonGoals.getJSONObject(i)
                                                                                    .getString(colHeader[j])
                                                                            : "",
                                                                    FontContext.SMALL_NORMAL_HELVETICA)));
                                else
                                    pcell = new PdfPCell(new Paragraph(fontFamilySelector.process(
                                            jsonGoals.getJSONObject(i).has(colHeader[j])
                                                    ? (jsonGoals.getJSONObject(i).getString(colHeader[j])
                                                            .equals("0")
                                                                    ? ""
                                                                    : jsonGoals.getJSONObject(i)
                                                                            .getString(colHeader[j]))
                                                    : "",
                                            FontContext.SMALL_NORMAL_HELVETICA)));
                                pcell.setBorder(PdfPCell.BOTTOM | PdfPCell.LEFT | PdfPCell.RIGHT);
                                pcell.setBorderColor(Color.GRAY);
                                pcell.setPadding(4);
                                pcell.setHorizontalAlignment(Element.ALIGN_CENTER);
                                pcell.setVerticalAlignment(Element.ALIGN_CENTER);
                                goalTable.addCell(pcell);
                            }
                        }
                    }
                    document.add(goalTable);
                } else {
                    String goalParam[] = {
                            messageSource.getMessage("hrms.performance.goals", null,
                                    RequestContextUtils.getLocale(request)),
                            messageSource.getMessage("hrms.performance.percent.completed", null,
                                    RequestContextUtils.getLocale(request)),
                            messageSource.getMessage("hrms.performance.goal.weightage", null,
                                    RequestContextUtils.getLocale(request)),
                            messageSource.getMessage("hrms.performance.self.rating", null,
                                    RequestContextUtils.getLocale(request)),
                            messageSource.getMessage("hrms.performance.self.comments", null,
                                    RequestContextUtils.getLocale(request)),
                            messageSource.getMessage("hrms.common.assigned.by", null,
                                    RequestContextUtils.getLocale(request)) };
                    String colHeader[] = { "gname", "gcomplete", "gwth", "gemprat", "empgoalcomment",
                            "assignedby" };
                    PdfPTable goalTable = null;
                    if (companyPreferences.isWeightage()) {
                        goalTable = new PdfPTable(6);
                        goalTable.setWidths(new float[] { 50, 60, 30, 50, 42, 60 });
                    } else {
                        goalTable = new PdfPTable(5);
                        goalTable.setWidths(new float[] { 50, 60, 50, 42, 60 });
                    }
                    goalTable.setWidthPercentage(100);
                    goalTable.setSpacingBefore(20);
                    goalTable.setHeaderRows(1);
                    for (int i = 0; i < goalParam.length; i++) {
                        if (!(!companyPreferences.isWeightage() && i == 2)) {
                            PdfPCell pgcell = new PdfPCell(new Paragraph(fontFamilySelector
                                    .process(goalParam[i], FontContext.MEDIUM_BOLD_HELVETICA)));
                            pgcell.setBorder(0);
                            pgcell.setBorder(PdfPCell.BOX);
                            pgcell.setPadding(4);
                            pgcell.setBorderColor(Color.GRAY);
                            pgcell.setHorizontalAlignment(Element.ALIGN_CENTER);
                            goalTable.addCell(pgcell);
                        }
                    }

                    for (int i = 0; i < jsonGoals.length(); i++) {
                        for (int j = 0; j < colHeader.length; j++) {
                            if (!(!companyPreferences.isWeightage() && j == 2)) {
                                PdfPCell pcell;
                                if (j != 3)
                                    pcell = new PdfPCell(
                                            new Paragraph(
                                                    fontFamilySelector
                                                            .process(
                                                                    jsonGoals.getJSONObject(i).has(colHeader[j])
                                                                            ? jsonGoals.getJSONObject(i)
                                                                                    .getString(colHeader[j])
                                                                            : "",
                                                                    FontContext.SMALL_NORMAL_HELVETICA)));
                                else
                                    pcell = new PdfPCell(new Paragraph(fontFamilySelector.process(
                                            jsonGoals.getJSONObject(i).has(colHeader[j])
                                                    ? (jsonGoals.getJSONObject(i).getString(colHeader[j])
                                                            .equals("0")
                                                                    ? ""
                                                                    : jsonGoals.getJSONObject(i)
                                                                            .getString(colHeader[j]))
                                                    : "",
                                            FontContext.SMALL_NORMAL_HELVETICA)));
                                pcell.setBorder(PdfPCell.BOTTOM | PdfPCell.LEFT | PdfPCell.RIGHT);
                                pcell.setBorderColor(Color.GRAY);
                                pcell.setPadding(4);
                                pcell.setHorizontalAlignment(Element.ALIGN_CENTER);
                                pcell.setVerticalAlignment(Element.ALIGN_CENTER);
                                goalTable.addCell(pcell);
                            }
                        }
                    }
                    document.add(goalTable);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        //Goals

        document.newPage();
        document.close();
        response.setHeader("Content-Disposition", "attachment; filename=\"" + "App_Form" + ".pdf\"");
        response.setContentType("application/octet-stream");
        response.setContentLength(baos.size());
        response.getOutputStream().write(baos.toByteArray());
    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        writer.close();
    }
}

From source file:com.prime.location.billing.InvoicedBillingManager.java

/**
 * Print invoice/*from ww  w. j  ava2 s .c  om*/
 */
public void printInvoice() {
    try { //catch better your exceptions, this is just an example
        FacesContext context = FacesContext.getCurrentInstance();

        Document pdf = new Document(PageSize.A4, 5f, 5f, 75f, 45f);

        String fileName = "PDFFile";

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(pdf, baos);
        TableHeader event = new TableHeader();
        event.setHeader("Header Here");
        writer.setPageEvent(event);

        if (!pdf.isOpen()) {
            pdf.open();
        }

        PdfPCell cell;

        PdfPTable header = new PdfPTable(new float[] { 1, 2, 1 });
        cell = new PdfPCell(new Paragraph("INVOICE",
                FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLDITALIC, Color.BLACK)));
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setColspan(3);
        cell.setBorder(Rectangle.NO_BORDER);
        header.addCell(cell);
        header.setTotalWidth(527);
        header.setLockedWidth(true);

        cell = new PdfPCell(new Phrase("Agency: " + selectedAgency.getDescription()));
        cell.setColspan(2);
        cell.setBorder(Rectangle.NO_BORDER);
        header.addCell(cell);

        cell = new PdfPCell(new Phrase("Invoice#: " + selectedInvoice.getId()));
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        header.addCell(cell);

        cell = new PdfPCell(
                new Phrase("Date: " + DateUtility.dateTimeFormat(selectedInvoice.getInvoiceDate())));
        cell.setColspan(3);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        header.addCell(cell);

        pdf.add(header);

        PdfPTable table = new PdfPTable(new float[] { 1, 3, 2, 1 });
        table.setSpacingBefore(15f);

        table.setTotalWidth(527);
        table.setLockedWidth(true);
        //table.setWidths(new int[]{3, 1, 1});

        table.getDefaultCell().setBackgroundColor(Color.LIGHT_GRAY);

        table.addCell("Date");
        table.addCell("Name");
        table.addCell("Service");
        table.addCell("Rate");

        table.getDefaultCell().setBackgroundColor(null);

        cell = new PdfPCell(new Phrase("Total(US$): "));
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setColspan(3);
        cell.setBackgroundColor(Color.LIGHT_GRAY);
        table.addCell(cell);

        cell = new PdfPCell(new Phrase(new DecimalFormat("###,###.###").format(selectedInvoice.getAmount())));
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setBackgroundColor(Color.LIGHT_GRAY);
        table.addCell(cell);

        // There are three special rows
        table.setHeaderRows(2);
        // One of them is a footer
        table.setFooterRows(1);
        Font f = FontFactory.getFont(FontFactory.HELVETICA, 10);
        //add remaining
        for (AgencyBilling billing : selectedInvoice.getBillings()) {
            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
            table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.getDefaultCell().setIndent(2);
            table.getDefaultCell().setFixedHeight(20);

            table.addCell(new Phrase(DateUtility.dateFormat(billing.getBillingDate()), f));
            table.addCell(new Phrase(billing.getPerson().getName(), f));
            table.addCell(new Phrase(billing.getTariff().getTariffType().getDescription(), f));
            cell = new PdfPCell(new Phrase(new DecimalFormat("###,###.###").format(billing.getRate()), f));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

            table.addCell(cell);

        }

        pdf.add(table);

        writer.getAcroForm().setNeedAppearances(true);

        //document.add(new Phrase(TEXT));
        //Keep modifying your pdf file (add pages and more)
        pdf.close();

        writePDFToResponse(context.getExternalContext(), baos, fileName);

        context.responseComplete();

    } catch (Exception e) {
        //e.printStackTrace();          
    }
}

From source file:com.prime.report.template.TableHeader.java

/**
 * Adds a header to every page//  w  w w .j a  v  a  2s.  c  o m
 *
 * @param writer
 * @param document
 * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(
 * com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
 */
@Override
public void onEndPage(PdfWriter writer, Document document) {

    PdfPTable table = new PdfPTable(4);
    try {
        table.setWidths(new int[] { 10, 11, 9, 1 });
        table.setTotalWidth(527);
        table.setLockedWidth(true);
        table.getDefaultCell().setFixedHeight(20);
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);

        String logoPath = "/resources/image/logo.png";
        ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext();
        String logo = servletContext.getRealPath(logoPath);
        Image img = Image.getInstance(logo);

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

        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(new Phrase("New South West Facility Center",
                FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLDITALIC, Color.BLACK)));
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
        table.addCell(String.format("Page %d of", writer.getPageNumber()));
        PdfPCell cell = new PdfPCell(Image.getInstance(total));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
        table.writeSelectedRows(0, -1, 34, 803, writer.getDirectContent());
    } catch (DocumentException de) {
        throw new ExceptionConverter(de);
    } catch (IOException ex) {
        Logger.getLogger(TableHeader.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.qcadoo.mes.workPlans.pdf.document.WorkPlanPdfForDivision.java

License:Open Source License

private void addWorkPlanTitle(Document document, Entity workPlan, String title, Locale locale)
        throws DocumentException {

    PdfPTable headerTable = pdfHelper.createPanelTable(2);

    PdfPCell titleCell = new PdfPCell();
    titleCell.setBorder(Rectangle.NO_BORDER);
    Paragraph workPlanTitle = new Paragraph(
            new Phrase(getWorkPlanTitle(locale), FontUtils.getDejavuBold11Light()));
    workPlanTitle.add(new Phrase(" " + getWorkPlanName(workPlan), FontUtils.getDejavuBold11Dark()));
    titleCell.addElement(workPlanTitle);

    PdfPCell divisionCell = new PdfPCell();
    divisionCell.setBorder(Rectangle.NO_BORDER);
    Paragraph divisionTitle = new Paragraph(
            new Phrase(getDivisionTitle(locale), FontUtils.getDejavuBold11Light()));
    divisionTitle.add(new Phrase(" " + getDivisionFromTitle(title, locale), FontUtils.getDejavuBold11Dark()));
    divisionTitle.setAlignment(Element.ALIGN_RIGHT);
    divisionCell.addElement(divisionTitle);

    headerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
    headerTable.setTableEvent(null);//from   ww w.j  a va 2  s .c  o  m
    headerTable.setSpacingAfter(4.0f);
    headerTable.addCell(titleCell);
    headerTable.addCell(divisionCell);
    document.add(headerTable);
}

From source file:com.qcadoo.mes.workPlans.pdf.document.WorkPlanPdfForDivision.java

License:Open Source License

private void addOperationTable(PdfWriter pdfWriter, GroupingContainer groupingContainer, Document document,
        OrderOperationComponent orderOperationComponent, Locale locale) throws DocumentException {

    Map<Long, Map<OperationProductColumn, ColumnAlignment>> outputProductsMap = groupingContainer
            .getOperationComponentIdProductOutColumnToAlignment();

    Map<Long, Map<OperationProductColumn, ColumnAlignment>> inputProductsMap = groupingContainer
            .getOperationComponentIdProductInColumnToAlignment();

    Entity operationComponent = orderOperationComponent.getOperationComponent();
    Entity order = orderOperationComponent.getOrder();
    Entity product = order.getBelongsToField(OrderFields.PRODUCT);

    Map<OperationProductColumn, ColumnAlignment> inputProductColumnAlignmentMap = inputProductsMap
            .get(operationComponent.getId());
    Map<OperationProductColumn, ColumnAlignment> outputProductColumnAlignmentMap = outputProductsMap
            .get(operationComponent.getId());

    PdfPTable table = pdfHelper.createPanelTable(3);

    PdfPCell headerCell = new PdfPCell();
    headerCell.setBorder(Rectangle.NO_BORDER);
    headerCell.setColspan(2);/*from  w  ww  .ja  v  a  2 s.c  o m*/

    PdfPCell inputCell = new PdfPCell();
    inputCell.setBorder(Rectangle.NO_BORDER);
    PdfPCell outputCell = new PdfPCell();
    outputCell.setBorder(Rectangle.NO_BORDER);
    PdfPCell codeCell = new PdfPCell();
    codeCell.setBorder(Rectangle.NO_BORDER);
    codeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
    codeCell.setVerticalAlignment(Element.ALIGN_TOP);
    codeCell.setRowspan(2);

    // addOperationSummary(headerCell, operationComponent);

    addOrderSummary(headerCell, order, product, operationComponent);

    addOperationProductsTable(inputCell, operationProductInComponents(operationComponent, order),
            inputProductColumnAlignmentMap, ProductDirection.IN, locale);
    addOperationProductsTable(outputCell, operationProductOutComponents(operationComponent, order),
            outputProductColumnAlignmentMap, ProductDirection.OUT, locale);

    codeCell.addElement(createBarcode(pdfWriter, operationComponent));

    float[] tableColumnWidths = new float[] { 70f, 70f, 10f };
    table.setWidths(tableColumnWidths);
    table.setTableEvent(null);
    table.addCell(headerCell);
    table.addCell(codeCell);
    table.addCell(inputCell);
    table.addCell(outputCell);
    table.setKeepTogether(true);
    document.add(table);
}

From source file:com.qcadoo.mes.workPlans.pdf.document.WorkPlanPdfForDivision.java

License:Open Source License

private void addOperationSummary(PdfPCell cell, Entity operationComponent) throws DocumentException {
    Entity operation = operationComponent.getBelongsToField(TechnologyOperationComponentFields.OPERATION);

    PdfPTable operationTable = pdfHelper.createPanelTable(1);

    PdfPCell numberCell = new PdfPCell();
    numberCell.setBorder(Rectangle.NO_BORDER);
    Paragraph operationName = new Paragraph(operation.getStringField(OperationFields.NUMBER) + " - "
            + operation.getStringField(OperationFields.NAME), FontUtils.getDejavuBold7Dark());
    numberCell.addElement(operationName);

    PdfPCell descriptionCell = new PdfPCell();
    descriptionCell.setBorder(Rectangle.NO_BORDER);
    String comment = operation.getStringField(OperationFields.COMMENT);
    Paragraph description = null;/*from  w  ww .  ja v  a 2  s.c om*/
    if (!StringUtils.isEmpty(comment)) {
        description = new Paragraph(comment, FontUtils.getDejavuBold7Dark());
    }

    operationTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
    operationTable.setTableEvent(null);
    operationTable.addCell(numberCell);
    if (description != null) {
        descriptionCell.addElement(description);
        operationTable.addCell(descriptionCell);
    } else {
        operationTable.addCell("");
    }
    cell.addElement(operationTable);
}

From source file:com.qcadoo.mes.workPlans.pdf.document.WorkPlanPdfForDivision.java

License:Open Source License

private void addOrderSummary(PdfPCell cell, Entity order, Entity product, Entity operationComponent)
        throws DocumentException {
    Entity operation = operationComponent.getBelongsToField(TechnologyOperationComponentFields.OPERATION);
    PdfPTable orderTable = pdfHelper.createPanelTable(3);
    PdfPCell operationCell = new PdfPCell();
    operationCell.setBorder(Rectangle.NO_BORDER);
    Paragraph operationName = new Paragraph(operation.getStringField(OperationFields.NUMBER) + " - "
            + operation.getStringField(OperationFields.NAME), FontUtils.getDejavuBold7Dark());
    operationCell.addElement(operationName);

    PdfPCell numberCell = new PdfPCell();
    numberCell.setBorder(Rectangle.NO_BORDER);
    Paragraph number = new Paragraph(order.getStringField(OrderFields.NUMBER), FontUtils.getDejavuBold7Dark());
    number.setAlignment(Element.ALIGN_RIGHT);
    numberCell.addElement(number);/*from www .  j  ava  2  s .c o m*/

    PdfPCell quantityCell = new PdfPCell();
    quantityCell.setBorder(Rectangle.NO_BORDER);
    Paragraph quantity = new Paragraph(
            numberService.formatWithMinimumFractionDigits(order.getDecimalField(OrderFields.PLANNED_QUANTITY),
                    0) + " " + product.getStringField(ProductFields.UNIT),
            FontUtils.getDejavuBold7Dark());
    quantity.setAlignment(Element.ALIGN_CENTER);
    quantityCell.addElement(quantity);

    PdfPCell descriptionCell = new PdfPCell();
    descriptionCell.setBorder(Rectangle.NO_BORDER);
    descriptionCell.setColspan(3);
    String comment = operationComponent.getStringField(TechnologyOperationComponentFields.COMMENT);
    Paragraph description = null;
    if (!StringUtils.isEmpty(comment)) {
        description = new Paragraph(comment, FontUtils.getDejavuBold7Dark());
    }

    float[] tableColumnWidths = new float[] { 160f, 30f, 10f };
    orderTable.setWidths(tableColumnWidths);
    orderTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
    orderTable.setTableEvent(null);
    orderTable.addCell(operationCell);
    orderTable.addCell(numberCell);
    orderTable.addCell(quantityCell);
    if (description != null) {
        descriptionCell.addElement(description);
        orderTable.addCell(descriptionCell);
    }
    cell.addElement(orderTable);
}

From source file:com.qcadoo.mes.workPlans.pdf.document.WorkPlanPdfForDivision.java

License:Open Source License

private void alignColumn(final PdfPCell cell, final ColumnAlignment columnAlignment) {
    if (ColumnAlignment.LEFT.equals(columnAlignment)) {
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
    } else if (ColumnAlignment.RIGHT.equals(columnAlignment)) {
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
    }/*from  w ww. ja  va  2s  .  c o  m*/
    cell.setBorder(Rectangle.BOX);
    cell.setPadding(2f);
}

From source file:com.slamd.report.PDFReportGenerator.java

License:Open Source License

/**
 * Writes information about the provided job to the document.
 *
 * @param  document  The document to which the job information should be
 *                   written.//from   w w w. ja v  a2s  . c o  m
 * @param  job       The job to include in the document.
 *
 * @throws  DocumentException  If a problem occurs while writing the contents.
 */
private void writeJob(Document document, Job job) throws DocumentException {
    Anchor anchor = new Anchor("Job " + job.getJobID(),
            FontFactory.getFont(FontFactory.HELVETICA, 18, Font.BOLD, Color.BLACK));
    anchor.setName(job.getJobID());
    Paragraph p = new Paragraph(anchor);
    document.add(p);

    // Write the general information to the document.
    p = new Paragraph("General Information",
            FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, Color.BLACK));
    document.add(p);

    PdfPTable table = new PdfPTable(2);
    table.setWidthPercentage(100);
    table.setWidths(new int[] { 30, 70 });
    writeTableCell(table, "Job ID");
    writeTableCell(table, job.getJobID());

    String optimizingJobID = job.getOptimizingJobID();
    if ((optimizingJobID != null) && (optimizingJobID.length() > 0)) {
        writeTableCell(table, "Optimizing Job ID");
        writeTableCell(table, optimizingJobID);
    }

    String descriptionStr = job.getJobDescription();
    if ((descriptionStr == null) || (descriptionStr.length() == 0)) {
        descriptionStr = "(Not Specified)";
    }
    writeTableCell(table, "Job Description");
    writeTableCell(table, descriptionStr);

    writeTableCell(table, "Job Type");
    writeTableCell(table, job.getJobClassName());

    writeTableCell(table, "Job Class");
    writeTableCell(table, job.getJobClass().getClass().getName());

    writeTableCell(table, "Job State");
    writeTableCell(table, job.getJobStateString());
    document.add(table);

    // Write the schedule config if appropriate.
    if (includeScheduleConfig) {
        document.add(new Paragraph(" "));
        p = new Paragraph("Schedule Information",
                FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, Color.BLACK));
        document.add(p);

        table = new PdfPTable(2);
        table.setWidthPercentage(100);
        table.setWidths(new int[] { 30, 70 });

        Date startTime = job.getStartTime();
        String startStr;
        if (startTime == null) {
            startStr = "(Not Available)";
        } else {
            startStr = dateFormat.format(startTime);
        }
        writeTableCell(table, "Scheduled Start Time");
        writeTableCell(table, startStr);

        Date stopTime = job.getStopTime();
        String stopStr;
        if (stopTime == null) {
            stopStr = "(Not Specified)";
        } else {
            stopStr = dateFormat.format(stopTime);
        }
        writeTableCell(table, "Scheduled Stop Time");
        writeTableCell(table, stopStr);

        int duration = job.getDuration();
        String durationStr;
        if (duration > 0) {
            durationStr = duration + " seconds";
        } else {
            durationStr = "(Not Specified)";
        }
        writeTableCell(table, "Scheduled Duration");
        writeTableCell(table, durationStr);

        writeTableCell(table, "Number of Clients");
        writeTableCell(table, String.valueOf(job.getNumberOfClients()));

        String[] requestedClients = job.getRequestedClients();
        if ((requestedClients != null) && (requestedClients.length > 0)) {
            PdfPTable clientTable = new PdfPTable(1);
            for (int i = 0; i < requestedClients.length; i++) {
                PdfPCell clientCell = new PdfPCell(new Phrase(requestedClients[i]));
                clientCell.setBorder(0);
                clientTable.addCell(clientCell);
            }

            writeTableCell(table, "Requested Clients");
            table.addCell(clientTable);
        }

        String[] monitorClients = job.getResourceMonitorClients();
        if ((monitorClients != null) && (monitorClients.length > 0)) {
            PdfPTable clientTable = new PdfPTable(1);
            for (int i = 0; i < monitorClients.length; i++) {
                PdfPCell clientCell = new PdfPCell(new Phrase(monitorClients[i]));
                clientCell.setBorder(0);
                clientTable.addCell(clientCell);
            }

            writeTableCell(table, "Resource Monitor Clients");
            table.addCell(clientTable);
        }

        writeTableCell(table, "Threads per Client");
        writeTableCell(table, String.valueOf(job.getThreadsPerClient()));

        writeTableCell(table, "Thread Startup Delay");
        writeTableCell(table, job.getThreadStartupDelay() + " milliseconds");

        writeTableCell(table, "Statistics Collection Interval");
        writeTableCell(table, job.getCollectionInterval() + " seconds");

        document.add(table);
    }

    // Write the job-specific parameter information if appropriate.
    if (includeJobConfig) {
        document.add(new Paragraph(" "));
        p = new Paragraph("Parameter Information",
                FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, Color.BLACK));
        document.add(p);

        table = new PdfPTable(2);
        table.setWidthPercentage(100);
        table.setWidths(new int[] { 30, 70 });

        Parameter[] params = job.getParameterList().getParameters();
        for (int i = 0; i < params.length; i++) {
            writeTableCell(table, params[i].getDisplayName());
            writeTableCell(table, params[i].getDisplayValue());
        }

        document.add(table);
    }

    // Write the statistical data if appropriate.
    if (includeStats && job.hasStats()) {
        document.add(new Paragraph(" "));
        p = new Paragraph("General Execution Data",
                FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, Color.BLACK));
        document.add(p);

        table = new PdfPTable(2);
        table.setWidthPercentage(100);
        table.setWidths(new int[] { 30, 70 });

        Date actualStartTime = job.getActualStartTime();
        String startStr;
        if (actualStartTime == null) {
            startStr = "(Not Available)";
        } else {
            startStr = dateFormat.format(actualStartTime);
        }
        writeTableCell(table, "Actual Start Time");
        writeTableCell(table, startStr);

        Date actualStopTime = job.getActualStopTime();
        String stopStr;
        if (actualStopTime == null) {
            stopStr = "(Not Available)";
        } else {
            stopStr = dateFormat.format(actualStopTime);
        }
        writeTableCell(table, "Actual Stop Time");
        writeTableCell(table, stopStr);

        int actualDuration = job.getActualDuration();
        String durationStr;
        if (actualDuration > 0) {
            durationStr = actualDuration + " seconds";
        } else {
            durationStr = "(Not Available)";
        }
        writeTableCell(table, "Actual Duration");
        writeTableCell(table, durationStr);

        String[] clients = job.getStatTrackerClientIDs();
        if ((clients != null) && (clients.length > 0)) {
            PdfPTable clientTable = new PdfPTable(1);
            for (int i = 0; i < clients.length; i++) {
                PdfPCell clientCell = new PdfPCell(new Phrase(clients[i]));
                clientCell.setBorder(0);
                clientTable.addCell(clientCell);
            }

            writeTableCell(table, "Clients Used");
            table.addCell(clientTable);
        }

        document.add(table);

        String[] trackerNames = job.getStatTrackerNames();
        for (int i = 0; i < trackerNames.length; i++) {
            StatTracker[] trackers = job.getStatTrackers(trackerNames[i]);
            if ((trackers != null) && (trackers.length > 0)) {
                document.newPage();
                StatTracker tracker = trackers[0].newInstance();
                tracker.aggregate(trackers);

                document.add(new Paragraph(" "));
                document.add(new Paragraph(trackerNames[i],
                        FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, Color.BLACK)));

                String[] summaryNames = tracker.getSummaryLabels();
                String[] summaryValues = tracker.getSummaryData();
                table = new PdfPTable(2);
                table.setWidthPercentage(100);
                table.setWidths(new int[] { 50, 50 });
                for (int j = 0; j < summaryNames.length; j++) {
                    writeTableCell(table, summaryNames[j]);
                    writeTableCell(table, summaryValues[j]);
                }
                document.add(table);

                if (includeGraphs) {
                    try {
                        ParameterList params = tracker.getGraphParameterStubs(job);
                        BufferedImage graphImage = tracker.createGraph(job, Constants.DEFAULT_GRAPH_WIDTH,
                                Constants.DEFAULT_GRAPH_HEIGHT, params);
                        Image image = Image.getInstance(imageToByteArray(graphImage));
                        image.scaleToFit(inchesToPoints(5.5), inchesToPoints(4.5));
                        document.add(image);
                    } catch (Exception e) {
                    }
                }
            }
        }
    }

    // Write the resource monitor data if appropriate.
    if (includeMonitorStats && job.hasResourceStats()) {
        String[] trackerNames = job.getResourceStatTrackerNames();
        for (int i = 0; i < trackerNames.length; i++) {
            StatTracker[] trackers = job.getResourceStatTrackers(trackerNames[i]);
            if ((trackers != null) && (trackers.length > 0)) {
                document.newPage();
                StatTracker tracker = trackers[0].newInstance();
                tracker.aggregate(trackers);

                document.add(new Paragraph(" "));
                document.add(new Paragraph(trackerNames[i],
                        FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, Color.BLACK)));

                String[] summaryNames = tracker.getSummaryLabels();
                String[] summaryValues = tracker.getSummaryData();
                table = new PdfPTable(2);
                table.setWidthPercentage(100);
                table.setWidths(new int[] { 50, 50 });
                for (int j = 0; j < summaryNames.length; j++) {
                    writeTableCell(table, summaryNames[j]);
                    writeTableCell(table, summaryValues[j]);
                }
                document.add(table);

                if (includeGraphs) {
                    try {
                        ParameterList params = tracker.getGraphParameterStubs(job);
                        BufferedImage graphImage = tracker.createMonitorGraph(job,
                                Constants.DEFAULT_GRAPH_WIDTH, Constants.DEFAULT_MONITOR_GRAPH_HEIGHT, params);
                        Image image = Image.getInstance(imageToByteArray(graphImage));
                        image.scaleToFit(inchesToPoints(5.5), inchesToPoints(4.5));
                        document.add(image);
                    } catch (Exception e) {
                    }
                }
            }
        }
    }
}

From source file:com.slamd.report.PDFReportGenerator.java

License:Open Source License

/**
 * Writes information about the provided optimizing job to the document.
 *
 * @param  document       The document to which the job information should be
 *                        written./*from  w  w w  .j  ava  2s.c o  m*/
 * @param  optimizingJob  The optimizing job to include in the document.
 *
 * @throws  DocumentException  If a problem occurs while writing the contents.
 */
private void writeOptimizingJob(Document document, OptimizingJob optimizingJob) throws DocumentException {
    Anchor anchor = new Anchor("Optimizing Job " + optimizingJob.getOptimizingJobID(),
            FontFactory.getFont(FontFactory.HELVETICA, 18, Font.BOLD, Color.BLACK));
    anchor.setName(optimizingJob.getOptimizingJobID());
    Paragraph p = new Paragraph(anchor);
    document.add(p);

    // Write the general information to the document.
    p = new Paragraph("General Information",
            FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, Color.BLACK));
    document.add(p);

    PdfPTable table = new PdfPTable(2);
    table.setWidthPercentage(100);
    table.setWidths(new int[] { 30, 70 });
    writeTableCell(table, "Optimizing Job ID");
    writeTableCell(table, optimizingJob.getOptimizingJobID());

    writeTableCell(table, "Job Type");
    writeTableCell(table, optimizingJob.getJobClassName());

    String descriptionStr = optimizingJob.getDescription();
    if ((descriptionStr == null) || (descriptionStr.length() == 0)) {
        descriptionStr = "(Not Specified)";
    }
    writeTableCell(table, "Base Description");
    writeTableCell(table, descriptionStr);

    writeTableCell(table, "Include Thread Count in Description");
    writeTableCell(table, String.valueOf(optimizingJob.includeThreadsInDescription()));

    writeTableCell(table, "Job State");
    writeTableCell(table, Constants.jobStateToString(optimizingJob.getJobState()));
    document.add(table);

    // Write the schedule config to the document if appropriate.
    if (includeScheduleConfig) {
        document.add(new Paragraph(" "));
        p = new Paragraph("Schedule Information",
                FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, Color.BLACK));
        document.add(p);

        table = new PdfPTable(2);
        table.setWidthPercentage(100);
        table.setWidths(new int[] { 30, 70 });

        Date startTime = optimizingJob.getStartTime();
        String startStr;
        if (startTime == null) {
            startStr = "(Not Available)";
        } else {
            startStr = dateFormat.format(startTime);
        }
        writeTableCell(table, "Scheduled Start Time");
        writeTableCell(table, startStr);

        int duration = optimizingJob.getDuration();
        String durationStr;
        if (duration > 0) {
            durationStr = duration + " seconds";
        } else {
            durationStr = "(Not Specified)";
        }
        writeTableCell(table, "Job Duration");
        writeTableCell(table, durationStr);

        writeTableCell(table, "Delay Between Iterations");
        writeTableCell(table, optimizingJob.getDelayBetweenIterations() + " seconds");

        writeTableCell(table, "Number of Clients");
        writeTableCell(table, String.valueOf(optimizingJob.getNumClients()));

        String[] requestedClients = optimizingJob.getRequestedClients();
        if ((requestedClients != null) && (requestedClients.length > 0)) {
            PdfPTable clientTable = new PdfPTable(1);
            for (int i = 0; i < requestedClients.length; i++) {
                PdfPCell clientCell = new PdfPCell(new Phrase(requestedClients[i]));
                clientCell.setBorder(0);
                clientTable.addCell(clientCell);
            }

            writeTableCell(table, "Requested Clients");
            table.addCell(clientTable);
        }

        String[] monitorClients = optimizingJob.getResourceMonitorClients();
        if ((monitorClients != null) && (monitorClients.length > 0)) {
            PdfPTable clientTable = new PdfPTable(1);
            for (int i = 0; i < monitorClients.length; i++) {
                PdfPCell clientCell = new PdfPCell(new Phrase(monitorClients[i]));
                clientCell.setBorder(0);
                clientTable.addCell(clientCell);
            }

            writeTableCell(table, "Resource Monitor Clients");
            table.addCell(clientTable);
        }

        writeTableCell(table, "Minimum Number of Threads");
        writeTableCell(table, String.valueOf(optimizingJob.getMinThreads()));

        int maxThreads = optimizingJob.getMaxThreads();
        String maxThreadsStr;
        if (maxThreads > 0) {
            maxThreadsStr = String.valueOf(maxThreads);
        } else {
            maxThreadsStr = "(Not Specified)";
        }
        writeTableCell(table, "Maximum Number of Threads");
        writeTableCell(table, maxThreadsStr);

        writeTableCell(table, "Thread Increment Between Iterations");
        writeTableCell(table, String.valueOf(optimizingJob.getThreadIncrement()));

        writeTableCell(table, "Statistics Collection Interval");
        writeTableCell(table, optimizingJob.getCollectionInterval() + " seconds");
        document.add(table);
    }

    // Get the optimization algorithm used.
    OptimizationAlgorithm optimizationAlgorithm = optimizingJob.getOptimizationAlgorithm();
    ParameterList paramList = optimizationAlgorithm.getOptimizationAlgorithmParameters();
    Parameter[] optimizationParams = paramList.getParameters();

    // Write the optimizing config to the document if appropriate.
    if (includeScheduleConfig) {
        document.add(new Paragraph(" "));
        p = new Paragraph("Optimization Settings",
                FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, Color.BLACK));
        document.add(p);

        table = new PdfPTable(2);
        table.setWidthPercentage(100);
        table.setWidths(new int[] { 30, 70 });

        for (int i = 0; i < optimizationParams.length; i++) {
            writeTableCell(table, optimizationParams[i].getDisplayName());
            writeTableCell(table, optimizationParams[i].getDisplayValue());
        }

        writeTableCell(table, "Maximum Consecutive Non-Improving Iterations");
        writeTableCell(table, String.valueOf(optimizingJob.getMaxNonImproving()));

        writeTableCell(table, "Re-Run Best Iteration");
        writeTableCell(table, String.valueOf(optimizingJob.reRunBestIteration()));

        int reRunDuration = optimizingJob.getReRunDuration();
        String durationStr;
        if (reRunDuration > 0) {
            durationStr = reRunDuration + " seconds";
        } else {
            durationStr = "(Not Specified)";
        }
        writeTableCell(table, "Re-Run Duration");
        writeTableCell(table, durationStr);

        document.add(table);
    }

    // Write the job-specific config to the document if appropriate.
    if (includeJobConfig) {
        document.add(new Paragraph(" "));
        p = new Paragraph("Parameter Information",
                FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, Color.BLACK));
        document.add(p);

        table = new PdfPTable(2);
        table.setWidthPercentage(100);
        table.setWidths(new int[] { 30, 70 });

        Parameter[] params = optimizingJob.getParameters().getParameters();
        for (int i = 0; i < params.length; i++) {
            writeTableCell(table, params[i].getDisplayName());
            writeTableCell(table, params[i].getDisplayValue());
        }

        document.add(table);
    }

    // Write the statistical data to the document if appropriate.
    if (includeStats && optimizingJob.hasStats()) {
        document.add(new Paragraph(" "));
        p = new Paragraph("Execution Data",
                FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, Color.BLACK));
        document.add(p);

        table = new PdfPTable(2);
        table.setWidthPercentage(100);
        table.setWidths(new int[] { 30, 70 });

        Date actualStartTime = optimizingJob.getActualStartTime();
        String startTimeStr;
        if (actualStartTime == null) {
            startTimeStr = "(Not Available)";
        } else {
            startTimeStr = dateFormat.format(actualStartTime);
        }
        writeTableCell(table, "Actual Start Time");
        writeTableCell(table, startTimeStr);

        Date actualStopTime = optimizingJob.getActualStopTime();
        String stopTimeStr;
        if (actualStopTime == null) {
            stopTimeStr = "(Not Available)";
        } else {
            stopTimeStr = dateFormat.format(actualStopTime);
        }
        writeTableCell(table, "Actual Stop Time");
        writeTableCell(table, stopTimeStr);

        Job[] iterations = optimizingJob.getAssociatedJobs();
        if ((iterations != null) && (iterations.length > 0)) {
            writeTableCell(table, "Job Iterations Completed");
            writeTableCell(table, String.valueOf(iterations.length));

            int optimalThreadCount = optimizingJob.getOptimalThreadCount();
            String threadStr;
            if (optimalThreadCount > 0) {
                threadStr = String.valueOf(optimalThreadCount);
            } else {
                threadStr = "(Not Available)";
            }
            writeTableCell(table, "Optimal Thread Count");
            writeTableCell(table, threadStr);

            double optimalValue = optimizingJob.getOptimalValue();
            String valueStr;
            if (optimalThreadCount > 0) {
                valueStr = decimalFormat.format(optimalValue);
            } else {
                valueStr = "(Not Available)";
            }
            writeTableCell(table, "Optimal Value");
            writeTableCell(table, valueStr);

            String optimalID = optimizingJob.getOptimalJobID();
            writeTableCell(table, "Optimal Job Iteration");
            if ((optimalID == null) || (optimalID.length() == 0)) {
                writeTableCell(table, "(Not Available)");
            } else if (includeOptimizingIterations) {
                anchor = new Anchor(optimalID,
                        FontFactory.getFont(FontFactory.HELVETICA, 12, Font.UNDERLINE, Color.BLUE));
                anchor.setReference('#' + optimalID);
                table.addCell(new PdfPCell(anchor));
            } else {
                writeTableCell(table, optimalID);
            }
        }

        Job reRunIteration = optimizingJob.getReRunIteration();
        if (reRunIteration != null) {
            writeTableCell(table, "Re-Run Iteration");
            if (includeOptimizingIterations) {
                anchor = new Anchor(reRunIteration.getJobID(),
                        FontFactory.getFont(FontFactory.HELVETICA, 12, Font.UNDERLINE, Color.BLUE));
                anchor.setReference('#' + reRunIteration.getJobID());
                table.addCell(new PdfPCell(anchor));
            } else {
                writeTableCell(table, reRunIteration.getJobID());
            }

            String valueStr;
            try {
                double iterationValue = optimizationAlgorithm.getIterationOptimizationValue(reRunIteration);
                valueStr = decimalFormat.format(iterationValue);
            } catch (Exception e) {
                valueStr = "N/A";
            }

            writeTableCell(table, "Re-Run Iteration Value");
            writeTableCell(table, valueStr);
        }

        document.add(table);

        if (includeOptimizingIterations && (iterations != null) && (iterations.length > 0)) {
            document.add(new Paragraph(" "));
            p = new Paragraph("Job Iterations",
                    FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, Color.BLACK));
            document.add(p);

            table = new PdfPTable(2);
            table.setWidthPercentage(100);
            table.setWidths(new int[] { 50, 50 });

            for (int i = 0; i < iterations.length; i++) {
                String valueStr;
                try {
                    double iterationValue = optimizationAlgorithm.getIterationOptimizationValue(iterations[i]);
                    valueStr = decimalFormat.format(iterationValue);
                } catch (Exception e) {
                    valueStr = "N/A";
                }

                anchor = new Anchor(iterations[i].getJobID(),
                        FontFactory.getFont(FontFactory.HELVETICA, 12, Font.UNDERLINE, Color.BLUE));
                anchor.setReference('#' + iterations[i].getJobID());
                table.addCell(new PdfPCell(anchor));
                writeTableCell(table, valueStr);
            }

            document.add(table);
        }

        if (includeGraphs && (iterations != null) && (iterations.length > 0)) {
            String[] statNames = iterations[0].getStatTrackerNames();
            for (int j = 0; j < statNames.length; j++) {
                StatTracker[] trackers = iterations[0].getStatTrackers(statNames[j]);
                if ((trackers != null) && (trackers.length > 0)) {
                    StatTracker tracker = trackers[0].newInstance();
                    tracker.aggregate(trackers);

                    try {
                        document.newPage();
                        ParameterList params = tracker.getGraphParameterStubs(iterations);
                        BufferedImage graphImage = tracker.createGraph(iterations,
                                Constants.DEFAULT_GRAPH_WIDTH, Constants.DEFAULT_GRAPH_HEIGHT, params);
                        Image image = Image.getInstance(imageToByteArray(graphImage));
                        image.scaleToFit(inchesToPoints(5.5), inchesToPoints(4.5));
                        document.add(image);
                    } catch (Exception e) {
                    }
                }
            }
        }

        if (includeOptimizingIterations && (iterations != null) && (iterations.length > 0)) {
            for (int i = 0; i < iterations.length; i++) {
                document.newPage();
                writeJob(document, iterations[i]);
            }
        }
        if (includeOptimizingIterations && (reRunIteration != null)) {
            document.newPage();
            writeJob(document, reRunIteration);
        }
    }
}