Example usage for com.lowagie.text Font HELVETICA

List of usage examples for com.lowagie.text Font HELVETICA

Introduction

In this page you can find the example usage for com.lowagie.text Font HELVETICA.

Prototype

int HELVETICA

To view the source code for com.lowagie.text Font HELVETICA.

Click Source Link

Document

a possible value of a font family.

Usage

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

License:Open Source License

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

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

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

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

        String str = hrmsManager.getAppraisalReport(session, request);
        JSONObject jobjTemplate = new JSONObject(str);
        com.krawler.utils.json.base.JSONArray jarr = jobjTemplate.getJSONArray("data");
        String goalstr = "";
        User user = (User) session.get(User.class, request.getParameter("userid"));
        companyid = user.getCompany().getCompanyID();
        if (hrmsManager.checkModule("goal", session, request, companyid))
            goalstr = hrmsManager.getAppraisalReportGoalsforGrid(session, request);
        com.krawler.utils.json.base.JSONArray jarr2 = jarr.getJSONObject(0).getJSONArray("data");
        JSONObject jobjAppraisal = new JSONObject(jarr2.getString(0));
        jarr = jobjAppraisal.getJSONArray("competencies");
        int headlen = colHeader.length;
        if (jarr.length() < 1) {
            headlen = headlen - 1;
        }
        for (int i = 0; i < headlen; i++) {
            PdfPCell pcell = new PdfPCell(new Paragraph(colHeader[i], fontMediumBold));
            pcell.setBorder(0);
            if (i == 0)
                pcell.setPaddingTop(10);
            pcell.setPaddingLeft(15);
            pcell.setPaddingBottom(4);
            pcell.setBorderColor(new Color(0xF2F2F2));
            pcell.setHorizontalAlignment(Element.ALIGN_LEFT);
            pcell.setVerticalAlignment(Element.ALIGN_LEFT);
            table.addCell(pcell);

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

        document.add(table);

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

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

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

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

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

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

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

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

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

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

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

}

From source file:com.mycompany.devman.domain.Raport.java

public static void main(String[] args) {

    Document document = new Document(); // Tworzymy dokument

    //* Ustawianie rozmiarw dokumentu
    Rectangle rect = new Rectangle(PageSize.A4); //Tworzenie elementu - rozmiaru dokumentu, ktry bdzie kwadratem o rozmiarze 210mm x 297mm - format a4
    // Utilities.millimetersToPoints(210), Utilities.millimetersToPoints(297)
    document.setPageSize(rect);//w w w.  j  a  v  a  2 s.co  m

    Font[] fonts = { new Font(), new Font(Font.HELVETICA, 14, Font.NORMAL) };

    try { //Blok Try jest po to poniewa nie zawsze moemy mie miejsce tam gdzie chcemy zapisa pdf
        PdfWriter.getInstance(document, new FileOutputStream("raport.pdf"));

        document.open(); //Otwarcie dokumentu - teraz moemy do niego wsadza co kolwiek chcemy
        Paragraph paragraph = new Paragraph();
        paragraph.add("Raport");
        document.add(paragraph); //dodanie paragrafu do dokumentu
        document.close();
    } catch (Exception e) {
        e.printStackTrace(); // Wywietli error
    }

}

From source file:com.silverpeas.kmelia.workflowextensions.SendInKmelia.java

License:Open Source License

private void generatePDFStepHeader(HistoryStep step, com.lowagie.text.Document document) {
    try {//  ww  w  . j  a v  a2 s  .c  o m
        String activity = "";
        if (step.getResolvedState() != null) {
            State resolvedState = step.getProcessInstance().getProcessModel().getState(step.getResolvedState());
            activity = resolvedState.getLabel(getRole(), getLanguage());
        }

        String sAction = null;
        try {
            if ("#question#".equals(step.getAction())) {
                sAction = getString("processManager.question");
            } else if ("#response#".equals(step.getAction())) {
                sAction = getString("processManager.response");
            } else if ("#reAssign#".equals(step.getAction())) {
                sAction = getString("processManager.reAffectation");
            } else {
                Action action = step.getProcessInstance().getProcessModel().getAction(step.getAction());
                sAction = action.getLabel(getRole(), getLanguage());
            }
        } catch (WorkflowException we) {
            sAction = "##";
        }

        String actor = getBestUserDetail().getDisplayedName();

        String date = DateUtil.getOutputDateAndHour(step.getActionDate(), getLanguage());

        String header = "";
        if (StringUtil.isDefined(activity)) {
            header += activity + " - ";
        }
        header += sAction + " (" + actor + " - " + date + ")";

        Font fontHeader = new Font(Font.HELVETICA, 12, Font.NORMAL);

        PdfPCell pCell = new PdfPCell(new Phrase(header, fontHeader));
        pCell.setFixedHeight(28);
        pCell.setBackgroundColor(new Color(239, 239, 239));
        pCell.setVerticalAlignment(Element.ALIGN_MIDDLE);

        PdfPTable pTable = new PdfPTable(1);
        pTable.setWidthPercentage(100);
        pTable.addCell(pCell);

        document.add(pTable);
    } catch (Exception e) {
        SilverTrace.error("workflowEngine", "SendInKmelia.generatePDFStep()", "root.MSG_GEN_ERROR", e);
    }
}

