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

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

Introduction

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

Prototype

public HTMLWorker(DocListener document) 

Source Link

Document

Creates a new instance of HTMLWorker

Usage

From source file:ch.emad.business.schuetu.print.PrintAgent.java

License:Apache License

public void saveFileToPrint(String name, String htmlContent) {
    OutputStream os = null;//  w w w  .  j  a  va 2  s  .  c o  m
    try {

        if (!this.init) {
            map.put(name, htmlContent);
            return;
        }

        CleanerProperties props = new CleanerProperties();

        // set some properties to non-default values
        props.setTranslateSpecialEntities(true);
        props.setTransResCharsToNCR(true);
        props.setOmitComments(true);

        // do parsing
        LOG.info("HtmlCleaner! Body wegnehmen");
        TagNode tagNode = new HtmlCleaner(props).clean(htmlContent);

        Object[] o = tagNode.evaluateXPath("//body");

        // serialize to xml file
        new PrettyXmlSerializer(props).writeToFile(
                //  --> mit utf-8 wurden sonderzeichen falsch gedruckt pathprinter+"out.xml", "utf-8"
                (TagNode) o[0], pathprinter + "out.xml");

        String outputFile = pathprinter + name + ".pdf";
        os = new FileOutputStream(outputFile);

        Document doc = new Document(PageSize.A4);
        PdfWriter.getInstance(doc, os);
        doc.open();
        HTMLWorker hw = new HTMLWorker(doc);

        hw.parse(new FileReader(pathprinter + "out.xml"));
        doc.close();

        if (this.applicationEventPublisher != null) {
            ch.emad.model.schuetu.model.integration.File file = new ch.emad.model.schuetu.model.integration.File();
            file.setContent(IOUtils.toByteArray(new FileInputStream(new File(outputFile))));
            file.setName(name + ".pdf");
            OutgoingMessage fileOut = new OutgoingMessage(this);
            fileOut.setPayload(file);
            this.applicationEventPublisher.publishEvent(fileOut);
        }

    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
    } finally {
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
                LOG.error(e.getMessage(), e);
            }
        }
    }
    FileUtils.deleteQuietly(new File(pathprinter + "out.xml"));
}

From source file:com.AppModel.Reportes.GeneraPdf.java

