Example usage for com.lowagie.text.html.simpleparser StyleSheet loadTagStyle

List of usage examples for com.lowagie.text.html.simpleparser StyleSheet loadTagStyle

Introduction

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

Prototype

public void loadTagStyle(String tag, String key, String value) 

Source Link

Usage

From source file:classroom.filmfestival_c.Movies25.java

@SuppressWarnings("unchecked")
public static boolean addText(String s, PdfContentByte canvas, float[] f, float size, boolean simulate)
        throws DocumentException, IOException {
    StyleSheet styles = new StyleSheet();
    styles.loadTagStyle("p", "size", size + "px");
    styles.loadTagStyle("p", "align", "justify");
    styles.loadTagStyle("p", "hyphenation", "en_us");
    ArrayList<Element> objects = HTMLWorker.parseToList(new StringReader(s), styles, null);
    ColumnText ct = new ColumnText(canvas);
    ct.setAlignment(Element.ALIGN_JUSTIFIED);
    ct.setLeading(size * 1.2f);//  w  ww .  ja  v a2  s.c o m
    ct.setSimpleColumn(f[1] + 2, f[2] + 2, f[3] - 2, f[4]);
    for (Element element : objects) {
        ct.addElement(element);
    }
    return ColumnText.hasMoreText(ct.go(simulate));
}

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;//from  w  w  w .  j a  va2  s .  co 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.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 av a  2s  .  c om*/
            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:com.shmsoft.dmass.print.Html2Pdf.java

License:Apache License

/**
 * Bad rendering, perhaps used only for Windows
 *//*from   ww w .  j a  va  2s  .  c om*/
@SuppressWarnings({ "rawtypes", "unchecked" })
private static void convertHtml2Pdf(Reader htmlReader, String outputFile) throws Exception {
    Document pdfDocument = new Document();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PdfWriter.getInstance(pdfDocument, baos);
    pdfDocument.open();
    StyleSheet styles = new StyleSheet();
    styles.loadTagStyle("body", "font", "Times New Roman");

    ImageProvider imageProvider = new ImageProvider() {

        @Override
        public Image getImage(String src, HashMap arg1, ChainedProperties arg2, DocListener arg3) {

            try {
                Image image = Image.getInstance(IOUtils.toByteArray(
                        getClass().getClassLoader().getResourceAsStream(ParameterProcessing.NO_IMAGE_FILE)));
                return image;
            } catch (Exception e) {
                System.out.println("Problem with html->pdf imaging, image provider fault");
            }

            return null;
        }

    };

    HashMap interfaceProps = new HashMap();
    interfaceProps.put("img_provider", imageProvider);

    ArrayList arrayElementList = HTMLWorker.parseToList(htmlReader, styles, interfaceProps);
    for (int i = 0; i < arrayElementList.size(); ++i) {
        Element e = (Element) arrayElementList.get(i);
        pdfDocument.add(e);
    }
    pdfDocument.close();
    byte[] bs = baos.toByteArray();
    File pdfFile = new File(outputFile);
    FileOutputStream out = new FileOutputStream(pdfFile);
    out.write(bs);
    out.close();
}

From source file:org.freeeed.print.Html2Pdf.java

License:Apache License

/**
 * Bad rendering, perhaps used only for Windows
 *///w  w w .  j  a  v  a2s.c  o  m
@SuppressWarnings({ "rawtypes", "unchecked" })
private static void convertHtml2Pdf(Reader htmlReader, File outputFile) throws Exception {
    Document pdfDocument = new Document();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PdfWriter.getInstance(pdfDocument, baos);
    pdfDocument.open();
    StyleSheet styles = new StyleSheet();
    styles.loadTagStyle("body", "font", "Times New Roman");

    ImageProvider imageProvider = new ImageProvider() {
        @Override
        public Image getImage(String src, HashMap arg1, ChainedProperties arg2, DocListener arg3) {

            try {
                return Image.getInstance(IOUtils.toByteArray(
                        getClass().getClassLoader().getResourceAsStream(ParameterProcessing.NO_IMAGE_FILE)));
            } catch (IOException | BadElementException e) {
                logger.warn("Problem with html to pdf rendering.", e);
            }

            return null;
        }
    };

    HashMap interfaceProps = new HashMap();
    interfaceProps.put("img_provider", imageProvider);

    ArrayList arrayElementList = HTMLWorker.parseToList(htmlReader, styles, interfaceProps);
    for (int i = 0; i < arrayElementList.size(); ++i) {
        Element e = (Element) arrayElementList.get(i);
        pdfDocument.add(e);
    }
    pdfDocument.close();
    byte[] bs = baos.toByteArray();
    FileOutputStream out = new FileOutputStream(outputFile);
    out.write(bs);
    out.close();
}

From source file:org.nuxeo.ecm.platform.ui.web.component.seam.UIHtmlText.java

License:Open Source License

/**
 * XXX - this needs some work//from   w  w  w.j  a  v  a  2s .c  o m
 */