From source file:com.silverpeas.kmelia.workflowextensions.SendInKmelia.java

License:Open Source License

private void generatePDFStepContent(HistoryStep step, com.lowagie.text.Document document) {
    try {// ww  w. j  av  a  2s .  co  m
        Form form;
        if ("#question#".equals(step.getAction()) || "#response#".equals(step.getAction())) {
            // TODO
            form = null;
        } else {
            form = getProcessInstance().getProcessModel().getPresentationForm(step.getAction(), getRole(),
                    getLanguage());
        }

        XmlForm xmlForm = (XmlForm) form;
        if (xmlForm != null && step.getActionRecord() != null) {
            DataRecord data = step.getActionRecord();
            VersioningUtil versioningUtil = new VersioningUtil();

            // Force simpletext displayers because itext cannot display HTML Form fields (select,
            // radio...)
            float[] colsWidth = { 25, 75 };
            PdfPTable tableContent = new PdfPTable(colsWidth);
            tableContent.setWidthPercentage(100);

            PdfPCell cell = null;
            Field field;
            String fieldLabel;
            String fieldValue = "";
            Font fontLabel = new Font(Font.HELVETICA, 10, Font.BOLD);
            Font fontValue = new Font(Font.HELVETICA, 10, Font.NORMAL);
            List<FieldTemplate> fieldTemplates = xmlForm.getFieldTemplates();
            for (FieldTemplate fieldTemplate1 : fieldTemplates) {
                GenericFieldTemplate fieldTemplate = (GenericFieldTemplate) fieldTemplate1;

                fieldLabel = fieldTemplate.getLabel("fr");
                field = data.getField(fieldTemplate.getFieldName());
                String componentId = step.getProcessInstance().getProcessModel().getModelId();

                //          fieldValue = data.getField(fieldTemplate.getFieldName()).getValue();
                //wysiwyg field
                if ("wysiwyg".equals(fieldTemplate.getDisplayerName())) {
                    String file = WysiwygFCKFieldDisplayer.getFile(componentId,
                            getProcessInstance().getInstanceId(), fieldTemplate.getFieldName(), getLanguage());

                    //Extract the text content of the html code
                    Source source = new Source(file);
                    if (source != null) {
                        fieldValue = source.getTextExtractor().toString();
                    }
                }
                //Field file type
                else if (FileField.TYPE.equals(fieldTemplate.getDisplayerName())
                        && StringUtil.isDefined(field.getValue())) {
                    boolean fromCompoVersion = "yes".equals(getOrganizationController()
                            .getComponentParameterValue(componentId, "versionControl"));
                    //Versioning Used
                    if (fromCompoVersion) {
                        DocumentVersion documentVersion = versioningUtil
                                .getDocumentVersion(new DocumentVersionPK(Integer.parseInt(field.getValue())));
                        if (documentVersion != null) {
                            fieldValue = documentVersion.getLogicalName();
                        }
                    } else {
                        AttachmentDetail attDetail = AttachmentController
                                .searchAttachmentByPK(new AttachmentPK(field.getValue(), componentId));
                        if (attDetail != null) {
                            fieldValue = attDetail.getLogicalName(getLanguage());
                        }
                    }
                }
                //Field date type
                else if (fieldTemplate.getTypeName().equals("date")) {
                    fieldValue = DateUtil.getOutputDate(fieldValue, "fr");
                }
                //Others fields type
                else {
                    fieldTemplate.setDisplayerName("simpletext");
                    fieldValue = field.getValue(getLanguage());
                }

                cell = new PdfPCell(new Phrase(fieldLabel, fontLabel));
                cell.setBorderWidth(0);
                cell.setPaddingBottom(5);
                tableContent.addCell(cell);

                cell = new PdfPCell(new Phrase(fieldValue, fontValue));
                cell.setBorderWidth(0);
                cell.setPaddingBottom(5);
                tableContent.addCell(cell);
            }

            document.add(tableContent);
        }
    } catch (Exception e) {
        SilverTrace.error("workflowEngine", "SendInKmelia.generatePDFStep()", "root.MSG_GEN_ERROR", e);
    }
}