public void generarArchivoPdf(String xml) {
    try {/* w  w w  . j a v  a 2 s  . c o m*/
        Document document = new Document(PageSize.A4);
        PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream("plantillaa.pdf"));
        document.open();
        document.addAuthor("Persona creadora");
        document.addCreator("Software generador");
        document.addCreationDate();
        document.addTitle("Titulo del documento");

        HTMLWorker htmlWorker = new HTMLWorker(document);
        //            String str = "<table>\n"
        //                    + "            <tr>\n"
        //                    + "                <td>Boleta</td>\n"
        //                    + "                <td>Fecha</td>\n"
        //                    + "                <th>Operacion</th>\n"
        //                    + "                <td>Abono</td>\n"
        //                    + "                <td>Interes generado </td>\n"
        //                    + "                <td>Cargo</td>\n"
        //                    + "                <td>Usuario que realizo el movimiento</td>    \n"
        //                    + "            </tr>\n"
        //                    + "            <tr>\n"
        //                    + "                <td align=center>MLOM005817</td>\n"
        //                    + "                <td align=center>2015-04-19 15:53:37.0</td>\n"
        //                    + "                <td align=center>Nuevo empeo</td>\n"
        //                    + "                <td align=center></td>\n"
        //                    + "                <td align=center></td>\n"
        //                    + "                <td align=center>$533.00</td>\n"
        //                    + "                <td align=center>admin</td>\n"
        //                    + "            </tr>\n"
        //                    + "            <tr>\n"
        //                    + "                <td align=center>MLOM005817</td>\n"
        //                    + "                <td align=center>2015-04-19 15:56:04.0</td>\n"
        //                    + "                <td align=center>Extension de contrato</td>\n"
        //                    + "                <td align=center></td><td align=center>$1.44</td>\n"
        //                    + "                <td align=center></td>\n"
        //                    + "                <td align=center>admin</td>\n"
        //                    + "            </tr>\n"
        //                    + "            <tr>\n"
        //                    + "                <td align=center>MLOM005817</td>\n"
        //                    + "                <td align=center>2015-04-19 16:00:51.0</td>\n"
        //                    + "                <td align=center>Desempeo</td>\n"
        //                    + "                <td align=center>$554.64 </td>\n"
        //                    + "                <td align=center>$21.64 </td>\n"
        //                    + "                <td align=center></td>\n"
        //                    + "                <td align=center>admin</td>\n"
        //                    + "            </tr>\n"
        //                    + "            <tr>\n"
        //                    + "                <td align=center>MLOM005818</td>\n"
        //                    + "                <td align=center>2015-04-19 16:37:24.0</td>\n"
        //                    + "                <td align=center>Refrendo</td>\n"
        //                    + "                <td align=center>$533.00 </td>\n"
        //                    + "                <td align=center>$21.64 </td>\n"
        //                    + "                <td align=center>$533.00 </td>\n"
        //                    + "                <td align=center>admin</td>\n"
        //                    + "            </tr>\n"
        //                    + "            <tr>\n"
        //                    + "                <td></td>\n"
        //                    + "                <td></td>\n"
        //                    + "                <td></td>\n"
        //                    + "                <td></td>\n"
        //                    + "                <td align=center><b>$1,087.64 pesos</b> </td>\n"
        //                    + "                <td align=center><b>$44.72 pesos</b> </td>\n"
        //                    + "                <td align=center><b>$1,066.00 pesos</b> </td>\n"
        //                    + "            </tr>\n"
        //                    + "            <tr style=height:50px;>\n"
        //                    + "                <td align=right colspan=7> </td>\n"
        //                    + "                <td  align=left colspan=5><b>El monto de apertura dia fue de: $90000.0 pesos</b> </td>\n"
        //                    + "                <td  align=left colspan=5><b id='saldoAlCierre' title='89511.72'>Saldo al cierre: $89511.72 pesos</b> </td>\n"
        //                    + "            </tr>\n"
        //                    + "        </table>";
        String str = "<table>\n" + "            <tr>\n" + "                <td>Boleta</td>\n"
                + "                <td>Fecha</td>\n" + "                <th>Operacion</th>\n"
                + "                <td>Abono</td>\n" + "                <td>Interes generado </td>\n"
                + "                <td>Cargo</td>\n"
                + "                <td>Usuario que realizo el movimiento</td>    \n" + "            </tr>\n"
                + "            <tr>\n" + "                <td align=center>MLOM005817</td>\n"
                + "                <td align=center>2015-04-19 15:53:37.0</td>\n"
                + "                <td align=center>Nuevo empeo</td>\n"
                + "                <td align=center></td>\n" + "                <td align=center></td>\n"
                + "                <td align=center>$533.00</td>\n"
                + "                <td align=center>admin</td>\n" + "            </tr>\n" + "            <tr>\n"
                + "                <td align=center>MLOM005817</td>\n"
                + "                <td align=center>2015-04-19 15:56:04.0</td>\n"
                + "                <td align=center>Extension de contrato</td>\n"
                + "                <td align=center></td><td align=center>$1.44</td>\n"
                + "                <td align=center></td>\n" + "                <td align=center>admin</td>\n"
                + "            </tr>\n" + "            <tr>\n"
                + "                <td align=center>MLOM005817</td>\n"
                + "                <td align=center>2015-04-19 16:00:51.0</td>\n"
                + "                <td align=center>Desempeo</td>\n"
                + "                <td align=center>$554.64 </td>\n"
                + "                <td align=center>$21.64 </td>\n" + "                <td align=center></td>\n"
                + "                <td align=center>admin</td>\n" + "            </tr>\n" + "            <tr>\n"
                + "                <td align=center>MLOM005818</td>\n"
                + "                <td align=center>2015-04-19 16:37:24.0</td>\n"
                + "                <td align=center>Refrendo</td>\n"
                + "                <td align=center>$533.00 </td>\n"
                + "                <td align=center>$21.64 </td>\n"
                + "                <td align=center>$533.00 </td>\n"
                + "                <td align=center>admin</td>\n" + "            </tr>\n" + "            <tr>\n"
                + "                <td></td>\n" + "                <td></td>\n" + "                <td></td>\n"
                + "                <td align=center><b>$1,087.64 pesos</b> </td>\n"
                + "                <td align=center><b>$44.72 pesos</b> </td>\n"
                + "                <td align=center><b>$1,066.00 pesos</b> </td>\n" + "            </tr>\n"
                + "            <tr style=height:50px;>\n" + "                <td align=right colspan=7> </td>\n"
                + "            </tr><tr>\n"
                + "                <td  align=left colspan=5><b>El monto de apertura dia fue de: $90000.0 pesos</b> </td>\n"
                + "            </tr><tr>\n"
                + "                <td  align=left colspan=5><b id='saldoAlCierre' title='89511.72'>Saldo al cierre: $89511.72 pesos</b> </td>\n"
                + "            </tr>\n" + "        </table>";
        htmlWorker.parse(new StringReader(str));
        document.close();
    } catch (Exception e) {
        System.out.println("" + e.getMessage());
    }

}