private StyleSheet getStyle() {
    StyleSheet styles = new StyleSheet();
    styles.loadTagStyle("body", "leading", "16,0");
    return styles;
}

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./*from  w  w w.  j av  a2s .c o 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:test.itext.html.HtmlWorker.java

License:Open Source License

public static void main(String args[]) {
    Document document = new Document();
    StyleSheet st = new StyleSheet();
    st.loadTagStyle("body", "leading", "16,0");

    StringBuffer sb = new StringBuffer();
    sb.append("<root><p><u><em><strong>Product Description</strong></em></u></p>");
    sb.append(/*from  w  w  w . j av a2 s.c om*/
            "<p style=\"text-align: justify\">Face the biggest test in soccer and come out on top with FIFA 08. Bringing home the silverware is harder than ever before as you make critical selection decisions and battle bookings, injuries and fatigue to produce a winning team. Defeat the toughest opposition with your in-form players overpower teams with quick movement off the ball and varying attacks. Select from fully-licensed teams, raise your game with the help of the crowd and start your quest for glory.</p>");
    sb.append("<p style=\"text-align: justify\"><strong>Starting the game</strong></p>");
    sb.append(
            "<p style=\"text-align: justify\">Highlight EA SPORTS FIFA 08 in the games menu on your phone. Press Select (or OK on the D-Pad) to start the game. You are prompted to choose sound either on or off. After you make your selection, the EA Mobile splash screen appears followed by EA SPORTS FIFA 08 title sequence and the Main Menu.<br />");
    sb.append("</p>");
    sb.append("<p style=\"text-align: justify\"><strong>Main Menu</strong></p>");
    sb.append("<ul>");
    sb.append("<li>Play Start a game.</li>");
    sb.append(
            "<li>Options View the available game options: sound, vibration, match length, difficulty, etc</li>");
    sb.append("<li>Help View detailed instructions and information on how to play the game.</li>");
    sb.append("<li>About Display copyright information and customer service information.</li>");
    sb.append("<li>More Games Display link to more EA Mobile games.</li>");
    sb.append("<li>Exit Exit the game.</li>");
    sb.append("</ul></root>");

    try {
        PdfWriter.getInstance(document, new FileOutputStream("html2.pdf"));
        Reader reader = new StringReader(sb.toString());
        document.open();
        ArrayList p = HTMLWorker.parseToList(reader, st);
        for (int k = 0; k < p.size(); ++k)
            document.add((Element) p.get(k));
    } catch (Exception e) {
        e.printStackTrace();
    }
    document.close();
}

From source file:test.itext.html.ParsingHtmlSnippets.java

License:Open Source License

public static void main(String args[]) throws Exception {
    /* chapter14/ParsingHtmlSnippets.java */
    //com.lowagie.text.ElementTags 

    StringBuffer sb = new StringBuffer();
    sb.append("<root><p><u><em><strong>Product Description</strong></em></u></p>");
    sb.append(//w  w  w  . j a  va2 s  . c o  m
            "<p style=\"text-align: justify\">Face the biggest test in soccer and come out on top with FIFA 08. Bringing home the silverware is harder than ever before as you make critical selection decisions and battle bookings, injuries and fatigue to produce a winning team. Defeat the toughest opposition with your in-form players overpower teams with quick movement off the ball and varying attacks. Select from fully-licensed teams, raise your game with the help of the crowd and start your quest for glory.</p>");
    sb.append("<p style=\"text-align: justify\"><strong>Starting the game</strong></p>");
    sb.append(
            "<p style=\"text-align: justify\">Highlight EA SPORTS FIFA 08 in the games menu on your phone. Press Select (or OK on the D-Pad) to start the game. You are prompted to choose sound either on or off. After you make your selection, the EA Mobile splash screen appears followed by EA SPORTS FIFA 08 title sequence and the Main Menu.<br />");
    sb.append("</p>");
    sb.append("<p style=\"text-align: justify\"><strong>Main Menu</strong></p>");
    sb.append("<ul>");
    sb.append("<li>Play Start a game.</li>");
    sb.append(
            "<li>Options View the available game options: sound, vibration, match length, difficulty, etc</li>");
    sb.append("<li>Help View detailed instructions and information on how to play the game.</li>");
    sb.append("<li>About Display copyright information and customer service information.</li>");
    sb.append("<li>More Games Display link to more EA Mobile games.</li>");
    sb.append("<li>Exit Exit the game.</li>");
    sb.append("</ul></root>");
    Reader reader = new StringReader(sb.toString());

    Document document = new Document();
    StyleSheet styles = new StyleSheet();
    styles.loadTagStyle("ol", "leading", "16,0");

    PdfWriter.getInstance(document, new FileOutputStream("html3.pdf"));
    document.open();
    ArrayList objects;
    objects = HTMLWorker.parseToList(reader, styles);
    for (int k = 0; k < objects.size(); ++k) {
        Element ele = (Element) objects.get(k);
        System.out.println(ele.type());
        document.add(ele);
    }
    document.close();
}