Example usage for com.lowagie.text.html.simpleparser HTMLWorker parseToList

List of usage examples for com.lowagie.text.html.simpleparser HTMLWorker parseToList

Introduction

In this page you can find the example usage for com.lowagie.text.html.simpleparser HTMLWorker parseToList.

Prototype

public static ArrayList parseToList(Reader reader, StyleSheet style) throws IOException 

Source Link

Usage

From source file:com.krawler.esp.servlets.AppraisalDetails.java

License:Open Source License

private ByteArrayOutputStream AppraisalDetail(HttpServletRequest request, Session session, boolean isEmm)
        throws JSONException, SessionExpiredException, DocumentException, ServiceException, IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    String[] colHeader = { "Employee Name", "Appraisal Cycle Name", "Appraisal Cycle Start Date",
            "Appraisal Cycle End Date", "Total No. of Appraisals", "No. of Appraisals submitted",
            "Overall Self Comment", "Overall Appraiser Comments", "Overall Competency Score", "Competencies" };
    String[] dataIndex = { "empname", "appcylename", "appcylestdate", "appcylendate", "totalappraisal",
            "appraisalsubmitted", "empcomment", "mancom", "manavgwght", "" };
    String[] compHeader = { "Name", "Description", "Self Appraisal Score", "Self Appraisal Comment",
            "Appraiser Competency Score", "Appraiser Comments" };
    String[] compDataIndex = { "comptename", "comptdesc", "selfcompscore", "selfcomment", "compmanwght" };
    String[] compGoalHeader = { "Goals", "Assigned By", "Appraiser Rating", "Appraiser Comment", "Self Rating",
            "Self Comments" };
    String[] compGoalDataIndex = { "gname", "assignedby", "gmanrat", "mangoalcomment", "gemprat",
            "empgoalcomment" };
    String managerComments = "";
    String scoreAvg = "";
    String companyid = null;//ww  w .j a v  a 2 s  .c  o  m
    Transaction tx = null;
    PdfWriter writer = null;
    try {
        Document document = new Document(PageSize.A4.rotate(), 25, 25, 25, 25);
        writer = PdfWriter.getInstance(document, baos);
        writer.setPageEvent(new EndPage());
        document.open();
        java.awt.Color tColor = new Color(9, 9, 9);
        fontSmallBold.setColor(tColor);
        Paragraph p = new Paragraph();

        PdfPTable table = new PdfPTable(2);
        table.setWidthPercentage(100);
        table.setWidths(new float[] { 55, 75 });

        PdfPTable mainTable = new PdfPTable(1);
        mainTable.setTotalWidth(90);
        mainTable.setWidthPercentage(100);
        mainTable.setSpacingBefore(20);

        PdfPCell headcell = null;
        headcell = new PdfPCell(new Paragraph("Appraisal Details", fontHeadingMediumBold));
        headcell.setBackgroundColor(new Color(0xEEEEEE));
        headcell.setPadding(5);
        mainTable.addCell(headcell);
        document.add(mainTable);

        String str = hrmsManager.getAppraisalReport(session, request);
        JSONObject jobjTemplate = new JSONObject(str);
        com.krawler.utils.json.base.JSONArray jarr = jobjTemplate.getJSONArray("data");
        String goalstr = "";
        User user = (User) session.get(User.class, request.getParameter("userid"));
        companyid = user.getCompany().getCompanyID();
        if (hrmsManager.checkModule("goal", session, request, companyid))
            goalstr = hrmsManager.getAppraisalReportGoalsforGrid(session, request);
        com.krawler.utils.json.base.JSONArray jarr2 = jarr.getJSONObject(0).getJSONArray("data");
        JSONObject jobjAppraisal = new JSONObject(jarr2.getString(0));
        jarr = jobjAppraisal.getJSONArray("competencies");
        int headlen = colHeader.length;
        if (jarr.length() < 1) {
            headlen = headlen - 1;
        }
        for (int i = 0; i < headlen; i++) {
            PdfPCell pcell = new PdfPCell(new Paragraph(colHeader[i], fontMediumBold));
            pcell.setBorder(0);
            if (i == 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);
            table.addCell(pcell);

            if (!dataIndex[i].equals("mancom")) {
                pcell = new PdfPCell(new Paragraph(!dataIndex[i].equals("")
                        ? !jobjAppraisal.isNull(dataIndex[i]) ? jobjAppraisal.getString(dataIndex[i]) : ""
                        : "", fontSmallRegular));
                if (i == 0)
                    pcell.setPaddingTop(10);
                pcell.setBorder(0);
                pcell.setPaddingLeft(10);
                pcell.setPaddingBottom(4);
                pcell.setBorderColor(new Color(0xF2F2F2));
                pcell.setHorizontalAlignment(Element.ALIGN_LEFT);
                pcell.setVerticalAlignment(Element.ALIGN_LEFT);
                table.addCell(pcell);
            } else {
                if (!jobjAppraisal.isNull(dataIndex[i])) {
                    String[] spl = jobjAppraisal.getString(dataIndex[i]).split(",");
                    String strData = "";
                    for (int counter = 0; counter < spl.length; counter++) {
                        strData += spl[counter] + " \n";
                    }
                    pcell = new PdfPCell(new Paragraph(strData, fontSmallRegular));
                    if (i == 0)
                        pcell.setPaddingTop(10);
                    pcell.setBorder(0);
                    pcell.setPaddingLeft(10);
                    pcell.setPaddingBottom(4);
                    pcell.setBorderColor(new Color(0xF2F2F2));
                    pcell.setHorizontalAlignment(Element.ALIGN_LEFT);
                    pcell.setVerticalAlignment(Element.ALIGN_LEFT);
                    table.addCell(pcell);
                }
            }
        }

        document.add(table);

        PdfPTable compTable = new PdfPTable(6);
        compTable.setWidthPercentage(100);
        compTable.setWidths(new float[] { 50, 60, 30, 50, 42, 70 });
        compTable.setSpacingBefore(20);
        compTable.setHeaderRows(1);

        for (int i = 0; i < compHeader.length; i++) {
            PdfPCell pcell = new PdfPCell(new Paragraph(compHeader[i], fontMediumBold));
            pcell.setBorder(0);
            pcell.setBorder(PdfPCell.BOX);
            pcell.setPadding(4);
            pcell.setBorderColor(Color.GRAY);
            pcell.setHorizontalAlignment(Element.ALIGN_CENTER);
            compTable.addCell(pcell);
        }

        for (int i = 0; i < jarr.length(); i++) {
            jobjAppraisal = jarr.getJSONObject(i);
            for (int k = 0; k < compHeader.length; k++) {
                if (k != compHeader.length - 1) {
                    scoreAvg = "";
                    if (!jobjAppraisal.isNull(compDataIndex[k]) && compDataIndex[k].equals("compmanwght")) {
                        scoreAvg = jobjAppraisal.getString("nominalRat");
                        Font font = new Font(Font.HELVETICA, 8, Font.BOLD, Color.BLACK);
                        Chunk chunk1 = new Chunk(jobjAppraisal.getString(compDataIndex[k]) + "\n\n",
                                fontSmallRegular);
                        Chunk chunk2 = null;
                        if (!StringUtil.isNullOrEmpty(request.getParameter("pdfEmail"))) {
                            //                                user=(User)session.get(User.class,request.getParameter("userid"));
                            //                                companyid=user.getCompany().getCompanyID();
                            if (hrmsManager.checkModule("modaverage", session, request, companyid)) {
                                chunk2 = new Chunk("[Mod Avg:  " + scoreAvg + " ]", font);
                            } else {
                                chunk2 = new Chunk("[Avg:  " + scoreAvg + " ]", font);
                            }
                        } else {
                            if (hrmsManager.checkModule("modaverage", session, request)) {
                                chunk2 = new Chunk("[Mod Avg:  " + scoreAvg + " ]", font);
                            } else {
                                chunk2 = new Chunk("[Avg:  " + scoreAvg + " ]", font);
                            }
                        }
                        Phrase phrase1 = new Phrase();
                        phrase1.add(chunk1);
                        phrase1.add(chunk2);

                        p = new Paragraph();
                        p.add(phrase1);
                    }
                    PdfPCell pcell = new PdfPCell();
                    if (!scoreAvg.equals("")) {
                        pcell = new PdfPCell(new Paragraph(p));
                        pcell.setPadding(0);
                        pcell.setPaddingTop(2);
                        pcell.setPaddingBottom(4);
                    } else {
                        if (!jobjAppraisal.isNull(compDataIndex[k])) {
                            String htmlStr = jobjAppraisal.getString(compDataIndex[k]);
                            htmlStr = htmlStr.replaceAll("\n", "<br>");
                            StyleSheet st = new StyleSheet();
                            st.loadTagStyle("body", "face", "HELVETICA");
                            st.loadTagStyle("body", "size", "1");
                            st.loadTagStyle("body", "leading", "8,0");
                            HTMLWorker worker = new HTMLWorker(document);
                            StringReader stringReader = new StringReader(htmlStr);
                            ArrayList listStr = HTMLWorker.parseToList(stringReader, st);
                            pcell.setPadding(4);
                            for (int htmlCount = 0; htmlCount < listStr.size(); ++htmlCount) {
                                if (!listStr.get(htmlCount).toString().equals("[]"))
                                    pcell.addElement((Element) listStr.get(htmlCount));
                            }
                        } else
                            pcell = new PdfPCell(new Paragraph(
                                    !jobjAppraisal.isNull(compDataIndex[k])
                                            ? hrmsManager.serverHTMLStripper(
                                                    jobjAppraisal.getString(compDataIndex[k]))
                                            : "",
                                    fontSmallRegular));
                    }
                    pcell.setBorder(PdfPCell.BOTTOM | PdfPCell.LEFT | PdfPCell.RIGHT);
                    pcell.setBorderColor(Color.GRAY);
                    pcell.setHorizontalAlignment(
                            compDataIndex[k].equals("comptename") || compDataIndex[k].equals("comptdesc")
                                    || compDataIndex[k].equals("selfcomment") ? Element.ALIGN_LEFT
                                            : Element.ALIGN_CENTER);
                    pcell.setVerticalAlignment(
                            compDataIndex[k].equals("comptdesc") || compDataIndex[k].equals("comptdesc")
                                    || compDataIndex[k].equals("selfcomment") ? Element.ALIGN_LEFT
                                            : Element.ALIGN_CENTER);
                    compTable.addCell(pcell);

                } else {
                    jarr2 = jobjAppraisal.getJSONArray("comments");
                    managerComments = "";
                    int commentCount = 1;
                    for (int j = jarr2.length() - 1; j >= 0; j--) {
                        jobjTemplate = jarr2.getJSONObject(j);
                        managerComments += commentCount + ")  " + jobjTemplate.getString("managercomment")
                                + "\n\n";
                        commentCount++;
                    }
                    PdfPCell pcell = new PdfPCell(new Paragraph(managerComments, fontSmallRegular));
                    pcell.setBorder(PdfPCell.BOTTOM | PdfPCell.LEFT | PdfPCell.RIGHT);
                    pcell.setPadding(4);
                    pcell.setBorderColor(Color.GRAY);
                    pcell.setHorizontalAlignment(Element.ALIGN_LEFT);
                    pcell.setVerticalAlignment(Element.ALIGN_LEFT);
                    compTable.addCell(pcell);
                }
            }
        }

        PdfPTable helpTable = new PdfPTable(1);
        helpTable.setTotalWidth(90);
        helpTable.setWidthPercentage(100);
        helpTable.setSpacingBefore(20);

        PdfPCell pcell = new PdfPCell(new Paragraph(
                "Mod Avg. : Average of ratings after excluding a minimum and a maximum rating. For e.g, mod average of 2, 3, 2, 4, 5, 3 is (2+3+4+3)/4",
                helpFont));
        pcell.setBorder(0);
        pcell.setPadding(4);
        pcell.setHorizontalAlignment(Element.ALIGN_LEFT);
        helpTable.addCell(pcell);

        document.add(compTable);
        if (!StringUtil.isNullOrEmpty(request.getParameter("pdfEmail"))) {
            if (hrmsManager.checkModule("modaverage", session, request, companyid)) {
                document.add(helpTable);
            }
        } else {
            if (hrmsManager.checkModule("modaverage", session, request)) {
                document.add(helpTable);
            }
        }

        if (!StringUtil.isNullOrEmpty(goalstr)) {
            PdfPTable compgTable = new PdfPTable(6);
            compgTable.setWidthPercentage(100);
            compgTable.setWidths(new float[] { 50, 60, 30, 50, 42, 70 });
            compgTable.setSpacingBefore(20);
            compgTable.setHeaderRows(1);
            for (int i = 0; i < compGoalHeader.length; i++) {
                PdfPCell pgcell = new PdfPCell(new Paragraph(compGoalHeader[i], fontMediumBold));
                pgcell.setBorder(0);
                pgcell.setBorder(PdfPCell.BOX);
                pgcell.setPadding(4);
                pgcell.setBorderColor(Color.GRAY);
                pgcell.setHorizontalAlignment(Element.ALIGN_CENTER);
                compgTable.addCell(pgcell);
            }
            JSONObject jobjTemplates = new JSONObject(goalstr);
            com.krawler.utils.json.base.JSONArray jarr11 = jobjTemplates.getJSONArray("data");
            JSONObject jobjl = new JSONObject();
            for (int i = 0; i < jarr11.length(); i++) {
                jobjl = jarr11.getJSONObject(i);
                for (int k = 0; k < compGoalHeader.length; k++) {
                    pcell = new PdfPCell(
                            new Paragraph(
                                    !jobjl.isNull(compGoalDataIndex[k]) ? StringUtil
                                            .serverHTMLStripper(jobjl.getString(compGoalDataIndex[k])) : "",
                                    fontSmallRegular));
                    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);
                    compgTable.addCell(pcell);
                }
            }
            document.add(compgTable);

            document.newPage();
            document.close();
        }
        if (!StringUtil.isNullOrEmpty(request.getParameter("pdfEmail"))) {
            String ipaddr = "";
            if (StringUtil.isNullOrEmpty(request.getHeader("x-real-ip"))) {
                ipaddr = request.getRemoteAddr();
            } else {
                ipaddr = request.getHeader("x-real-ip");
            }
            User u = (User) session.get(User.class, request.getParameter("d"));
            User u1 = (User) session.get(User.class, request.getParameter("userid"));
            Appraisalcycle appcy = (Appraisalcycle) session.get(Appraisalcycle.class,
                    request.getParameter("appraisalcycid"));
            //AuditAction action = (AuditAction) session.load(AuditAction.class, AuditAction.Appraisal_Report_Download);
            String details = "";
            if (StringUtil.equal(request.getParameter("d"), request.getParameter("userid"))) {
                details = "User " + u.getFirstName() + " " + u.getLastName() + " has downloaded self"
                        + " appraisal report for appraisal cycle " + appcy.getCyclename()
                        + " through email link";
            } else {
                details = "Reviewer " + u.getFirstName() + " " + u.getLastName() + " has downloaded "
                        + u1.getFirstName() + " " + u1.getLastName() + "'s"
                        + " appraisal report for appraisal cycle " + appcy.getCyclename()
                        + " through email link";
            }
            tx = session.beginTransaction();
            //@@ProfileHandler.insertAuditLog(session, action, details, ipaddr, u);
            tx.commit();
        } else {
            String details = "";
            User u = null;
            String appCycleID = request.getParameter("appraisalcycid");
            Appraisalcycle appcy = (Appraisalcycle) session.get(Appraisalcycle.class, appCycleID);
            String userID = request.getParameter("userid");
            if (StringUtil.isNullOrEmpty(userID)) {
                userID = AuthHandler.getUserid(request);
                u = (User) session.get(User.class, userID);
                details = "User " + AuthHandler.getFullName(u) + " has downloaded self"
                        + " appraisal report for appraisal cycle " + appcy.getCyclename()
                        + " through Deskera HRMS";
            } else {
                u = (User) session.get(User.class, userID);

                details = "Reviewer "
                        + AuthHandler
                                .getFullName((User) session.get(User.class, AuthHandler.getUserid(request)))
                        + " has downloaded " + AuthHandler.getFullName(u) + "'s"
                        + " appraisal report for appraisal cycle " + appcy.getCyclename()
                        + " through Deskera HRMS";
            }
            tx = session.beginTransaction();
            //@@ProfileHandler.insertAuditLog(session, AuditAction.Appraisal_Report_Download,details,request);
            tx.commit();
        }
    } catch (DocumentException ex) {
        throw ServiceException.FAILURE("AppraisalDetails.AppraisalDetail", ex);
    } catch (JSONException e) {
        throw ServiceException.FAILURE("AppraisalDetails.AppraisalDetail", e);
    } catch (Exception ex) {
        if (tx != null) {
            tx.rollback();
        }
        throw ServiceException.FAILURE(ex.getMessage(), ex);
    } finally {
        writer.close();
    }
    return baos;

}

