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

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

Introduction

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

Prototype

public StyleSheet() 

Source Link

Document

Creates a new instance of StyleSheet

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);/*  ww w .j  a v  a2s  . 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 .java2  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 ww  .  j a  v  a  2 s. c o  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 = {/*w w w  .  j  a v  a 2 s.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
 *//*w w w  . ja v a2 s.  c  o  m*/
@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: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   ww w  .  j  a v  a 2s .co 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

private StyleSheet createDefaultStyleSheet() {
    StyleSheet styles = new StyleSheet();

    //      styles.loadTagStyle("ul", "face", "Times");
    //      styles.loadTagStyle("ul", "size", "25px");
    //      styles.loadTagStyle("ul", "leading", "15f");
    //      styles.loadTagStyle("ul", "list-style-type", "square");
    //      styles.loadTagStyle("li", "face", "Times");
    //      styles.loadTagStyle("li", "size", "25px");
    //      styles.loadTagStyle("li", "leading", "15f");
    //      styles.loadTagStyle("p", "face", "Times");
    //      styles.loadTagStyle("p", "size", "11px");
    //      styles.loadTagStyle("p", "leading", "12f");
    //      styles.loadTagStyle("p", "spacingAfter", "6x");

    return styles;
}

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

License:Open Source License

public static void fromHTMLtoPDF(String html, File saveTo) {
    try {// ww  w.ja  va2  s  .c om
        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.freeeed.print.Html2Pdf.java

License:Apache License

/**
 * Bad rendering, perhaps used only for Windows
 */// w  ww  .j av a  2s  .  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.ja va  2  s  .c  o m
 */
private StyleSheet getStyle() {
    StyleSheet styles = new StyleSheet();
    styles.loadTagStyle("body", "leading", "16,0");
    return styles;
}