From source file:com.stratelia.webactiv.almanach.control.AlmanachPdfGenerator.java

License:Open Source License

static public void buildPdf(String name, AlmanachSessionController almanach, String mode)
        throws AlmanachRuntimeException {
    try {/*ww  w .  ja va 2 s .  c o  m*/
        SilverTrace.info("almanach", "AlmanachPdfGenerator.buildPdf()", "root.MSG_GEN_ENTER_METHOD");

        String fileName = FileRepositoryManager.getTemporaryPath(almanach.getSpaceId(),
                almanach.getComponentId()) + name;
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);

        // we add some meta information to the document
        document.addAuthor(almanach.getSettings().getString("author", ""));
        document.addSubject(almanach.getSettings().getString("subject", ""));
        document.addCreationDate();

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

        try {
            Calendar currentDay = Calendar.getInstance();
            currentDay.setTime(almanach.getCurrentDay());
            String sHeader = almanach.getString("events");
            if (mode.equals(PDF_MONTH_ALLDAYS) || mode.equals(PDF_MONTH_EVENTSONLY)) {
                sHeader += " " + almanach.getString("GML.mois" + currentDay.get(Calendar.MONTH));
            }
            sHeader += " " + currentDay.get(Calendar.YEAR);
            HeaderFooter header = new HeaderFooter(new Phrase(sHeader), false);
            HeaderFooter footer = new HeaderFooter(new Phrase("Page "), true);
            footer.setAlignment(Element.ALIGN_CENTER);

            document.setHeader(header);
            document.setFooter(footer);

            createFirstPage(almanach, document);
            document.newPage();

            Font titleFont = new Font(Font.HELVETICA, 24, Font.NORMAL, new Color(255, 255, 255));
            Paragraph cTitle = new Paragraph(almanach.getString("Almanach") + " "
                    + almanach.getString("GML.mois" + currentDay.get(Calendar.MONTH)) + " "
                    + currentDay.get(Calendar.YEAR), titleFont);
            Chapter chapter = new Chapter(cTitle, 1);

            // Collection<EventDetail> events =
            // almanach.getListRecurrentEvent(mode.equals(PDF_YEAR_EVENTSONLY));
            AlmanachCalendarView almanachView;
            if (PDF_YEAR_EVENTSONLY.equals(mode)) {
                almanachView = almanach.getYearlyAlmanachCalendarView();
            } else {
                almanachView = almanach.getMonthlyAlmanachCalendarView();
            }

            List<DisplayableEventOccurrence> occurrences = almanachView.getEvents();
            generateAlmanach(chapter, almanach, occurrences, mode);

            document.add(chapter);
        } catch (Exception ex) {
            throw new AlmanachRuntimeException("PdfGenerator.generate", AlmanachRuntimeException.WARNING,
                    "AlmanachRuntimeException.EX_PROBLEM_TO_GENERATE_PDF", ex);
        }

        document.close();
        SilverTrace.info("almanach", "AlmanachPdfGenerator.buildPdf()", "root.MSG_GEN_EXIT_METHOD");

    } catch (Exception e) {
        throw new AlmanachRuntimeException("PdfGenerator.generate", AlmanachRuntimeException.WARNING,
                "AlmanachRuntimeException.EX_PROBLEM_TO_GENERATE_PDF", e);
    }

}

From source file:com.stratelia.webactiv.almanach.control.AlmanachPdfGenerator.java

License:Open Source License

private static void createFirstPage(AlmanachSessionController almanach, Document document)
        throws AlmanachException {
    try {//from w  w  w .j a  v  a2s . co  m
        Font masterFont = new Font(Font.HELVETICA, 40, Font.BOLD, new Color(0, 0, 0));
        Paragraph masterTitle = new Paragraph("\n\n\n\n" + almanach.getComponentLabel(), masterFont);

        masterTitle.setAlignment(Element.ALIGN_CENTER);

        Font secondFont = new Font(Font.HELVETICA, 14, Font.NORMAL, new Color(0, 0, 0));
        Paragraph secondTitle = new Paragraph(almanach.getString("editeLe") + " "
                + DateUtil.getOutputDate(new Date(), almanach.getLanguage()) + almanach.getString("Silverpeas"),
                secondFont);

        secondTitle.setAlignment(Element.ALIGN_CENTER);

        document.add(masterTitle);
        document.add(secondTitle);
    } catch (DocumentException e) {
        throw new AlmanachException("AlmanachPdfGenerator.createFirstPage()", SilverpeasException.ERROR,
                "almanach.EX_CANT_CREATE_FIRST_PAGE", e);
    }
}