From source file:com.aripd.clms.service.ContractServiceBean.java

@Override
public void generatePdf(ContractEntity contract) {
    String baseFontUrl = "/fonts/Quivira.otf";
    FontFactory.register(baseFontUrl);/*from  w  w  w  . j a  v  a 2s. c  om*/

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    try {
        BaseFont bf = BaseFont.createFont(baseFontUrl, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        Font font18n = new Font(bf, 18, Font.NORMAL);
        Font font12n = new Font(bf, 12, Font.NORMAL);
        Font font8n = new Font(bf, 8, Font.NORMAL);
        Font font8nbu = new Font(bf, 8, Font.BOLD | Font.UNDERLINE);
        Font font8ng = new Font(bf, 8, Font.NORMAL, Color.DARK_GRAY);
        Font font6n = new Font(bf, 6, Font.NORMAL);

        Document document = new Document(PageSize.A4);
        PdfWriter writer = PdfWriter.getInstance(document, output);
        document.open();
        addMetaData(document);
        addTitlePage(document, contract);
        Image imgBlue = Image.getInstance(1, 1, 3, 8, new byte[] { (byte) 0, (byte) 0, (byte) 255, });
        imgBlue.scaleAbsolute(document.getPageSize().getWidth(), 10);
        imgBlue.setAbsolutePosition(0, document.getPageSize().getHeight() - imgBlue.getScaledHeight());
        PdfImage stream = new PdfImage(imgBlue, "", null);
        stream.put(new PdfName("ITXT_SpecialId"), new PdfName("123456789"));
        PdfIndirectObject ref = writer.addToBody(stream);
        imgBlue.setDirectReference(ref.getIndirectReference());
        document.add(imgBlue);

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

        PdfPCell cell = new PdfPCell(new Paragraph(contract.getName(), font18n));
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setColspan(2);
        cell.setPadding(5);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("Version: " + contract.getVersion(), font8n));
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setColspan(2);
        cell.setPadding(5);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("Review: " + contract.getReview(), font8n));
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setColspan(2);
        cell.setPadding(5);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph(contract.getRemark(), font12n));
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setColspan(2);
        cell.setPadding(5);
        table.addCell(cell);
        document.add(table);
        // Start a new page
        document.newPage();

        HTMLWorker htmlWorker = new HTMLWorker(document);
        htmlWorker.parse(new StringReader(contract.getRemark()));
        // Start a new page
        document.newPage();

        document.add(new Paragraph("Review Board", font18n));
        document.add(new LineSeparator(0.5f, 100, null, 0, -5));

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

        cell = new PdfPCell(new Paragraph("Review Board", font18n));
        cell.setColspan(3);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("Version", font12n));
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("Date", font12n));
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("Review", font12n));
        table.addCell(cell);
        for (HistoryContractEntity history : historyContractService.listing(contract)) {
            cell = new PdfPCell(new Paragraph(history.getVersion().toString(), font8n));
            table.addCell(cell);
            cell = new PdfPCell(new Paragraph(history.getStartdate().toString(), font8n));
            table.addCell(cell);
            cell = new PdfPCell(new Paragraph(history.getReview(), font8n));
            table.addCell(cell);
        }
        document.add(table);

        document.close();

        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
        response.reset();
        response.addHeader("Content-Type", "application/force-download");
        String filename = URLEncoder.encode(contract.getName() + ".pdf", "UTF-8");
        //            response.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + filename);
        response.getOutputStream().write(output.toByteArray());
        response.getOutputStream().flush();
        context.responseComplete();
        context.renderResponse();

    } catch (BadPdfFormatException | IOException ex) {
        Logger.getLogger(ContractServiceBean.class.getName()).log(Level.SEVERE, null, ex);
    } catch (DocumentException ex) {
        Logger.getLogger(ContractServiceBean.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.ikon.util.DocConverter.java

License:Open Source License

/**
 * Convert HTML to PDF//from w w w  . j a v a2 s .  c om
 */
public void html2pdf(File input, File output) throws ConversionException, DatabaseException, IOException {
    log.debug("** Convert from HTML to PDF **");
    FileOutputStream fos = null;

    try {
        fos = new FileOutputStream(output);

        // Make conversion
        Document doc = new Document(PageSize.A4);
        PdfWriter.getInstance(doc, fos);
        doc.open();
        HTMLWorker html = new HTMLWorker(doc);
        html.parse(new FileReader(input));
        doc.close();
    } catch (DocumentException e) {
        throw new ConversionException("Exception in conversion: " + e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(fos);
    }
}

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   ww  w.  ja v a2 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.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 = {//  ww w  .  j  ava  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.openkm.util.DocConverter.java

License:Open Source License

/**
 * Convert SRC to PDF//w  ww .  ja  v  a2s.  co  m
 */
public void src2pdf(File input, File output, String lang)
        throws ConversionException, DatabaseException, IOException {
    log.debug("** Convert from SRC to PDF **");
    FileOutputStream fos = null;
    FileInputStream fis = null;

    try {
        fos = new FileOutputStream(output);
        fis = new FileInputStream(input);

        // Make syntax highlight
        String source = IOUtils.toString(fis);
        JaSHi jashi = new JaSHi(source, lang);
        // jashi.EnableLineNumbers(1);
        String parsed = jashi.ParseCode();

        // Make conversion to PDF
        Document doc = new Document(PageSize.A4.rotate());
        PdfWriter.getInstance(doc, fos);
        doc.open();
        HTMLWorker html = new HTMLWorker(doc);
        html.parse(new StringReader(parsed));
        doc.close();
    } catch (DocumentException e) {
        throw new ConversionException("Exception in conversion: " + e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(fos);
    }
}

From source file:MbView.MbAbonos.java

public void imprimeDespiese(Object document) {
    try {/*from   w w w. j  ava 2  s .c o m*/
        Document pdf = (Document) document;
        pdf.open();
        pdf.setPageSize(PageSize.A4);
        HTMLWorker htmlWorker = new HTMLWorker(pdf);
        String html = "";
        html = new ImprimeDespiece().imprime(lstDespiece);
        htmlWorker.parse(new StringReader(html));
    } catch (Exception e) {
        System.out.println("Ocurrio un error generando pdf: " + e.toString());
    }

}

From source file:org.jbpm.designer.web.server.TransformerServlet.java

License:Apache License

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.setCharacterEncoding("UTF-8");
    String formattedSvgEncoded = req.getParameter("fsvg");
    String uuid = Utils.getUUID(req);
    String profileName = Utils.getDefaultProfileName(req.getParameter("profile"));
    String transformto = req.getParameter("transformto");
    String jpdl = req.getParameter("jpdl");
    String gpd = req.getParameter("gpd");
    String bpmn2in = req.getParameter("bpmn2");
    String jsonin = req.getParameter("json");
    String preprocessingData = req.getParameter("pp");
    String respaction = req.getParameter("respaction");
    String pp = req.getParameter("pp");
    String processid = req.getParameter("processid");
    String sourceEnc = req.getParameter("enc");
    String convertServiceTasks = req.getParameter("convertservicetasks");
    String htmlSourceEnc = req.getParameter("htmlenc");

    String formattedSvg = (formattedSvgEncoded == null ? ""
            : new String(Base64.decodeBase64(formattedSvgEncoded), "UTF-8"));

    String htmlSource = (htmlSourceEnc == null ? "" : new String(Base64.decodeBase64(htmlSourceEnc), "UTF-8"));

    if (sourceEnc != null && sourceEnc.equals("true")) {
        bpmn2in = new String(Base64.decodeBase64(bpmn2in), "UTF-8");
    }//from   w  w  w .  j  a  v  a 2s.com

    if (profile == null) {
        profile = _profileService.findProfile(req, profileName);
    }

    DroolsFactoryImpl.init();
    BpsimFactoryImpl.init();

    Repository repository = profile.getRepository();

    if (transformto != null && transformto.equals(TO_PDF)) {
        if (respaction != null && respaction.equals(RESPACTION_SHOWURL)) {

            try {
                ByteArrayOutputStream pdfBout = new ByteArrayOutputStream();
                Document pdfDoc = new Document(PageSize.A4);
                PdfWriter pdfWriter = PdfWriter.getInstance(pdfDoc, pdfBout);
                pdfDoc.open();
                pdfDoc.addCreationDate();

                PNGTranscoder t = new PNGTranscoder();
                t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen");

                float widthHint = getFloatParam(req, SVG_WIDTH_PARAM, DEFAULT_PDF_WIDTH);
                float heightHint = getFloatParam(req, SVG_HEIGHT_PARAM, DEFAULT_PDF_HEIGHT);
                String objStyle = "style=\"width:" + widthHint + "px;height:" + heightHint + "px;\"";
                t.addTranscodingHint(SVGAbstractTranscoder.KEY_WIDTH, widthHint);
                t.addTranscodingHint(SVGAbstractTranscoder.KEY_HEIGHT, heightHint);

                ByteArrayOutputStream imageBout = new ByteArrayOutputStream();
                TranscoderInput input = new TranscoderInput(new StringReader(formattedSvg));
                TranscoderOutput output = new TranscoderOutput(imageBout);
                t.transcode(input, output);

                Image processImage = Image.getInstance(imageBout.toByteArray());
                scalePDFImage(pdfDoc, processImage);
                pdfDoc.add(processImage);

                pdfDoc.close();

                resp.setCharacterEncoding("UTF-8");
                resp.setContentType("text/plain");

                resp.getWriter()
                        .write("<object type=\"application/pdf\" " + objStyle
                                + " data=\"data:application/pdf;base64,"
                                + Base64.encodeBase64String(pdfBout.toByteArray()) + "\"></object>");
            } catch (Exception e) {
                resp.sendError(500, e.getMessage());
            }
        } else {
            storeInRepository(uuid, formattedSvg, transformto, processid, repository);

            try {
                resp.setCharacterEncoding("UTF-8");
                resp.setContentType("application/pdf");
                if (processid != null) {
                    resp.setHeader("Content-Disposition", "attachment; filename=\"" + processid + ".pdf\"");
                } else {
                    resp.setHeader("Content-Disposition", "attachment; filename=\"" + uuid + ".pdf\"");
                }

                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                Document pdfDoc = new Document(PageSize.A4);
                PdfWriter pdfWriter = PdfWriter.getInstance(pdfDoc, resp.getOutputStream());
                pdfDoc.open();
                pdfDoc.addCreationDate();

                PNGTranscoder t = new PNGTranscoder();
                t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen");
                TranscoderInput input = new TranscoderInput(new StringReader(formattedSvg));
                TranscoderOutput output = new TranscoderOutput(bout);
                t.transcode(input, output);

                Image processImage = Image.getInstance(bout.toByteArray());
                scalePDFImage(pdfDoc, processImage);
                pdfDoc.add(processImage);

                pdfDoc.close();
            } catch (Exception e) {
                resp.sendError(500, e.getMessage());
            }
        }
    } else if (transformto != null && transformto.equals(TO_PNG)) {
        try {
            if (respaction != null && respaction.equals(RESPACTION_SHOWURL)) {
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                PNGTranscoder t = new PNGTranscoder();
                t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen");
                TranscoderInput input = new TranscoderInput(new StringReader(formattedSvg));
                TranscoderOutput output = new TranscoderOutput(bout);
                t.transcode(input, output);
                resp.setCharacterEncoding("UTF-8");
                resp.setContentType("text/plain");
                if (req.getParameter(SVG_WIDTH_PARAM) != null && req.getParameter(SVG_HEIGHT_PARAM) != null) {
                    int widthHint = (int) getFloatParam(req, SVG_WIDTH_PARAM, DEFAULT_PDF_WIDTH);
                    int heightHint = (int) getFloatParam(req, SVG_HEIGHT_PARAM, DEFAULT_PDF_HEIGHT);
                    resp.getWriter()
                            .write("<img width=\"" + widthHint + "\" height=\"" + heightHint
                                    + "\" src=\"data:image/png;base64,"
                                    + Base64.encodeBase64String(bout.toByteArray()) + "\">");
                } else {
                    resp.getWriter().write("<img src=\"data:image/png;base64,"
                            + Base64.encodeBase64String(bout.toByteArray()) + "\">");
                }
            } else {
                storeInRepository(uuid, formattedSvg, transformto, processid, repository);
                resp.setContentType("image/png");
                if (processid != null) {
                    resp.setHeader("Content-Disposition", "attachment; filename=\"" + processid + ".png\"");
                } else {
                    resp.setHeader("Content-Disposition", "attachment; filename=\"" + uuid + ".png\"");
                }

                PNGTranscoder t = new PNGTranscoder();
                t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen");
                TranscoderInput input = new TranscoderInput(new StringReader(formattedSvg));
                TranscoderOutput output = new TranscoderOutput(resp.getOutputStream());
                t.transcode(input, output);
            }
        } catch (TranscoderException e) {
            resp.sendError(500, e.getMessage());
        }
    } else if (transformto != null && transformto.equals(TO_SVG)) {
        storeInRepository(uuid, formattedSvg, transformto, processid, repository);
    } else if (transformto != null && transformto.equals(BPMN2_TO_JSON)) {
        try {
            if (convertServiceTasks != null && convertServiceTasks.equals("true")) {
                bpmn2in = bpmn2in.replaceAll("drools:taskName=\".*?\"", "drools:taskName=\"ReadOnlyService\"");
                bpmn2in = bpmn2in.replaceAll("tns:taskName=\".*?\"", "tns:taskName=\"ReadOnlyService\"");
            }

            Definitions def = ((JbpmProfileImpl) profile).getDefinitions(bpmn2in);
            def.setTargetNamespace("http://www.omg.org/bpmn20");

            if (convertServiceTasks != null && convertServiceTasks.equals("true")) {
                // fix the data input associations for converted tasks
                List<RootElement> rootElements = def.getRootElements();
                for (RootElement root : rootElements) {
                    if (root instanceof Process) {
                        updateTaskDataInputs((Process) root, def);
                    }
                }
            }

            // get the xml from Definitions
            ResourceSet rSet = new ResourceSetImpl();
            rSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("bpmn2",
                    new JBPMBpmn2ResourceFactoryImpl());
            JBPMBpmn2ResourceImpl bpmn2resource = (JBPMBpmn2ResourceImpl) rSet
                    .createResource(URI.createURI("virtual.bpmn2"));
            bpmn2resource.getDefaultLoadOptions().put(JBPMBpmn2ResourceImpl.OPTION_ENCODING, "UTF-8");
            bpmn2resource.getDefaultLoadOptions().put(JBPMBpmn2ResourceImpl.OPTION_DEFER_IDREF_RESOLUTION,
                    true);
            bpmn2resource.getDefaultLoadOptions().put(JBPMBpmn2ResourceImpl.OPTION_DISABLE_NOTIFY, true);
            bpmn2resource.getDefaultLoadOptions().put(JBPMBpmn2ResourceImpl.OPTION_PROCESS_DANGLING_HREF,
                    JBPMBpmn2ResourceImpl.OPTION_PROCESS_DANGLING_HREF_RECORD);
            bpmn2resource.setEncoding("UTF-8");
            rSet.getResources().add(bpmn2resource);
            bpmn2resource.getContents().add(def);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            bpmn2resource.save(outputStream, new HashMap<Object, Object>());
            String revisedXmlModel = outputStream.toString();
            String json = profile.createUnmarshaller().parseModel(revisedXmlModel, profile, pp);
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("application/json");
            resp.getWriter().print(json);
        } catch (Exception e) {
            e.printStackTrace();
            _logger.error(e.getMessage());
            resp.setContentType("application/json");
            resp.getWriter().print("{}");
        }
    } else if (transformto != null && transformto.equals(JSON_TO_BPMN2)) {
        try {
            DroolsFactoryImpl.init();
            BpsimFactoryImpl.init();
            if (preprocessingData == null) {
                preprocessingData = "";
            }
            String processXML = profile.createMarshaller().parseModel(jsonin, preprocessingData);
            resp.setContentType("application/xml");
            resp.getWriter().print(processXML);
        } catch (Exception e) {
            e.printStackTrace();
            _logger.error(e.getMessage());
            resp.setContentType("application/xml");
            resp.getWriter().print("");
        }
    } else if (transformto != null && transformto.equals(HTML_TO_PDF)) {
        try {
            resp.setContentType("application/pdf");
            if (processid != null) {
                resp.setHeader("Content-Disposition", "attachment; filename=\"" + processid + ".pdf\"");
            } else {
                resp.setHeader("Content-Disposition", "attachment; filename=\"" + uuid + ".pdf\"");
            }

            Document pdfDoc = new Document(PageSize.A4);
            PdfWriter pdfWriter = PdfWriter.getInstance(pdfDoc, resp.getOutputStream());
            pdfDoc.open();
            pdfDoc.addCreator("jBPM Designer");
            pdfDoc.addSubject("Business Process Documentation");
            pdfDoc.addCreationDate();
            pdfDoc.addTitle("Process Documentation");

            HTMLWorker htmlWorker = new HTMLWorker(pdfDoc);
            htmlWorker.parse(new StringReader(htmlSource));
            pdfDoc.close();
        } catch (DocumentException e) {
            resp.sendError(500, e.getMessage());
        }
    }
}