From source file:com.krawler.spring.exportFunctionality.exportDAOImpl.java

License:Open Source License

public void getHtmlCell(String htmlString, PdfPTable mainTable, String baseUrl) {
    StringReader strReader = new StringReader(
            htmlString.replaceAll("src=\"[^\"]*?video.jsp", "src=\"" + baseUrl + "video.jsp"));
    StyleSheet styles = new StyleSheet();
    try {//from  w w  w. java 2 s .co  m
        for (Object ele : HTMLWorker.parseToList(strReader, styles)) {
            //Phrase phraseStr = new Phrase((Phrase)ele);
            PdfPCell cell = new PdfPCell();
            cell.addElement((Element) ele);
            cell.setBorder(0);
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            mainTable.addCell(cell);
        }
    } catch (Exception e) {
        log.debug("Cannot read html string: " + e.getMessage());
    }
}

From source file:com.krawler.spring.hrms.exportreport.exportAppraisalReportPDFDAOImpl.java

License:Open Source License

private ByteArrayOutputStream AppraisalDetail(HttpServletRequest request, Session session, boolean isEmm,
        String str, String goalstr, String quesansstr)
        throws JSONException, SessionExpiredException, DocumentException, ServiceException, IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    String[] colHeader = {/*from   www.j  a va  2  s.com*/
            messageSource.getMessage("hrms.common.employee.name", null, RequestContextUtils.getLocale(request)),
            messageSource.getMessage("hrms.performance.appraisal.cycle.name", null,
                    RequestContextUtils.getLocale(request)),
            messageSource.getMessage("hrms.performance.appraisal.start.date", null,
                    RequestContextUtils.getLocale(request)),
            messageSource.getMessage("hrms.performance.appraisal.end.date", null,
                    RequestContextUtils.getLocale(request)),
            messageSource.getMessage("hrms.performance.total.appraisals", null,
                    RequestContextUtils.getLocale(request)),
            messageSource.getMessage("hrms.common.Updates.NoofAppraisalsSubmitted", null,
                    RequestContextUtils.getLocale(request)),
            messageSource.getMessage("hrms.performance.overall.self.comments", null,
                    RequestContextUtils.getLocale(request)),
            messageSource.getMessage("hrms.performance.overall.appraiser.comments", null,
                    RequestContextUtils.getLocale(request)),
            messageSource.getMessage("hrms.performance.overall.competency.score", null,
                    RequestContextUtils.getLocale(request)),
            messageSource.getMessage("hrms.performance.competencies", null,
                    RequestContextUtils.getLocale(request)) };
    String[] colHeader1 = {
            messageSource.getMessage("hrms.common.employee.name", null, RequestContextUtils.getLocale(request)),
            messageSource.getMessage("hrms.performance.appraisal.cycle.name", null,
                    RequestContextUtils.getLocale(request)),
            messageSource.getMessage("hrms.performance.appraisal.start.date", null,
                    RequestContextUtils.getLocale(request)),
            messageSource.getMessage("hrms.performance.appraisal.end.date", null,
                    RequestContextUtils.getLocale(request)),
            messageSource.getMessage("hrms.performance.total.appraisals", null,
                    RequestContextUtils.getLocale(request)),
            messageSource.getMessage("hrms.common.Updates.NoofAppraisalsSubmitted", null,
                    RequestContextUtils.getLocale(request)),
            messageSource.getMessage("hrms.performance.overall.appraiser.comments", null,
                    RequestContextUtils.getLocale(request)),
            messageSource.getMessage("hrms.performance.overall.competency.score", null,
                    RequestContextUtils.getLocale(request)),
            messageSource.getMessage("hrms.performance.competencies", null,
                    RequestContextUtils.getLocale(request)) };
    String[] colHeader2 = {
            messageSource.getMessage("hrms.common.employee.name", null, RequestContextUtils.getLocale(request)),
            messageSource.getMessage("hrms.performance.appraisal.cycle.name", null,
                    RequestContextUtils.getLocale(request)),
            messageSource.getMessage("hrms.performance.appraisal.start.date", null,
                    RequestContextUtils.getLocale(request)),
            messageSource.getMessage("hrms.performance.appraisal.end.date", null,
                    RequestContextUtils.getLocale(request)),
            messageSource.getMessage("hrms.performance.total.appraisals", null,
                    RequestContextUtils.getLocale(request)),
            messageSource.getMessage("hrms.common.Updates.NoofAppraisalsSubmitted", null,
                    RequestContextUtils.getLocale(request)),
            messageSource.getMessage("hrms.performance.overall.competency.score", null,
                    RequestContextUtils.getLocale(request)),
            messageSource.getMessage("hrms.performance.competencies", null,
                    RequestContextUtils.getLocale(request)) };
    String[] dataIndex = { "empname", "appcylename", "appcylestdate", "appcylendate", "totalappraisal",
            "appraisalsubmitted", "empcomment", "mancom", "manavgwght", "" };
    String[] dataIndex1 = { "empname", "appcylename", "appcylestdate", "appcylendate", "totalappraisal",
            "appraisalsubmitted", "mancom", "manavgwght", "" };
    String[] dataIndex2 = { "empname", "appcylename", "appcylestdate", "appcylendate", "totalappraisal",
            "appraisalsubmitted", "manavgwght", "" };
    String[] compHeader = {
            messageSource.getMessage("hrms.common.name", null, RequestContextUtils.getLocale(request)),
            messageSource.getMessage("hrms.performance.description", null,
                    RequestContextUtils.getLocale(request)),
            messageSource.getMessage("hrms.performance.self.appraisal.score", null,
                    RequestContextUtils.getLocale(request)),
            messageSource.getMessage("hrms.performance.self.appraisal.comment", null,
                    RequestContextUtils.getLocale(request)),
            messageSource.getMessage("hrms.performance.appraiser.competency.score", null,
                    RequestContextUtils.getLocale(request)),
            messageSource.getMessage("hrms.performance.appraiser.comments", null,
                    RequestContextUtils.getLocale(request)) };
    String[] compDataIndex = { "comptename", "comptdesc", "selfcompscore", "selfcomment", "compmanwght" };
    String[] compGoalHeader = {
            messageSource.getMessage("hrms.performance.goals", null, RequestContextUtils.getLocale(request)),
            messageSource.getMessage("hrms.common.assigned.by", null, RequestContextUtils.getLocale(request)),
            messageSource.getMessage("hrms.performance.appraiser.rating", null,
                    RequestContextUtils.getLocale(request)),
            messageSource.getMessage("hrms.performance.appraiser.comment", 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[] compGoalDataIndex = { "gname", "assignedby", "gmanrat", "mangoalcomment", "gemprat",
            "empgoalcomment" };
    String[] quesAnsHeader1 = {
            messageSource.getMessage("hrms.performance.Questions", null,
                    RequestContextUtils.getLocale(request)),
            messageSource.getMessage("hrms.performance.appraiser.response", null,
                    RequestContextUtils.getLocale(request)) };
    String[] quesAnsHeader = {
            messageSource.getMessage("hrms.performance.Questions", null,
                    RequestContextUtils.getLocale(request)),
            messageSource.getMessage("hrms.performance.appraiser.response", null,
                    RequestContextUtils.getLocale(request)),
            messageSource.getMessage("hrms.performance.self.response", null,
                    RequestContextUtils.getLocale(request)) };
    String[] quesAnsDataIndex = { hrmsAnonymousAppraisalConstants.question,
            hrmsAnonymousAppraisalConstants.answer, hrmsAnonymousAppraisalConstants.employeeanswer };
    String[] quesAnsDataIndex1 = { hrmsAnonymousAppraisalConstants.question,
            hrmsAnonymousAppraisalConstants.answer };
    String managerComments = "";
    String scoreAvg = "";
    String companyid = null;
    PdfWriter writer = null;
    try {
        String usID = request.getParameter("userid");
        String self = request.getParameter("self");
        Boolean removecolumn = false;
        if (!StringUtil.isNullOrEmpty(self) && self.equals("false")) {
            quesAnsHeader = quesAnsHeader1;
            quesAnsDataIndex = quesAnsDataIndex1;
            colHeader = colHeader1;
            dataIndex = dataIndex1;
            removecolumn = true;
        }

        if (StringUtil.isNullOrEmpty(usID)) {
            usID = sessionHandlerImplObj.getUserid(request);
        }
        if (StringUtil.isNullOrEmpty(request.getParameter("pdfEmail")))
            companyid = sessionHandlerImplObj.getCompanyid(request);
        else {
            User u = (User) hibernateTemplate.get(User.class, usID);
            companyid = u.getCompany().getCompanyID();
        }

        HashMap<String, Object> requestParams = new HashMap<String, Object>();
        //                companyid  = sessionHandlerImplObj.getCompanyid(request);

        requestParams.put("companyid", companyid);
        requestParams.put("checklink", "appraisal");
        if (!hrmsCommonDAOObj.checkModule(requestParams).isSuccessFlag()) {
            quesAnsHeader = quesAnsHeader1;
            quesAnsDataIndex = quesAnsDataIndex1;
            colHeader = colHeader1;
            removecolumn = true;
        }
        requestParams.clear();
        requestParams.put("companyid", companyid);
        requestParams.put("checklink", "overallcomments");
        if (!hrmsCommonDAOObj.checkModule(requestParams).isSuccessFlag()) {
            colHeader = colHeader2;
            dataIndex = dataIndex2;
        }

        requestParams.clear();
        Document document = new Document(PageSize.A4.rotate(), 25, 25, 25, 25);
        writer = PdfWriter.getInstance(document, baos);
        writer.setPageEvent(new EndPage());
        document.open();
        java.awt.Color tColor = new Color(9, 9, 9);
        //fontSmallBold.setColor(tColor);
        Paragraph p = new Paragraph();

        PdfPTable table = new PdfPTable(2);
        table.setWidthPercentage(100);
        table.setWidths(new float[] { 55, 75 });

        PdfPTable mainTable = new PdfPTable(1);
        mainTable.setTotalWidth(90);
        mainTable.setWidthPercentage(100);
        mainTable.setSpacingBefore(20);

        PdfPCell headcell = null;
        headcell = new PdfPCell(
                new Paragraph(fontFamilySelector.process(
                        messageSource.getMessage("hrms.performance.appraisal.details", null,
                                RequestContextUtils.getLocale(request)),
                        FontContext.REGULAR_BOLD_HELVETICA, tColor)));
        headcell.setBackgroundColor(new Color(0xEEEEEE));
        headcell.setPadding(5);
        mainTable.addCell(headcell);
        document.add(mainTable);

        //                String str=hrmsManager.getAppraisalReport(session, request);
        JSONObject jobjTemplate = new JSONObject(str);
        com.krawler.utils.json.base.JSONArray jarr = jobjTemplate.getJSONArray("data");
        com.krawler.utils.json.base.JSONArray jarr2 = jarr.getJSONObject(0).getJSONArray("data");
        JSONObject jobjAppraisal = new JSONObject(jarr2.getString(0));
        jarr = jobjAppraisal.getJSONArray("competencies");
        int headlen = colHeader.length;
        if (jarr.length() < 1) {
            headlen = headlen - 2;
        }

        for (int i = 0; i < headlen; i++) {
            PdfPCell pcell = new PdfPCell(
                    new Paragraph(fontFamilySelector.process(colHeader[i], FontContext.MEDIUM_BOLD_HELVETICA)));
            pcell.setBorder(0);
            if (i == 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);
            table.addCell(pcell);

            if (!dataIndex[i].equals("mancom")) {
                pcell = new PdfPCell(new Paragraph(fontFamilySelector.process(!dataIndex[i].equals("")
                        ? !jobjAppraisal.isNull(dataIndex[i]) ? jobjAppraisal.getString(dataIndex[i]) : ""
                        : "", FontContext.SMALL_NORMAL_HELVETICA)));
                if (i == 0)
                    pcell.setPaddingTop(10);
                pcell.setBorder(0);
                pcell.setPaddingLeft(10);
                pcell.setPaddingBottom(4);
                pcell.setBorderColor(new Color(0xF2F2F2));
                pcell.setHorizontalAlignment(Element.ALIGN_LEFT);
                pcell.setVerticalAlignment(Element.ALIGN_LEFT);
                table.addCell(pcell);
            } else {
                if (!jobjAppraisal.isNull(dataIndex[i])) {
                    JSONArray spl = new JSONArray(jobjAppraisal.getString(dataIndex[i]));
                    String strData = "";
                    for (int counter = 0; counter < spl.length(); counter++) {
                        strData += spl.getString(counter) + "\n";
                    }
                    pcell = new PdfPCell(new Paragraph(
                            fontFamilySelector.process(strData, FontContext.SMALL_NORMAL_HELVETICA)));
                    if (i == 0)
                        pcell.setPaddingTop(10);
                    pcell.setBorder(0);
                    pcell.setPaddingLeft(10);
                    pcell.setPaddingBottom(4);
                    pcell.setBorderColor(new Color(0xF2F2F2));
                    pcell.setHorizontalAlignment(Element.ALIGN_LEFT);
                    pcell.setVerticalAlignment(Element.ALIGN_LEFT);
                    table.addCell(pcell);
                }
            }
        }

        document.add(table);

        PdfPTable quesansTable = new PdfPTable(quesAnsHeader.length);
        quesansTable.setWidthPercentage(100);
        if (removecolumn) {
            quesansTable.setWidths(new float[] { 40, 40 });
        } else {
            quesansTable.setWidths(new float[] { 40, 40, 40 });
        }
        quesansTable.setSpacingBefore(20);
        quesansTable.setHeaderRows(1);
        for (int i = 0; i < quesAnsHeader.length; i++) {
            PdfPCell pgcell = new PdfPCell(new Paragraph(
                    fontFamilySelector.process(quesAnsHeader[i], FontContext.MEDIUM_BOLD_HELVETICA)));
            pgcell.setBorder(0);
            pgcell.setBorder(PdfPCell.BOX);
            pgcell.setPadding(4);
            pgcell.setBorderColor(Color.GRAY);
            pgcell.setHorizontalAlignment(Element.ALIGN_CENTER);
            quesansTable.addCell(pgcell);
        }

        JSONObject quesansjobj = new JSONObject(quesansstr);
        JSONArray quesansjarr = quesansjobj.getJSONArray("quesans");
        JSONObject qajobj = new JSONObject();
        for (int i = 0; i < quesansjarr.length(); i++) {
            qajobj = quesansjarr.getJSONObject(i);
            for (int k = 0; k < quesAnsHeader.length; k++) {
                String qatext = !qajobj.isNull(quesAnsDataIndex[k]) ? qajobj.getString(quesAnsDataIndex[k])
                        : "";
                qatext = qatext.replaceAll("~", "\n\n");
                qatext = qatext.replaceAll("\n", "<br/>");
                StyleSheet st = new StyleSheet();
                st.loadTagStyle("body", "face", "HELVETICA");
                st.loadTagStyle("body", "size", "1");
                st.loadTagStyle("body", "leading", "8,0");
                StringReader stringReader = new StringReader(qatext);
                PdfPCell pcell = new PdfPCell();
                ArrayList listStr = HTMLWorker.parseToList(stringReader, st);
                pcell.setPadding(4);
                for (int htmlCount = 0; htmlCount < listStr.size(); ++htmlCount) {
                    if (!listStr.get(htmlCount).toString().equals("[]"))
                        pcell.addElement((Element) listStr.get(htmlCount));
                }

                pcell.setBorder(PdfPCell.BOTTOM | PdfPCell.LEFT | PdfPCell.RIGHT);
                pcell.setBorderColor(Color.GRAY);
                pcell.setPadding(4);
                pcell.setHorizontalAlignment(Element.ALIGN_LEFT);
                pcell.setVerticalAlignment(Element.ALIGN_CENTER);
                quesansTable.addCell(pcell);
            }
        }
        document.add(quesansTable);

        PdfPTable compTable = new PdfPTable(6);
        compTable.setWidthPercentage(100);
        compTable.setWidths(new float[] { 50, 60, 30, 50, 42, 70 });
        compTable.setSpacingBefore(20);
        compTable.setHeaderRows(1);

        for (int i = 0; i < compHeader.length; i++) {
            PdfPCell pcell = new PdfPCell(new Paragraph(
                    fontFamilySelector.process(compHeader[i], FontContext.MEDIUM_BOLD_HELVETICA)));
            pcell.setBorder(0);
            pcell.setBorder(PdfPCell.BOX);
            pcell.setPadding(4);
            pcell.setBorderColor(Color.GRAY);
            pcell.setHorizontalAlignment(Element.ALIGN_CENTER);
            compTable.addCell(pcell);
        }

        for (int i = 0; i < jarr.length(); i++) {
            jobjAppraisal = jarr.getJSONObject(i);
            for (int k = 0; k < compHeader.length; k++) {
                if (k != compHeader.length - 1) {
                    scoreAvg = "";
                    if (!jobjAppraisal.isNull(compDataIndex[k]) && compDataIndex[k].equals("compmanwght")) {
                        scoreAvg = jobjAppraisal.getString("nominalRat");
                        Chunk chunk1 = fontFamilySelector.processChunk(
                                jobjAppraisal.getString(compDataIndex[k]) + "\n\n",
                                FontContext.SMALL_NORMAL_HELVETICA);
                        Chunk chunk2 = null;
                        requestParams.clear();
                        if (!StringUtil.isNullOrEmpty(request.getParameter("pdfEmail"))) {
                            //                                User user=(User)session.get(User.class,request.getParameter("userid"));
                            //                                companyid=user.getCompany().getCompanyID();
                            requestParams.put("companyid", companyid);
                            requestParams.put("checklink", "modaverage");
                            if (hrmsCommonDAOObj.checkModule(requestParams).isSuccessFlag()) {
                                chunk2 = fontFamilySelector.processChunk("["
                                        + messageSource.getMessage("hrms.performance.mod.avg", null,
                                                RequestContextUtils.getLocale(request))
                                        + ":  " + scoreAvg + " ]", FontContext.SMALL_NORMAL_HELVETICA);
                            } else {
                                chunk2 = fontFamilySelector.processChunk("["
                                        + messageSource.getMessage("hrms.performance.avg", null,
                                                RequestContextUtils.getLocale(request))
                                        + ":  " + scoreAvg + " ]", FontContext.SMALL_NORMAL_HELVETICA);
                            }
                        } else {
                            requestParams.put("companyid", companyid);
                            requestParams.put("checklink", "modaverage");
                            if (hrmsCommonDAOObj.checkModule(requestParams).isSuccessFlag()) {
                                chunk2 = fontFamilySelector.processChunk("["
                                        + messageSource.getMessage("hrms.performance.mod.avg", null,
                                                RequestContextUtils.getLocale(request))
                                        + ":  " + scoreAvg + " ]", FontContext.SMALL_NORMAL_HELVETICA);
                            } else {
                                chunk2 = fontFamilySelector.processChunk("["
                                        + messageSource.getMessage("hrms.performance.avg", null,
                                                RequestContextUtils.getLocale(request))
                                        + ":  " + scoreAvg + " ]", FontContext.SMALL_NORMAL_HELVETICA);
                            }
                        }
                        Phrase phrase1 = new Phrase();
                        phrase1.add(chunk1);
                        phrase1.add(chunk2);

                        p = new Paragraph();
                        p.add(phrase1);
                    }
                    PdfPCell pcell = new PdfPCell();
                    if (!scoreAvg.equals("")) {
                        pcell = new PdfPCell(new Paragraph(p));
                        pcell.setPadding(0);
                        pcell.setPaddingTop(2);
                        pcell.setPaddingBottom(4);
                    } else {
                        if (!jobjAppraisal.isNull(compDataIndex[k])) {
                            String htmlStr = jobjAppraisal.getString(compDataIndex[k]);
                            htmlStr = htmlStr.replaceAll("\n", "<br>");
                            StyleSheet st = new StyleSheet();
                            st.loadTagStyle("body", "face", "HELVETICA");
                            st.loadTagStyle("body", "size", "1");
                            st.loadTagStyle("body", "leading", "8,0");
                            HTMLWorker worker = new HTMLWorker(document);
                            StringReader stringReader = new StringReader(htmlStr);
                            ArrayList<Element> listStr = HTMLWorker.parseToList(stringReader, st);
                            pcell.setPadding(4);
                            for (int htmlCount = 0; htmlCount < listStr.size(); ++htmlCount) {
                                if (!listStr.get(htmlCount).getChunks().isEmpty()) {
                                    pcell.addElement(fontFamilySelector.processElement(
                                            listStr.get(htmlCount).getChunks(),
                                            FontContext.SMALL_NORMAL_HELVETICA));
                                }
                            }
                        } else
                            pcell = new PdfPCell(new Paragraph(fontFamilySelector.process(
                                    !jobjAppraisal.isNull(compDataIndex[k]) ? StringUtil
                                            .serverHTMLStripper(jobjAppraisal.getString(compDataIndex[k])) : "",
                                    FontContext.SMALL_NORMAL_HELVETICA)));
                    }
                    pcell.setBorder(PdfPCell.BOTTOM | PdfPCell.LEFT | PdfPCell.RIGHT);
                    pcell.setBorderColor(Color.GRAY);
                    pcell.setHorizontalAlignment(
                            compDataIndex[k].equals("comptename") || compDataIndex[k].equals("comptdesc")
                                    || compDataIndex[k].equals("selfcomment") ? Element.ALIGN_LEFT
                                            : Element.ALIGN_CENTER);
                    pcell.setVerticalAlignment(
                            compDataIndex[k].equals("comptdesc") || compDataIndex[k].equals("comptdesc")
                                    || compDataIndex[k].equals("selfcomment") ? Element.ALIGN_LEFT
                                            : Element.ALIGN_CENTER);
                    compTable.addCell(pcell);

                } else {
                    jarr2 = jobjAppraisal.getJSONArray("comments");
                    managerComments = "";
                    int commentCount = 1;
                    for (int j = jarr2.length() - 1; j >= 0; j--) {
                        jobjTemplate = jarr2.getJSONObject(j);
                        managerComments += commentCount + ")  " + jobjTemplate.getString("managercomment")
                                + "\n\n";
                        commentCount++;
                    }
                    PdfPCell pcell = new PdfPCell(new Paragraph(
                            fontFamilySelector.process(managerComments, FontContext.SMALL_NORMAL_HELVETICA)));
                    pcell.setBorder(PdfPCell.BOTTOM | PdfPCell.LEFT | PdfPCell.RIGHT);
                    pcell.setPadding(4);
                    pcell.setBorderColor(Color.GRAY);
                    pcell.setHorizontalAlignment(Element.ALIGN_LEFT);
                    pcell.setVerticalAlignment(Element.ALIGN_LEFT);
                    compTable.addCell(pcell);
                }
            }
        }
        document.add(compTable);
        PdfPCell pcell;
        if (jarr.length() > 0) {
            PdfPTable helpTable = new PdfPTable(1);
            helpTable.setTotalWidth(90);
            helpTable.setWidthPercentage(100);
            helpTable.setSpacingBefore(20);

            pcell = new PdfPCell(new Paragraph(fontFamilySelector.process(
                    messageSource.getMessage("hrms.performance.mod.avg", null,
                            RequestContextUtils.getLocale(request))
                            + ". : "
                            + messageSource.getMessage("hrms.performance.mode.average.ratings", null,
                                    RequestContextUtils.getLocale(request)),
                    FontContext.SMALL_BOLD_HELVETICA)));
            pcell.setBorder(0);
            pcell.setPadding(4);
            pcell.setHorizontalAlignment(Element.ALIGN_LEFT);
            helpTable.addCell(pcell);

            requestParams.clear();
            requestParams.put("companyid", companyid);
            requestParams.put("checklink", "modaverage");
            if (!StringUtil.isNullOrEmpty(request.getParameter("pdfEmail"))) {
                if (hrmsCommonDAOObj.checkModule(requestParams).isSuccessFlag()) {
                    document.add(helpTable);
                }
            } else {
                if (hrmsCommonDAOObj.checkModule(requestParams).isSuccessFlag()) {
                    document.add(helpTable);
                }
            }
        }
        PdfPTable compgTable = new PdfPTable(6);
        compgTable.setWidthPercentage(100);
        compgTable.setWidths(new float[] { 50, 60, 30, 50, 42, 70 });
        compgTable.setSpacingBefore(20);
        compgTable.setHeaderRows(1);
        for (int i = 0; i < compGoalHeader.length; i++) {
            PdfPCell pgcell = new PdfPCell(new Paragraph(
                    fontFamilySelector.process(compGoalHeader[i], FontContext.MEDIUM_BOLD_HELVETICA)));
            pgcell.setBorder(0);
            pgcell.setBorder(PdfPCell.BOX);
            pgcell.setPadding(4);
            pgcell.setBorderColor(Color.GRAY);
            pgcell.setHorizontalAlignment(Element.ALIGN_CENTER);
            compgTable.addCell(pgcell);
        }

        JSONObject jobjTemplates = new JSONObject(goalstr);
        com.krawler.utils.json.base.JSONArray jarr11 = jobjTemplates.getJSONArray("data");
        JSONObject jobjl = new JSONObject();
        for (int i = 0; i < jarr11.length(); i++) {
            jobjl = jarr11.getJSONObject(i);
            for (int k = 0; k < compHeader.length; k++) {
                pcell = new PdfPCell(
                        new Paragraph(
                                fontFamilySelector.process(
                                        !jobjl.isNull(compGoalDataIndex[k]) ? StringUtil
                                                .serverHTMLStripper(jobjl.getString(compGoalDataIndex[k])) : "",
                                        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);
                compgTable.addCell(pcell);
            }
        }
        document.add(compgTable);

        document.newPage();
        document.close();
    } catch (DocumentException ex) {
        ex.printStackTrace();
        throw ServiceException.FAILURE("AppraisalDetails.AppraisalDetail", ex);
    } catch (JSONException e) {
        e.printStackTrace();
        throw ServiceException.FAILURE("AppraisalDetails.AppraisalDetail", e);
    } catch (Exception ex) {
        ex.printStackTrace();
        throw ServiceException.FAILURE(ex.getMessage(), ex);
    } finally {
        writer.close();
    }
    return baos;

}

From source file:EplanPrinter.RTFWrite.java

License:Open Source License

public String addItem(String comment, String category, String group) throws DocumentException, IOException {
    if (cg.compareTo(group) != 0) {
        count = 1;// w  w w. j a v  a2s .co m
        cg = group;
        cc = category;

        Font groupContent = new Font();
        groupContent.setStyle("bold");
        groupContent.setStyle("underline");
        groupContent.setSize(12);
        Paragraph g = new Paragraph(group, groupContent);

        Font catContent = new Font();
        catContent.setSize(12);
        Paragraph c = new Paragraph(category, catContent);
        c.setIndentationLeft(30);
        document.add(g);
        document.add(c);
    } else if (cc.compareTo(category) != 0) {
        count = 1;
        cc = category;
        Paragraph c = new Paragraph(category);
        c.setIndentationLeft(30);
        document.add(c);
    }
    Paragraph p = new Paragraph();
    //document.add(p);
    String test = count + ". " + comment;
    test = test.replaceAll("<p>", " ");
    test = test.replaceAll("</p>", " ");

    if (test.indexOf("<ol>") != -1) {
        test = test.replaceAll("<ol>", "");
        test = test.replaceAll("</ol>", "");
        test = test.replaceAll("</li>", "<br />");
        int subCount = 1;
        while (test.indexOf("<li>") != -1) {
            test = test.replaceFirst("<li>", subCount + ". ");
            subCount++;
        }
        int marker = test.lastIndexOf("<br />");
        String sub1 = test.substring(0, marker);
        String sub2 = test.substring(marker);
        sub2 = sub2.replaceAll("<br />", "");
        test = sub1 + sub2;
    }
    if (test.indexOf("<ul>") != -1) {
        test = test.replaceAll("<ul>", "");
        test = test.replaceAll("</ul>", "");
        test = test.replaceAll("</li>", "<br />");
        int c = 149;
        char ch = (char) 149;
        test = test.replaceAll("<li>", "&bull;");
        int marker = test.lastIndexOf("<br />");
        String sub1 = test.substring(0, marker);
        String sub2 = test.substring(marker);
        sub2 = sub2.replaceAll("<br />", "");
        test = sub1 + sub2;
    }

    StringReader str = new StringReader(test);
    List<Element> e = HTMLWorker.parseToList(str, null);
    for (int k = 0; k < e.size(); ++k) {
        p.add((com.lowagie.text.Element) e.get(k));
    }

    p.setIndentationLeft(40);
    p.setFirstLineIndent(30);
    document.add(p);

    count = count + 1;

    return "";
}

From source file:fr.aliasource.webmail.server.export.ConversationExporter.java

License:GNU General Public License

@SuppressWarnings("unchecked")
private void exportMessage(Set<ClientMessage> cm, Document d, boolean isForward) throws DocumentException {

    LineSeparator hr = new LineSeparator();
    StyleSheet styles = new StyleSheet();
    Font fnormal = new Font(Font.HELVETICA, 9, Font.NORMAL);
    Font fbold = new Font(Font.HELVETICA, 9, Font.BOLD);

    Iterator<ClientMessage> it = cm.iterator();
    Cell c = null;//from   w w  w.j  a va  2  s. c o m
    while (it.hasNext()) {
        ClientMessage fwdCm = it.next();
        if (isForward) {
            c = new Cell();
        }

        // Subject (only if isForward)
        if (isForward) {
            String subjectText = fwdCm.getSubject();
            String dateText = formatDate(fwdCm.getDate());
            Chunk subject = new Chunk(subjectText, fbold);
            Chunk date = new Chunk(dateText, fbold);
            Paragraph subjectPar = new Paragraph(subject + ", " + date);
            subjectPar.setIndentationLeft(5.0f);
            c.add(subjectPar);
            c.add(Chunk.NEWLINE);
        } else {
            String dateText = formatDate(fwdCm.getDate());
            Chunk date = new Chunk(dateText, fbold);
            Paragraph datePar = new Paragraph(date);
            datePar.setAlignment(Element.ALIGN_RIGHT);
            d.add(datePar);
        }

        // Sender
        String senderText = formatAddress(fwdCm.getSender());
        Chunk sender = new Chunk(senderText, fbold);
        sender.setTextRise(10.0f);
        Paragraph senderPar = new Paragraph(sender);
        if (isForward) {
            senderPar.setIndentationLeft(5.0f);
            c.add(senderPar);
        } else {
            d.add(senderPar);
        }

        appendRecipients(d, c, isForward, "To:", fwdCm.getTo());
        appendRecipients(d, c, isForward, "Cc:", fwdCm.getCc());
        appendRecipients(d, c, isForward, "Bcc:", fwdCm.getBcc());
        if (isForward) {
            c.add(Chunk.NEWLINE);
        }

        // Body
        String bodyText = fwdCm.getBody().getCleanHtml();
        Paragraph bodyPar = new Paragraph();
        bodyPar.setFont(fnormal);
        if (bodyText != null && !bodyText.isEmpty()) {
            try {
                List<Element> objects = HTMLWorker.parseToList(new StringReader(bodyText), styles);
                for (Iterator<Element> iterator = objects.iterator(); iterator.hasNext();) {
                    Element el = iterator.next();
                    if (!(el instanceof Image)) {
                        // bodyPar.add(el);
                        if (isForward) {
                            c.add(el);
                        } else {
                            bodyPar.add(el);
                        }
                    }
                }
            } catch (Exception e) {
                logger.warn("Cannot generate pdf from html body use plain text instead", e);
                // bodyPar.add(fwdCm.getBody().getPlain());
                if (isForward) {
                    Chunk t = new Chunk(fwdCm.getBody().getPlain());
                    t.setFont(fnormal);
                    c.add(t);
                } else {
                    bodyPar.add(fwdCm.getBody().getPlain());
                }
            }
        } else {
            if (isForward) {
                Chunk t = new Chunk(fwdCm.getBody().getPlain());
                t.setFont(fnormal);
                c.add(t);
            } else {
                bodyPar.add(fwdCm.getBody().getPlain());
            }
        }

        if (isForward) {
            // c.add(bodyPar);
            Table t = new Table(1);
            t.setPadding(5);
            t.setBackgroundColor(new Color(242, 242, 242));
            t.addCell(c);
            d.add(t);
        } else {
            bodyPar.setIndentationLeft(15.0f);
            d.add(bodyPar);
        }

        if (fwdCm.getFwdMessages() != null) {
            this.exportMessage(fwdCm.getFwdMessages(), d, true);
        }
        d.add(hr);
    }

}

From source file:it.eng.spagobi.engines.worksheet.exporter.WorkSheetPDFExporter.java

License:Mozilla Public License

public void addHtmlToPdfContentByte(String html, float[] pos) {

    PdfContentByte cb = docWriter.getDirectContent();
    StyleSheet styles = createDefaultStyleSheet();

    ColumnText ct = new ColumnText(cb);
    ct.setSimpleColumn(pos[0], pos[1], pos[2], pos[3]);
    ct.setYLine(pos[3]);/*  w w w.j a v a2s.c  o m*/
    try {
        ArrayList htmlObjs = HTMLWorker.parseToList(new StringReader(html), styles);
        for (int k = 0; k < htmlObjs.size(); ++k) {
            ct.addElement((Element) htmlObjs.get(k));
        }
        ct.go();
    } catch (Exception e) {
        throw new RuntimeException("Could not parse HTML", e);
    }
}

From source file:org.fnppl.opensdx.pdf.PDFUtil.java

License:Open Source License

public static void fromHTMLtoPDF(String html, File saveTo) {
    try {//from  w ww  . j a va2s.  c o  m
        Document document = new Document();
        StyleSheet styles = new StyleSheet();

        PdfWriter.getInstance(document, new FileOutputStream(saveTo));
        document.open();

        ArrayList parts = HTMLWorker.parseToList(new StringReader(html), styles);
        for (int i = 0; i < parts.size(); i++) {
            Element e = (Element) parts.get(i);
            document.add(e);
        }
        document.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:org.sigmah.server.endpoint.export.sigmah.exporter.ProjectReportExporter.java

License:Open Source License

/**
 * Adds the given section to the RTF document.
 * @param section Section to add.//  www  .  j a  va 2s .  co  m
 * @param prefix Current index (for example: 3.1.1).
 * @param index Local index.
 * @param parent Parent element.
 * @throws DocumentException
 */
private void addSection(ProjectReportSectionDTO section, StringBuilder prefix, int index, Object parent)
        throws DocumentException, IOException {

    // Adding the title to the document
    final TextElementArray thisSection;
    if (parent instanceof Document) {
        // Style
        final Paragraph paragraph = new Paragraph(section.getName());
        paragraph.getFont().setSize(16);
        paragraph.getFont().setStyle(Font.BOLD);

        // New chapter
        final Chapter chapter = new Chapter(paragraph, index);
        thisSection = chapter;

    } else if (parent instanceof Chapter) {
        // Style
        final Paragraph paragraph = new Paragraph(section.getName());
        paragraph.getFont().setSize(14);
        paragraph.getFont().setStyle(Font.BOLD);

        // New section
        final Section chapterSection = ((Chapter) parent).addSection(paragraph);
        thisSection = chapterSection;

    } else if (parent instanceof TextElementArray) {
        // Style
        final Paragraph paragraph = new Paragraph(prefix.toString() + ' ' + section.getName());
        paragraph.getFont().setSize(12);
        paragraph.getFont().setStyle(Font.BOLD);

        // New paragraph
        ((TextElementArray) parent).add(paragraph);
        thisSection = (TextElementArray) parent;

    } else
        thisSection = null;

    // Adding the content of this section
    int subIndex = 1;
    final int prefixLength = prefix.length();

    final StyleSheet stylesheet = new StyleSheet();
    stylesheet.loadTagStyle(HtmlTags.PARAGRAPH, "margin", "0");
    stylesheet.loadTagStyle(HtmlTags.PARAGRAPH, "padding", "0");
    stylesheet.loadTagStyle(HtmlTags.DIV, "margin", "0");
    stylesheet.loadTagStyle(HtmlTags.DIV, "padding", "0");

    for (final ProjectReportContent child : section.getChildren()) {

        if (child instanceof ProjectReportSectionDTO) {
            prefix.append(index).append('.');

            addSection((ProjectReportSectionDTO) child, prefix, subIndex, thisSection);
            subIndex++;

            prefix.setLength(prefixLength);

        } else if (child instanceof RichTextElementDTO) {

            final String value = ((RichTextElementDTO) child).getText();
            if (value != null && !"".equals(value)) {

                // HTML parsing.
                final List<Element> elements = HTMLWorker.parseToList(new StringReader(value), stylesheet);

                for (final Element element : elements)
                    thisSection.add(element);
            }
        }
    }

    // Adding the chapter to the document
    if (thisSection instanceof Chapter && parent instanceof Document)
        ((Document) parent).add((Chapter) thisSection);
}

From source file:questions.tables.TableAndHTMLWorker.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    Document document = new Document();
    try {//from w  w w.j  av  a2  s  .c  o  m
        StyleSheet styles = new StyleSheet();
        PdfWriter.getInstance(document, new FileOutputStream(RESULT));
        document.open();
        ArrayList objects;
        objects = HTMLWorker.parseToList(new FileReader(RESOURCE), styles);
        PdfPTable table = new PdfPTable(1);
        PdfPCell cell = new PdfPCell();
        for (int k = 0; k < objects.size(); ++k)
            cell.addElement((Element) objects.get(k));
        table.addCell(cell);
        document.add(table);
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println(e.getMessage());
    }
    document.close();
}

From source file:ro.nextreports.engine.exporter.RtfExporter.java

License:Apache License

private RtfCell renderRtfCell(BandElement bandElement, Object value, int gridRow, int gridColumn, int rowSpan,
        int colSpan, boolean image) {
    Map<String, Object> style = buildCellStyleMap(bandElement, value, gridRow, gridColumn, colSpan);
    String stringValue;//from   ww  w  .  ja  v a2 s. c  om

    FontFactoryImp fact = new FontFactoryImp();
    Font fnt;
    if (bandElement != null) {
        String fontName = (String) style.get(StyleFormatConstants.FONT_NAME_KEY);
        int size = ((Float) style.get(StyleFormatConstants.FONT_SIZE)).intValue();
        fnt = getFont(fontName, size);
    } else {
        fnt = getFont(10);
    }

    RtfCell cell = null;
    boolean specialCell = false;
    if (image) {
        try {
            if (value == null) {
                cell = new RtfCell(new Phrase(IMAGE_NOT_FOUND));
            } else {
                ImageBandElement ibe = (ImageBandElement) bandElement;
                byte[] imageBytes = getImage((String) value, ibe.getWidth(), ibe.getHeight());
                cell = new RtfCell(Image.getInstance(imageBytes));
            }
        } catch (Exception e) {
            cell = new RtfCell(IMAGE_NOT_LOADED);
        }
        specialCell = true;
    } else if (bandElement instanceof HyperlinkBandElement) {
        Hyperlink hyperlink = ((HyperlinkBandElement) bandElement).getHyperlink();
        Anchor anchor = new Anchor(hyperlink.getText(), fnt);
        anchor.setReference(hyperlink.getUrl());
        Phrase ph = new Phrase();
        ph.add(anchor);
        try {
            cell = new RtfCell(ph);
        } catch (BadElementException e) {
            e.printStackTrace();
            cell = new RtfCell(hyperlink.getText());
        }
        specialCell = true;
    } else if (bandElement instanceof ReportBandElement) {
        Report report = ((ReportBandElement) bandElement).getReport();
        ExporterBean eb = null;
        try {
            eb = getSubreportExporterBean(report);
            RtfExporter subExporter = new RtfExporter(eb);
            subExporter.export();
            Table innerTable = subExporter.getTable();
            cell = new RtfCell(innerTable);
        } catch (Exception e) {
            cell = new RtfCell();
            e.printStackTrace();
        } finally {
            if ((eb != null) && (eb.getResult() != null)) {
                eb.getResult().close();
            }
        }
        specialCell = true;
    } else if (bandElement instanceof VariableBandElement) {
        VariableBandElement vbe = (VariableBandElement) bandElement;
        Variable var = VariableFactory.getVariable(vbe.getVariable());
        if (var instanceof PageNoVariable) {
            cell = new RtfCell();
            cell.add(new RtfPageNumber());
            cell.setBorderWidth(0);
            specialCell = true;
        }
    } else if (bandElement instanceof ExpressionBandElement) {
        // special case pageNo inside an expression
        // bandName is not important here (it is used for groupRow
        // computation)
        PrefixSuffix pf = interpretPageNo(bandElement);
        if (pf != null) {
            updateFont(fnt, style);
            cell = new RtfCell();
            if (!"".equals(pf.getPrefix())) {
                cell.add(new Phrase(pf.getPrefix(), fnt));
            }
            cell.add(new RtfPageNumber(fnt));
            if (!"".equals(pf.getSuffix())) {
                cell.add(new Phrase(pf.getSuffix(), fnt));
            }
            specialCell = true;
        }
    } else if (bandElement instanceof ImageColumnBandElement) {
        try {
            String v = StringUtil.getValueAsString(value, null);
            if (StringUtil.BLOB.equals(v)) {
                cell = new RtfCell(new Phrase(StringUtil.BLOB));
            } else {
                ImageColumnBandElement icbe = (ImageColumnBandElement) bandElement;
                byte[] imageD = StringUtil.decodeImage(v);
                byte[] imageBytes = getImage(imageD, icbe.getWidth(), icbe.getHeight());
                cell = new RtfCell(Image.getInstance(imageBytes));
            }
        } catch (Exception e) {
            cell = new RtfCell(IMAGE_NOT_LOADED);
        }
        specialCell = true;
    }
    if (!specialCell) {
        if (style.containsKey(StyleFormatConstants.PATTERN)) {
            stringValue = StringUtil.getValueAsString(value, (String) style.get(StyleFormatConstants.PATTERN),
                    getReportLanguage());
        } else {
            stringValue = StringUtil.getValueAsString(value, null, getReportLanguage());
        }
        if (stringValue == null) {
            stringValue = "";
        }
        Phrase ph;
        if (stringValue.startsWith("<html>")) {
            StringReader reader = new StringReader(stringValue);
            List<Element> elems = new ArrayList<Element>();
            try {
                elems = HTMLWorker.parseToList(reader, new StyleSheet());
                ph = new Phrase();
                for (int i = 0; i < elems.size(); i++) {
                    Element elem = (Element) elems.get(i);
                    ph.add(elem);
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                ph = new Phrase(stringValue, fnt);
            }
        } else {
            ph = new Phrase(stringValue, fnt);
        }

        try {
            cell = new RtfCell(ph);
        } catch (BadElementException e) {
            e.printStackTrace();
            cell = new RtfCell(stringValue);
        }
    }

    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);

    if (colSpan > 1) {
        cell.setColspan(colSpan);
    }

    if (rowSpan > 1) {
        cell.setRowspan(rowSpan);
    }

    setCellStyle(fnt, style, cell);

    return cell;
}