From source file:com.stratelia.webactiv.almanach.control.AlmanachPdfGenerator.java

License:Open Source License

private static void generateAlmanach(Chapter chapter, AlmanachSessionController almanach,
        List<DisplayableEventOccurrence> occurrences, String mode) throws AlmanachException {

    boolean monthScope = AlmanachPdfGenerator.PDF_MONTH_EVENTSONLY.equals(mode)
            || AlmanachPdfGenerator.PDF_MONTH_ALLDAYS.equals(mode);
    boolean yearScope = AlmanachPdfGenerator.PDF_YEAR_EVENTSONLY.equals(mode);

    int currentDay = -1;
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(almanach.getCurrentDay());
    calendar.set(Calendar.DAY_OF_MONTH, 1);
    int currentMonth = calendar.get(Calendar.MONTH);
    int currentYear = calendar.get(Calendar.YEAR);

    if (yearScope) {
        // start from begin of current year
        calendar.set(Calendar.MONTH, 0);
    }/* ww  w . ja  va  2 s  . c  om*/

    // for each day of the current month
    while ((monthScope && currentMonth == calendar.get(Calendar.MONTH))
            || (yearScope && currentYear == calendar.get(Calendar.YEAR))) {
        Section section = null;
        if (AlmanachPdfGenerator.PDF_MONTH_ALLDAYS.equals(mode)) {
            section = chapter.addSection(generateParagraph(calendar, almanach), 0);
        }

        Font titleTextFont = new Font(Font.BOLD, 12, Font.SYMBOL, new Color(0, 0, 0));

        // get the events of the current day
        for (DisplayableEventOccurrence occurrence : occurrences) {
            EventDetail event = occurrence.getEventDetail();
            String theDay = DateUtil.date2SQLDate(calendar.getTime());
            String startDay = DateUtil.date2SQLDate(occurrence.getStartDate().asDate());
            String startHour = event.getStartHour();
            String endHour = event.getEndHour();

            if (startDay.compareTo(theDay) > 0) {
                continue;
            }

            String endDay = startDay;
            if (event.getEndDate() != null) {
                endDay = DateUtil.date2SQLDate(occurrence.getEndDate().asDate());
            }

            if (endDay.compareTo(theDay) < 0) {
                continue;
            }

            if (calendar.get(Calendar.DAY_OF_MONTH) != currentDay) {
                if (AlmanachPdfGenerator.PDF_MONTH_EVENTSONLY.equals(mode)
                        || AlmanachPdfGenerator.PDF_YEAR_EVENTSONLY.equals(mode)) {
                    section = chapter.addSection(generateParagraph(calendar, almanach), 0);
                }
                currentDay = calendar.get(Calendar.DAY_OF_MONTH);
            }

            Font textFont;
            if (event.getPriority() == 0) {
                textFont = new Font(Font.HELVETICA, 10, Font.NORMAL, new Color(0, 0, 0));
            } else {
                textFont = new Font(Font.HELVETICA, 10, Font.BOLD, new Color(0, 0, 0));
            }

            String eventTitle = event.getTitle();
            if (startDay.compareTo(theDay) == 0 && startHour != null && startHour.length() != 0) {
                eventTitle += " (" + startHour;
                if (endDay.compareTo(theDay) == 0 && endHour != null && endHour.length() != 0) {
                    eventTitle += "-" + endHour;
                }
                eventTitle += ")";
            }

            section.add(new Paragraph(eventTitle, titleTextFont));
            if (StringUtil.isDefined(event.getPlace())) {
                section.add(new Paragraph(event.getPlace(), titleTextFont));
            }
            if (StringUtil.isDefined(event.getDescription(almanach.getLanguage()))) {
                section.add(new Paragraph(event.getDescription(almanach.getLanguage()), textFont));
            }
            section.add(new Paragraph("\n"));

        } // end for
        calendar.add(Calendar.DAY_OF_MONTH, 1);
    }
}

From source file:com.stratelia.webactiv.almanach.control.AlmanachPdfGenerator.java

License:Open Source License

private static Paragraph generateParagraph(Calendar calendar, AlmanachSessionController almanach) {
    Font dateFont = new Font(Font.HELVETICA, 14, Font.NORMAL, new Color(0, 0, 255));
    Paragraph dateSection = new Paragraph(almanach.getString("GML.jour" + calendar.get(Calendar.DAY_OF_WEEK))
            + " " + calendar.get(Calendar.DAY_OF_MONTH) + " "
            + almanach.getString("GML.mois" + calendar.get(Calendar.MONTH)) + " " + calendar.get(Calendar.YEAR),
            dateFont);//  ww w . j  a  v a2  s. c om
    return dateSection;
}

From source file:com.stratelia.webactiv.newsEdito.control.PdfGenerator.java

License:Open Source License

/**
 * Method declaration// w  w w  .  ja v a 2s. c  om
 * @param name
 * @param completePubList
 * @param langue
 * @throws NewsEditoException
 * @see
 */
public static void generatePubList(String name, Collection<CompletePublication> completePubList, String langue)
        throws NewsEditoException {
    SilverTrace.info("NewsEdito", "PdfGenerator.generatePubList", "NewsEdito.MSG_ENTRY_METHOD",
            "Pdf name = " + name);
    try {
        CompletePublication first = completePubList.iterator().next();
        String fileName = FileRepositoryManager.getTemporaryPath(
                first.getPublicationDetail().getPK().getSpace(),
                first.getPublicationDetail().getPK().getComponentName()) + name;
        ResourceLocator message = new ResourceLocator(
                "com.stratelia.webactiv.newsEdito.multilang.newsEditoBundle", langue);
        // creation of the document with a certain size and certain margins
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);

        // we add some meta information to the document
        document.addAuthor("Generateur de PDF Silverpeas");
        document.addSubject("Compilation de publications Silverpeas");
        document.addCreationDate();

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

        createFirstPage(document, langue);

        HeaderFooter header = new HeaderFooter(new Phrase(message.getString("publicationCompilation")), false);
        HeaderFooter footer = new HeaderFooter(new Phrase("Page "), new Phrase("."));

        footer.setAlignment(Element.ALIGN_CENTER);

        document.setHeader(header);
        document.setFooter(footer);

        document.newPage();

        Font titleFont = new Font(Font.HELVETICA, 24, Font.NORMAL, new Color(255, 255, 255));
        Paragraph cTitle = new Paragraph(message.getString("listPublication"), titleFont);
        Chapter chapter = new Chapter(cTitle, 1);

        Iterator<CompletePublication> i = completePubList.iterator();
        CompletePublication complete = null;
        while (i.hasNext()) {
            complete = i.next();

            addPublication(chapter, complete);
        }

        document.add(chapter);

        document.close();
    } catch (Exception e) {
        throw new NewsEditoException("PdfGenerator.generatePubList", NewsEditoException.WARNING,
                "NewsEdito.EX_PROBLEM_TO_GENERATE_PUBLI_LIST", e);
    }
}

From source file:com.stratelia.webactiv.newsEdito.control.PdfGenerator.java

License:Open Source License

/**
 * Method declaration// w  w w.  j av  a 2 s  .c om
 * @param document
 * @param langue
 * @throws NewsEditoException
 * @see
 */
public static void createFirstPage(Document document, String langue) throws NewsEditoException {
    try {
        ResourceLocator message = new ResourceLocator(
                "com.stratelia.webactiv.newsEdito.multilang.newsEditoBundle", langue);

        Font masterFont = new Font(Font.HELVETICA, 40, Font.BOLD, new Color(0, 0, 0));
        Paragraph masterTitle = new Paragraph("\n\n\n\n" + message.getString("journalEditorial"), masterFont);

        masterTitle.setAlignment(Element.ALIGN_CENTER);

        Font secondFont = new Font(Font.HELVETICA, 20, Font.NORMAL, new Color(0, 0, 0));
        Paragraph secondTitle = new Paragraph(
                message.getString("editeLe") + " " + DateUtil.getOutputDate(new Date(), langue), secondFont);

        secondTitle.setAlignment(Element.ALIGN_CENTER);

        document.add(masterTitle);
        document.add(secondTitle);
    } catch (Exception e) {
        throw new NewsEditoException("PdfGenerator.createFirstPage", NewsEditoException.WARNING,
                "NewsEdito.EX_PROBLEM_TO_GENERATE_PAGE_ONE", e);
    }

}