Example usage for java.io ByteArrayOutputStream size

List of usage examples for java.io ByteArrayOutputStream size

Introduction

In this page you can find the example usage for java.io ByteArrayOutputStream size.

Prototype

public synchronized int size() 

Source Link

Document

Returns the current size of the buffer.

Usage

From source file:org.kuali.kfs.module.purap.document.web.struts.PurchaseOrderAction.java

/**
 * Print a particular selected PO Quote as a PDF.
 *
 * @param mapping An ActionMapping/*ww  w.  j a va  2  s  . com*/
 * @param form An ActionForm -- The PO Quote must be selected here.
 * @param request The HttpServletRequest
 * @param response The HttpServletResponse
 * @throws Exception
 * @return An ActionForward
 */
public ActionForward printPoQuote(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    // String poDocId = request.getParameter("docId");
    // PurchaseOrderDocument po = (PurchaseOrderDocument)
    // SpringContext.getBean(DocumentService.class).getByDocumentHeaderId(poDocId);
    // Integer poSelectedVendorId = new Integer(request.getParameter("quoteVendorId"));
    KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
    PurchaseOrderDocument po = (PurchaseOrderDocument) kualiDocumentFormBase.getDocument();
    PurchaseOrderVendorQuote poVendorQuote = po.getPurchaseOrderVendorQuotes().get(getSelectedLine(request));
    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    poVendorQuote.setTransmitPrintDisplayed(false);
    try {
        StringBuffer sbFilename = new StringBuffer();
        sbFilename.append("PURAP_PO_QUOTE_");
        sbFilename.append(po.getPurapDocumentIdentifier());
        sbFilename.append("_");
        sbFilename.append(System.currentTimeMillis());
        sbFilename.append(".pdf");

        boolean success = SpringContext.getBean(PurchaseOrderService.class).printPurchaseOrderQuotePDF(po,
                poVendorQuote, baosPDF);

        if (!success) {
            poVendorQuote.setTransmitPrintDisplayed(true);
            poVendorQuote.setPdfDisplayedToUserOnce(false);

            if (baosPDF != null) {
                baosPDF.reset();
            }
            return mapping.findForward(KFSConstants.MAPPING_BASIC);
        }
        response.setHeader("Cache-Control", "max-age=30");
        response.setContentType("application/pdf");
        StringBuffer sbContentDispValue = new StringBuffer();
        // sbContentDispValue.append("inline");
        sbContentDispValue.append("attachment");
        sbContentDispValue.append("; filename=");
        sbContentDispValue.append(sbFilename);

        response.setHeader("Content-disposition", sbContentDispValue.toString());

        response.setContentLength(baosPDF.size());

        ServletOutputStream sos;

        sos = response.getOutputStream();

        baosPDF.writeTo(sos);

        sos.flush();

    } finally {
        if (baosPDF != null) {
            baosPDF.reset();
        }
    }

    return null;
}

From source file:com.kohmiho.mpsr.export.PDFGenerator.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)/*from ww  w .  j av a2 s .  com*/
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String mpsrID = request.getParameter("MPSR_ID");
    if (null == mpsrID)
        return;

    MPSRProjectInfo basicInfo = MPSRProjectInfo.getInstance(mpsrID);
    MPSRExecutiveSummary exeSummary = MPSRExecutiveSummary.getInstance(mpsrID);
    MPSRStatusSummary statusSummary = MPSRStatusSummary.getInstance(mpsrID);
    MPSRFunctionPerformance funcPerform = MPSRFunctionPerformance.getInstance(mpsrID);
    MPSRCostPerformance costPerform = MPSRCostPerformance.getInstance(mpsrID);
    MPSRSchedulePerformance[] schedulePerform = MPSRSchedulePerformance.getInstance(mpsrID);
    MPSRSafety safety = MPSRSafety.getInstance(mpsrID);
    MPSRAuthorization auth = MPSRAuthorization.getInstance(mpsrID);
    MPSRBudget budget = MPSRBudget.getInstance(mpsrID);
    MPSRCostReport[] costRpt = MPSRCostReport.getInstance(mpsrID);
    MPSRSchedule schedule = MPSRSchedule.getInstance(mpsrID);
    MPSRMilestone[] milestones = MPSRMilestone.getInstance(mpsrID);
    MPSRLPE lpe = MPSRLPE.getInstance(mpsrID);
    MPSRInsidePlantDesign[] ipds = MPSRInsidePlantDesign.getInstance(mpsrID);
    MPSROutsidePlantDesign[] opds = MPSROutsidePlantDesign.getInstance(mpsrID);
    MPSRProcure procure = MPSRProcure.getInstance(mpsrID);
    MPSRApprovedChanges[] approvedChanges = MPSRApprovedChanges.getInstance(mpsrID);
    MPSRPendingChanges[] pendingChanges = MPSRPendingChanges.getInstance(mpsrID);
    MPSRInsidePlantConstruction[] ipcs = MPSRInsidePlantConstruction.getInstance(mpsrID);
    MPSROutsidePlantConstruction[] opcs = MPSROutsidePlantConstruction.getInstance(mpsrID);
    MPSRAppendix[] appendixs = MPSRAppendix.getInstance(mpsrID);
    MPSRAttachment[] attachments = MPSRAttachment.getInstance(mpsrID);

    // response.setContentType("application/pdf");
    // response.setHeader("Content-Disposition",
    // "attachment; filename=\"test.pdf\"");

    Font fontNormal = null;
    Font fontCoverTitle = new Font(FontFamily.HELVETICA, 20, Font.BOLD);
    Font fontCoverTableHeader = new Font(FontFamily.HELVETICA, 16, Font.BOLD);
    Font fontCoverTableContent = new Font(FontFamily.HELVETICA, 16);
    Font fontChapterHeader = new Font(FontFamily.HELVETICA, 18, Font.BOLD);
    Font fontSection1Header = new Font(FontFamily.HELVETICA, 16, Font.BOLD);
    Font fontSection2Header = new Font(FontFamily.HELVETICA, 14, Font.BOLD);
    Font fontWork = new Font(FontFamily.HELVETICA, 12, Font.UNDERLINE);

    Font fontTableCaption = new Font(FontFamily.TIMES_ROMAN, 12, Font.BOLD);
    Font fontTableColumnHeader = new Font(FontFamily.HELVETICA, 12, Font.BOLD);
    Font fontTableColumnHeaderYellow = new Font(FontFamily.HELVETICA, 12, Font.BOLD);
    fontTableColumnHeaderYellow.setColor(BaseColor.YELLOW);
    Font fontTableRowTitle = new Font(FontFamily.HELVETICA, 12, Font.ITALIC);
    Font fontTableCellBold = new Font(FontFamily.HELVETICA, 12, Font.BOLD);
    Font fontTableNote = new Font(FontFamily.HELVETICA, 10, Font.ITALIC);
    Font fontImageCaption = new Font(FontFamily.TIMES_ROMAN, 9, Font.BOLD);

    Font fontPOTableHeader = new Font(FontFamily.HELVETICA, 10, Font.BOLD);
    fontPOTableHeader.setColor(BaseColor.YELLOW);
    Font fontPOTable = new Font(FontFamily.HELVETICA, 9);
    Font fontPOTableSummary = new Font(FontFamily.HELVETICA, 9, Font.BOLD);

    Font fontPageHeader = new Font(FontFamily.HELVETICA, 8);
    Font fontPageFooter = new Font(FontFamily.HELVETICA, 10);

    Phrase[] headerTexts = new Phrase[] { new Phrase("ELECTRIC DELIVERY", fontPageHeader),
            new Phrase("DELIVERY PROJECTS & CONSTRUCTION (DP&C)", fontPageHeader),
            new Phrase("PROJECT MONTHLY REPORT", fontPageHeader) };

    Paragraph paragraph = null;
    PdfPTable table = null;
    PdfPCell cell = null;

    Document document = new Document(DEFAULT_PAGE_SIZE, 36, 36, 9 * 10, 36);
    ByteArrayOutputStream baosOrig = new ByteArrayOutputStream();
    XMLWorkerHelper xmlWorker = XMLWorkerHelper.getInstance();

    try {
        PdfWriter writer = PdfWriter.getInstance(document, baosOrig);
        writer.setStrictImageSequence(true);
        writer.setLinearPageMode();
        writer.setViewerPreferences(PdfWriter.PageModeUseOutlines | PdfWriter.FitWindow);

        Image icon = getEmbeddedImage(getServletContext(), "/resource/image/company_logo.png");

        document.open();

        PdfOutline root = writer.getRootOutline();

        // *******************************************************************************************//

        // addOutline(root, writer, MPSRUI.TREE_0);

        for (int i = 0; i < 2; i++) {
            document.add(new Paragraph(" "));
        }

        String[] titles = { " DELIVERY PROJECTS & CONSTRUCTION", "MONTHLY REPORT",
                basicInfo.getReportMonthYear(), basicInfo.getProjectTitle(),
                "PROJECT No. " + basicInfo.getProjectDefinition() };
        int[] spaceingAfters = { 48, 48, 48, 24, 48 };
        for (int i = 0; i < titles.length; i++) {
            paragraph = new Paragraph();
            paragraph.setSpacingAfter(spaceingAfters[i]);
            paragraph.setFont(fontCoverTitle);
            paragraph.setAlignment(Element.ALIGN_CENTER);
            paragraph.add(new Chunk(titles[i]));
            document.add(paragraph);
        }

        addCoverImage(document, MPSRUI.getFilePath(mpsrID, basicInfo.getFileName()));

        document.add(new Paragraph(" "));

        table = new PdfPTable(2);
        table.addCell(new Phrase("Client", fontCoverTableHeader));
        table.addCell(new Phrase(basicInfo.getProjectManager(), fontCoverTableContent));
        table.addCell(new Phrase("Location", fontCoverTableHeader));
        table.addCell(new Phrase(basicInfo.getProjectDirector(), fontCoverTableContent));
        document.add(table);

        // *******************************************************************************************//

        document.resetPageCount();
        document.add(Chunk.NEXTPAGE);
        writer.setPageEvent(new MPSRPageEventHelper(icon, headerTexts, fontPageFooter));

        // *******************************************************************************************//

        PdfOutline outline1 = addOutline(root, writer, MPSRUI.TREE_1);
        addSectionTitle(document, MPSRUI.TREE_1, fontChapterHeader, 0, 0, 12);

        PdfOutline outline2 = addOutline(outline1, writer, "1.1");

        addOutline(outline2, writer, MPSRUI.TREE_1_1_1);
        addSectionTitle(document, MPSRUI.TREE_1_1_1, fontSection2Header, 12, 12, 0);
        addParagraph(document, writer, xmlWorker, exeSummary.getDesc_1_1_1(), fontNormal, 12, 0, 12);

        addOutline(outline2, writer, MPSRUI.TREE_1_1_2);
        addSectionTitle(document, MPSRUI.TREE_1_1_2, fontSection2Header, 12, 12, 0);
        addParagraph(document, writer, xmlWorker, exeSummary.getDesc_1_1_2(), fontNormal, 12, 0, 12);

        addOutline(outline2, writer, MPSRUI.TREE_1_1_3);
        addSectionTitle(document, MPSRUI.TREE_1_1_3, fontSection2Header, 12, 12, 0);
        addParagraph(document, writer, xmlWorker, exeSummary.getDesc_1_1_3(), fontNormal, 12, 0, 12);

        addOutline(outline2, writer, MPSRUI.TREE_1_1_4);
        addSectionTitle(document, MPSRUI.TREE_1_1_4, fontSection2Header, 12, 12, 0);
        addParagraph(document, writer, xmlWorker, exeSummary.getDesc_1_1_4(), fontNormal, 12, 0, 12);

        // *******************************************************************************************//
        // 1.2 Status Summary
        // *******************************************************************************************//

        outline2 = addOutline(outline1, writer, MPSRUI.TREE_1_2);
        addSectionTitle(document, MPSRUI.TREE_1_2, fontSection1Header, 6, 12, 12);

        paragraph = new Paragraph();
        paragraph.add(basicInfo.getProjectTitle());
        paragraph.setSpacingAfter(4);
        document.add(paragraph);

        table = new PdfPTable(5);
        table.setTotalWidth(500);
        table.setLockedWidth(true);
        table.setWidths(new int[] { 3, 1, 1, 1, 1 });

        cell = new PdfPCell(
                new Phrase("Project #: " + basicInfo.getProjectDefinition(), fontTableColumnHeader));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell);
        String[] headers = { "Status", "Approved (Include RnC)", "To Date", "At Completion" };
        for (String header : headers) {
            cell = new PdfPCell(new Phrase(header, fontTableColumnHeader));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
        }

        String[][] cellValues = {
                { "Budget ($M)", statusSummary.getBudgetStatus(),
                        !"".equals(statusSummary.getBudgetApproved()) ? CURRENCY_FORMATTER
                                .format(Double.parseDouble(statusSummary.getBudgetApproved())) : "",
                        !"".equals(statusSummary.getBudgetToDate())
                                ? CURRENCY_FORMATTER.format(Double.parseDouble(statusSummary.getBudgetToDate()))
                                : "",
                        !"".equals(statusSummary.getBudgetAtCompletion()) ? CURRENCY_FORMATTER
                                .format(Double.parseDouble(statusSummary.getBudgetAtCompletion())) : "" },
                { "Schedule - Duration (months)", statusSummary.getScheduleStatus(),
                        statusSummary.getScheduleApproved(), statusSummary.getScheduleToDate(),
                        statusSummary.getScheduleAtCompletion() },
                { "In-Service Date", statusSummary.getInServiceDateStatus(),
                        statusSummary.getInServiceDateApproved(), statusSummary.getInServiceDateToDate(),
                        statusSummary.getInServiceDateAtCompletion() } };
        for (int i = 0; i < cellValues.length; i++) {
            table.addCell(new Phrase(cellValues[i][0]));
            cell = new PdfPCell(new Phrase(cellValues[i][1]));
            cell.setBackgroundColor(getBackgroundColor(cellValues[i][1]));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);
            for (int j = 2; j < 5; j++) {
                cell = new PdfPCell(new Phrase(cellValues[i][j]));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(cell);
            }
        }

        document.add(table);

        // -------------------------------------------------------------------//

        paragraph = new Paragraph("Legend:");
        paragraph.setSpacingAfter(4);
        paragraph.setIndentationLeft(25);
        document.add(paragraph);

        table = new PdfPTable(3);
        table.setTotalWidth(240);
        table.setLockedWidth(true);
        table.setHorizontalAlignment(Element.ALIGN_LEFT);
        String[] legends = { "On Target", "At Risk", "Off Target" };
        for (String legend : legends) {
            cell = new PdfPCell(new Phrase(legend));
            cell.setBackgroundColor(getBackgroundColor(legend));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setMinimumHeight(18);
            cell.setPadding(0);
            table.addCell(cell);
        }

        paragraph = new Paragraph();
        paragraph.add(table);
        paragraph.setIndentationLeft(25);
        document.add(paragraph);

        // *******************************************************************************************//
        // 1.2.1 Functional Area Performance Indicators
        // *******************************************************************************************//

        addOutline(outline2, writer, MPSRUI.TREE_1_2_1);
        addSectionTitle(document, MPSRUI.TREE_1_2_1, fontSection2Header, 12, 12, 12);

        table = new PdfPTable(4);
        table.setTotalWidth(550);
        table.setLockedWidth(true);
        table.setWidths(new int[] { 4, 1, 1, 4 });

        headers = new String[] { "Activities", "Current Status", "Trend",
                "Comments (main performance drives)" };
        for (String header : headers) {
            cell = new PdfPCell(new Phrase(header, fontTableColumnHeader));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
        }

        Image imgArrowUp = getEmbeddedImage(getServletContext(), "/VAADIN/themes/MPSR/img/Arrow_Up.png");
        Image imgArrowDown = getEmbeddedImage(getServletContext(), "/VAADIN/themes/MPSR/img/Arrow_Down.png");
        Image imgArrowEven = getEmbeddedImage(getServletContext(), "/VAADIN/themes/MPSR/img/Arrow_Even.png");
        Image[] images = { imgArrowUp, imgArrowDown, imgArrowEven };
        for (Image image : images) {
            image.scaleToFit(12, 12);
        }

        cellValues = new String[][] {
                { "Project - " + basicInfo.getProjectTitle(), funcPerform.getProjectStatus(),
                        funcPerform.getProjectTrend(), funcPerform.getProjectComment() },
                { "  Target Budget", funcPerform.getTargetBudgetStatus(), funcPerform.getTargetBudgetTrend(),
                        funcPerform.getTargetBudgetComment() },
                { "  Safety", funcPerform.getSafetyStatus(), funcPerform.getSafetyTrend(),
                        funcPerform.getSafetyComment() },
                { "  Licensing & Permitting", funcPerform.getLicensingStatus(), funcPerform.getLicensingTrend(),
                        funcPerform.getLicensingComment() },
                { "  Corporate Properties", funcPerform.getCorporateStatus(), funcPerform.getCorporateTrend(),
                        funcPerform.getCorporateComment() },
                { "  Inside Plant Design & Engineering", funcPerform.getIPDEStatus(),
                        funcPerform.getIPDETrend(), funcPerform.getIPDEComment() },
                { "  Public Outreach", funcPerform.getOutreachStatus(), funcPerform.getOutreachTrend(),
                        funcPerform.getOutreachComment() },
                { "  Procurement", funcPerform.getProcureStatus(), funcPerform.getProcureTrend(),
                        funcPerform.getProcureComment() },
                { "  Construction", funcPerform.getConstructionStatus(), funcPerform.getConstructionTrend(),
                        funcPerform.getConstructionComment() },
                { "  Environmental - Resource Recovery", funcPerform.getEnviromentStatus(),
                        funcPerform.getEnviromentTrend(), funcPerform.getEnviromentComment() },
                { "  Salvage", funcPerform.getSalvageStatus(), funcPerform.getSalvageTrend(),
                        funcPerform.getSalvageComment() },
                { "  Withdrawal", funcPerform.getWithdrawalStatus(), funcPerform.getWithdrawalTrend(),
                        funcPerform.getWithdrawalComment() } };
        for (int i = 0; i < cellValues.length; i++) {
            cell = new PdfPCell(new Phrase(cellValues[i][0]));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(cellValues[i][1]));
            cell.setBackgroundColor(getBackgroundColor(cellValues[i][1]));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            if ("Up".equals(cellValues[i][2])) {
                cell = new PdfPCell(imgArrowUp);
            } else if ("Down".equals(cellValues[i][2])) {
                cell = new PdfPCell(imgArrowDown);
            } else if ("Even".equals(cellValues[i][2])) {
                cell = new PdfPCell(imgArrowEven);
            } else {
                cell = new PdfPCell();
            }

            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(cellValues[i][3]));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            table.addCell(cell);
        }

        document.add(table);

        // *******************************************************************************************//

        document.setPageSize(DEFAULT_PAGE_SIZE.rotate());
        document.add(Chunk.NEXTPAGE);

        addOutline(outline2, writer, MPSRUI.TREE_1_2_2);
        addSectionTitle(document, MPSRUI.TREE_1_2_2, fontSection2Header, 12, 12, 12);
        addImage(document, MPSRUI.getFilePath(mpsrID, costPerform.getFileName()));

        // *******************************************************************************************//
        // 1.2.3 Schedule Performance
        // *******************************************************************************************//

        document.add(Chunk.NEXTPAGE);

        addOutline(outline2, writer, MPSRUI.TREE_1_2_3);
        addSectionTitle(document, MPSRUI.TREE_1_2_3, fontSection2Header, 12, 12, 12);

        table = new PdfPTable(9);
        table.setTotalWidth(750);
        table.setLockedWidth(true);
        table.setWidths(new int[] { 3, 1, 1, 1, 1, 1, 1, 1, 1 });
        table.setHorizontalAlignment(Element.ALIGN_CENTER);

        headers = new String[] { "WBS", "Original Duration", "Remaining Duration", "Baseline Start Date",
                "Baseline Finish Date", "Start Date", "Finish Date", "Total Float", "Status" };
        for (String header : headers) {
            cell = new PdfPCell(new Phrase(header, fontTableColumnHeaderYellow));
            cell.setBackgroundColor(BaseColor.BLUE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
        }

        for (int i = 0; i < schedulePerform.length; i++) {
            cell = new PdfPCell(new Phrase(schedulePerform[i].getWBS()));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(Double.toString(schedulePerform[i].getOriginalDuration())));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(Double.toString(schedulePerform[i].getRemainingDuration())));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(schedulePerform[i].getPlannedStartDate()));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(schedulePerform[i].getPlannedFinishDate()));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(schedulePerform[i].getStartDate()));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(schedulePerform[i].getFinishDate()));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(schedulePerform[i].getTotalFloat()));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(schedulePerform[i].getStatus()));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
        }

        table.setHeaderRows(1);

        document.add(table);

        // *******************************************************************************************//
        // 1.3 Project Change Control
        // *******************************************************************************************//

        document.setPageSize(DEFAULT_PAGE_SIZE);
        document.add(Chunk.NEXTPAGE);

        outline2 = addOutline(outline1, writer, MPSRUI.TREE_1_3);
        addSectionTitle(document, MPSRUI.TREE_1_3, fontSection1Header, 6, 12, 12);

        addOutline(outline2, writer, MPSRUI.TREE_1_3_1);
        addSectionTitle(document, MPSRUI.TREE_1_3_1, fontSection2Header, 12, 12, 0);
        addParagraph(document, writer, xmlWorker, exeSummary.getDesc_1_3_1(), fontNormal, 12, 0, 12);

        addOutline(outline2, writer, MPSRUI.TREE_1_3_2);
        addSectionTitle(document, MPSRUI.TREE_1_3_2, fontSection2Header, 12, 12, 0);
        addParagraph(document, writer, xmlWorker, exeSummary.getDesc_1_3_2(), fontNormal, 12, 0, 12);

        // *******************************************************************************************//
        // 2 Safety
        // *******************************************************************************************//

        addOutline(root, writer, MPSRUI.TREE_2);
        addSectionTitle(document, MPSRUI.TREE_2, fontChapterHeader, 0, 24, 12);
        addParagraph(document, writer, xmlWorker, safety.getDesc1(), fontNormal, 12, 0, 12);

        paragraph = new Paragraph("Table 2.1 Project Safety Summary", fontTableCaption);
        paragraph.setAlignment(Element.ALIGN_CENTER);
        paragraph.setSpacingAfter(6);
        document.add(paragraph);

        table = new PdfPTable(3);
        table.setTotalWidth(300);
        table.setLockedWidth(true);
        table.setWidths(new int[] { 1, 1, 1 });
        table.setHorizontalAlignment(Element.ALIGN_RIGHT);

        cell = new PdfPCell(new Phrase("Total Work Hours", fontTableColumnHeaderYellow));
        cell.setColspan(3);
        cell.setBackgroundColor(BaseColor.BLUE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell);

        headers = new String[] { "Current Period", "Calendar YTD", "Project To Date" };
        for (String header : headers) {
            cell = new PdfPCell(new Phrase(header, fontTableColumnHeader));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
        }

        cellValues = new String[][] { { INTEGER_FORMATTER.format(safety.getTotalWorkHoursCurrent()),
                INTEGER_FORMATTER.format(safety.getTotalWorkHoursYTD()),
                INTEGER_FORMATTER.format(safety.getTotalWorkHoursPTD()) } };
        for (int i = 0; i < cellValues.length; i++) {
            cell = new PdfPCell(new Phrase(cellValues[i][0]));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(cellValues[i][1]));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(cellValues[i][2], fontTableCellBold));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
        }

        document.add(table);

        // -----------------------------------

        table = new PdfPTable(4);
        table.setTotalWidth(500);
        table.setLockedWidth(true);
        table.setWidths(new int[] { 2, 1, 1, 1 });
        table.setHorizontalAlignment(Element.ALIGN_RIGHT);

        cell = new PdfPCell(new Phrase("Incidents", fontTableColumnHeaderYellow));
        cell.setColspan(4);
        cell.setBackgroundColor(BaseColor.BLUE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell);

        cellValues = new String[][] {
                { "OSHA Recordable", INTEGER_FORMATTER.format(safety.getOshaRecordableCurrent()),
                        INTEGER_FORMATTER.format(safety.getOshaRecordableYTD()),
                        INTEGER_FORMATTER.format(safety.getOshaRecordablePTD()) },
                { "First Aid", INTEGER_FORMATTER.format(safety.getFirstAid1Current()),
                        INTEGER_FORMATTER.format(safety.getFirstAid1YTD()),
                        INTEGER_FORMATTER.format(safety.getFirstAid1PTD()) },
                { "Near Miss", INTEGER_FORMATTER.format(safety.getNearMissCurrent()),
                        INTEGER_FORMATTER.format(safety.getNearMissYTD()),
                        INTEGER_FORMATTER.format(safety.getNearMissPTD()) },
                { "First Aid", INTEGER_FORMATTER.format(safety.getFirstAid2Current()),
                        INTEGER_FORMATTER.format(safety.getFirstAid2YTD()),
                        INTEGER_FORMATTER.format(safety.getFirstAid2PTD()) } };
        for (int i = 0; i < cellValues.length; i++) {
            cell = new PdfPCell(new Phrase(cellValues[i][0], fontTableRowTitle));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(cellValues[i][1]));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(cellValues[i][2]));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(cellValues[i][3], fontTableCellBold));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
        }

        cell = new PdfPCell(new Phrase("*Note - " + safety.getNote(), fontTableNote));
        cell.setColspan(4);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setVerticalAlignment(Element.ALIGN_TOP);
        table.addCell(cell);

        document.add(table);

        // *******************************************************************************************//
        // 3 Project Authorization
        // *******************************************************************************************//

        addOutline(root, writer, MPSRUI.TREE_3);
        addSectionTitle(document, MPSRUI.TREE_3, fontChapterHeader, 0, 24, 12);
        addParagraph(document, writer, xmlWorker, auth.getDesc1(), fontNormal, 12, 0, 12);

        table = new PdfPTable(10);
        table.setSpacingBefore(6);
        table.setTotalWidth(550);
        table.setLockedWidth(true);
        table.setWidths(new int[] { 3, 1, 1, 1, 1, 1, 1, 2, 1, 1 });
        table.setHorizontalAlignment(Element.ALIGN_CENTER);

        headers = new String[] { "$ Millions", "Prior", auth.getHeaderYear0(), auth.getHeaderYear1(),
                auth.getHeaderYear2(), auth.getHeaderYear3(), auth.getHeaderYear4(), auth.getHeaderPostYear(),
                "Total", "Auth" };
        for (String header : headers) {
            cell = new PdfPCell(new Phrase(header, fontTableColumnHeader));
            cell.setBackgroundColor(BaseColor.YELLOW);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
        }

        cellValues = new String[][] { { "Base", NUMBER_FORMATTER.format(auth.getBasePriorYear()),
                NUMBER_FORMATTER.format(auth.getBaseYear0()), NUMBER_FORMATTER.format(auth.getBaseYear1()),
                NUMBER_FORMATTER.format(auth.getBaseYear2()), NUMBER_FORMATTER.format(auth.getBaseYear3()),
                NUMBER_FORMATTER.format(auth.getBaseYear4()), NUMBER_FORMATTER.format(auth.getBasePostYear()),
                NUMBER_FORMATTER.format(auth.getBaseTotal()), "" },
                { "Risk & Contingency", NUMBER_FORMATTER.format(auth.getRnCPriorYear()),
                        NUMBER_FORMATTER.format(auth.getRnCYear0()),
                        NUMBER_FORMATTER.format(auth.getRnCYear1()),
                        NUMBER_FORMATTER.format(auth.getRnCYear2()),
                        NUMBER_FORMATTER.format(auth.getRnCYear3()),
                        NUMBER_FORMATTER.format(auth.getRnCYear4()),
                        NUMBER_FORMATTER.format(auth.getRnCPostYear()),
                        NUMBER_FORMATTER.format(auth.getRnCTotal()), "" },
                { "Total Project " + auth.getTotalProjectDate(), NUMBER_FORMATTER.format(auth.getPriorTotal()),
                        NUMBER_FORMATTER.format(auth.getYear0Total()),
                        NUMBER_FORMATTER.format(auth.getYear1Total()),
                        NUMBER_FORMATTER.format(auth.getYear2Total()),
                        NUMBER_FORMATTER.format(auth.getYear3Total()),
                        NUMBER_FORMATTER.format(auth.getYear4Total()),
                        NUMBER_FORMATTER.format(auth.getPostTotal()),
                        NUMBER_FORMATTER.format(auth.getTotalTotal()), "" },
                { "Current Request " + auth.getReq0RequestDate(),
                        NUMBER_FORMATTER.format(auth.getReq0PriorYear()),
                        NUMBER_FORMATTER.format(auth.getReq0Year0()),
                        NUMBER_FORMATTER.format(auth.getReq0Year1()),
                        NUMBER_FORMATTER.format(auth.getReq0Year2()),
                        NUMBER_FORMATTER.format(auth.getReq0Year3()),
                        NUMBER_FORMATTER.format(auth.getReq0Year4()),
                        NUMBER_FORMATTER.format(auth.getReq0PostYear()),
                        NUMBER_FORMATTER.format(auth.getReq0Total()),
                        NUMBER_FORMATTER.format(auth.getReq0Authorization()) },
                { "Request Date " + auth.getReq1RequestDate(), NUMBER_FORMATTER.format(auth.getReq1PriorYear()),
                        NUMBER_FORMATTER.format(auth.getReq1Year0()),
                        NUMBER_FORMATTER.format(auth.getReq1Year1()),
                        NUMBER_FORMATTER.format(auth.getReq1Year2()),
                        NUMBER_FORMATTER.format(auth.getReq1Year3()),
                        NUMBER_FORMATTER.format(auth.getReq1Year4()),
                        NUMBER_FORMATTER.format(auth.getReq1PostYear()),
                        NUMBER_FORMATTER.format(auth.getReq1Total()),
                        NUMBER_FORMATTER.format(auth.getReq1Authorization()) },
                { "Request Date " + auth.getReq2RequestDate(), NUMBER_FORMATTER.format(auth.getReq2PriorYear()),
                        NUMBER_FORMATTER.format(auth.getReq2Year0()),
                        NUMBER_FORMATTER.format(auth.getReq2Year1()),
                        NUMBER_FORMATTER.format(auth.getReq2Year2()),
                        NUMBER_FORMATTER.format(auth.getReq2Year3()),
                        NUMBER_FORMATTER.format(auth.getReq2Year4()),
                        NUMBER_FORMATTER.format(auth.getReq2PostYear()),
                        NUMBER_FORMATTER.format(auth.getReq2Total()),
                        NUMBER_FORMATTER.format(auth.getReq2Authorization()) },
                { "Target Budget", "", "", "", "", "", "", "", auth.getTargetBudget(), "" } };
        for (int i = 0; i < cellValues.length; i++) {

            cell = new PdfPCell(new Phrase(cellValues[i][0]));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            for (int j = 1; j < cellValues[i].length; j++) {
                cell = new PdfPCell(new Phrase(cellValues[i][j]));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                table.addCell(cell);
            }
        }

        document.add(table);

        // *******************************************************************************************//
        // 4 Project Budget
        // *******************************************************************************************//

        addOutline(root, writer, MPSRUI.TREE_4);
        addSectionTitle(document, MPSRUI.TREE_4, fontChapterHeader, 0, 24, 12);
        addParagraph(document, writer, xmlWorker, budget.getDesc1(), fontNormal, 12, 0, 12);

        table = new PdfPTable(2);
        table.setSpacingBefore(6);
        table.setTotalWidth(350);
        table.setLockedWidth(true);
        table.setWidths(new int[] { 5, 2 });
        table.setHorizontalAlignment(Element.ALIGN_CENTER);

        cellValues = new String[][] {
                { "Current Approved Budget (Base + RnC)",
                        CURRENCY_FORMATTER.format(budget.getPMBudget()) + "M" },
                { "Approved Phase Funding", CURRENCY_FORMATTER.format(budget.getPMActual()) + "M" },
                { "Expended To Date", CURRENCY_FORMATTER.format(budget.getPMCommitment()) + "M" },
                { "At Completion", CURRENCY_FORMATTER.format(budget.getPMAdditionalCost()) + "M" } };
        for (int i = 0; i < cellValues.length; i++) {
            cell = new PdfPCell(new Phrase(cellValues[i][0]));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(cellValues[i][1]));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
        }

        document.add(table);

        // ----------------------------------------------------
        // table 4.1
        // ----------------------------------------------------

        paragraph = new Paragraph("Table 4.1 Cost Report Summary", fontTableCaption);
        paragraph.setAlignment(Element.ALIGN_CENTER);
        paragraph.setSpacingAfter(6);
        document.add(paragraph);

        table = new PdfPTable(5);
        table.setTotalWidth(500);
        table.setLockedWidth(true);
        table.setWidths(new int[] { 1, 1, 1, 1, 1 });
        table.setHorizontalAlignment(Element.ALIGN_CENTER);

        headers = new String[] { "Work Element", "Description", "Estimate", "Actual", "EAC" };
        for (String header : headers) {
            cell = new PdfPCell(new Phrase(header, fontTableColumnHeaderYellow));
            cell.setBackgroundColor(BaseColor.BLUE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
        }

        for (int i = 0; i < costRpt.length; i++) {
            cell = new PdfPCell(new Phrase(costRpt[i].getWbs()));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(costRpt[i].getWbsDesc()));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(formatNumberString(costRpt[i].getEstimate())));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(formatNumberString(costRpt[i].getActual())));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(formatNumberString(costRpt[i].getEAC())));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
        }

        document.add(table);

        // *******************************************************************************************//
        // 5 Project Schedule
        // *******************************************************************************************//

        outline1 = addOutline(root, writer, MPSRUI.TREE_5);
        addSectionTitle(document, MPSRUI.TREE_5, fontChapterHeader, 0, 24, 12);

        addOutline(outline1, writer, MPSRUI.TREE_5_1);
        addSectionTitle(document, MPSRUI.TREE_5_1, fontSection1Header, 6, 12, 12);
        addParagraph(document, writer, xmlWorker, schedule.getDesc_5_1(), fontNormal, 12, 0, 12);

        addOutline(outline1, writer, MPSRUI.TREE_5_2);
        addSectionTitle(document, MPSRUI.TREE_5_2, fontSection1Header, 6, 12, 12);
        addParagraph(document, writer, xmlWorker, schedule.getDesc_5_2(), fontNormal, 12, 0, 12);

        addOutline(outline1, writer, MPSRUI.TREE_5_3);
        addSectionTitle(document, MPSRUI.TREE_5_3, fontSection1Header, 6, 12, 12);
        addParagraph(document, writer, xmlWorker, schedule.getDesc_5_3(), fontNormal, 12, 0, 12);

        addOutline(outline1, writer, MPSRUI.TREE_5_4);
        addSectionTitle(document, MPSRUI.TREE_5_4, fontSection1Header, 6, 12, 12);
        addParagraph(document, writer, xmlWorker, schedule.getDesc_5_4(), fontNormal, 12, 0, 12);

        // ----------------------------------------------------
        // table 5.1
        // ----------------------------------------------------

        paragraph = new Paragraph("Table 5.1 Planned Scorecard Milestones", fontTableCaption);
        paragraph.setAlignment(Element.ALIGN_CENTER);
        paragraph.setSpacingAfter(6);
        document.add(paragraph);

        table = new PdfPTable(3);
        table.setTotalWidth(500);
        table.setLockedWidth(true);
        table.setWidths(new int[] { 3, 1, 1 });
        table.setHorizontalAlignment(Element.ALIGN_CENTER);

        headers = new String[] { "Milestone", "Planned Date", "Finish Date" };
        for (String header : headers) {
            cell = new PdfPCell(new Phrase(header, fontTableColumnHeaderYellow));
            cell.setBackgroundColor(BaseColor.BLUE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
        }

        for (int i = 0; i < milestones.length; i++) {
            cell = new PdfPCell(new Phrase(milestones[i].getMilestone()));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(milestones[i].getPlannedDate()));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(milestones[i].getFinishDate()));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
        }

        document.add(table);

        // *******************************************************************************************//
        // 6 License & Permitting, and Environmental Status
        // *******************************************************************************************//

        outline1 = addOutline(root, writer, MPSRUI.TREE_6);
        addSectionTitle(document, MPSRUI.TREE_6, fontChapterHeader, 0, 24, 12);

        addOutline(outline1, writer, MPSRUI.TREE_6_1);
        addSectionTitle(document, MPSRUI.TREE_6_1, fontSection1Header, 6, 12, 12);
        addParagraph(document, writer, xmlWorker, lpe.getDesc_6_1(), fontNormal, 12, 0, 12);

        outline2 = addOutline(outline1, writer, MPSRUI.TREE_6_2);
        addSectionTitle(document, MPSRUI.TREE_6_2, fontSection1Header, 6, 12, 12);

        addOutline(outline2, writer, MPSRUI.TREE_6_2_1);
        addSectionTitle(document, MPSRUI.TREE_6_2_1, fontSection2Header, 12, 12, 12);
        addParagraph(document, writer, xmlWorker, lpe.getDesc_6_2_1(), fontNormal, 12, 0, 12);

        addOutline(outline2, writer, MPSRUI.TREE_6_2_2);
        addSectionTitle(document, MPSRUI.TREE_6_2_2, fontSection2Header, 12, 12, 12);
        addParagraph(document, writer, xmlWorker, lpe.getDesc_6_2_2(), fontNormal, 12, 0, 12);

        // *******************************************************************************************//
        // 7 Engineering Status
        // *******************************************************************************************//

        outline1 = addOutline(root, writer, MPSRUI.TREE_7);
        addSectionTitle(document, MPSRUI.TREE_7, fontChapterHeader, 0, 24, 12);

        addOutline(outline1, writer, MPSRUI.TREE_7_1);
        addSectionTitle(document, MPSRUI.TREE_7_1, fontSection1Header, 6, 12, 12);

        table = new PdfPTable(5);
        table.setTotalWidth(500);
        table.setLockedWidth(true);
        table.setWidths(new int[] { 2, 1, 1, 1, 3 });
        table.setHorizontalAlignment(Element.ALIGN_CENTER);

        headers = new String[] { "Package", "IFR", "IFC", "Indicator", "Note" };
        for (String header : headers) {
            cell = new PdfPCell(new Phrase(header, fontTableColumnHeaderYellow));
            cell.setBackgroundColor(BaseColor.BLUE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
        }

        for (int i = 0; i < ipds.length; i++) {
            cell = new PdfPCell(new Phrase(ipds[i].getPackage()));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(ipds[i].getIFR()));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(ipds[i].getIFC()));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(ipds[i].getIndicator()));
            cell.setBackgroundColor(getBackgroundColor(ipds[i].getIndicator()));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(ipds[i].getNote()));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);
        }

        document.add(table);

        // -----------------------------------------------------------------------------------//

        addOutline(outline1, writer, MPSRUI.TREE_7_2);
        addSectionTitle(document, MPSRUI.TREE_7_2, fontSection1Header, 6, 12, 12);

        table = new PdfPTable(5);
        table.setTotalWidth(500);
        table.setLockedWidth(true);
        table.setWidths(new int[] { 2, 1, 1, 1, 3 });
        table.setHorizontalAlignment(Element.ALIGN_CENTER);

        headers = new String[] { "Package", "IFR", "IFC", "Indicator", "Note" };
        for (String header : headers) {
            cell = new PdfPCell(new Phrase(header, fontTableColumnHeaderYellow));
            cell.setBackgroundColor(BaseColor.BLUE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
        }

        for (int i = 0; i < opds.length; i++) {
            cell = new PdfPCell(new Phrase(opds[i].getPackage()));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(opds[i].getIFR()));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(opds[i].getIFC()));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(opds[i].getIndicator()));
            cell.setBackgroundColor(getBackgroundColor(opds[i].getIndicator()));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(opds[i].getNote()));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);
        }

        document.add(table);

        // *******************************************************************************************//
        // 8 Procurement Status
        // *******************************************************************************************//

        outline1 = addOutline(root, writer, MPSRUI.TREE_8);
        addSectionTitle(document, MPSRUI.TREE_8, fontChapterHeader, 0, 24, 12);

        outline2 = addOutline(outline1, writer, MPSRUI.TREE_8_1);
        addSectionTitle(document, MPSRUI.TREE_8_1, fontSection1Header, 6, 12, 12);

        table = new PdfPTable(2);
        table.setTotalWidth(300);
        table.setLockedWidth(true);
        table.setWidths(new int[] { 1, 1 });
        table.setHorizontalAlignment(Element.ALIGN_CENTER);

        cellValues = new String[][] {
                { "Receipted to Date", CURRENCY_FORMATTER.format(procure.getReceiptedToDate()) },
                { "Open Commitments", CURRENCY_FORMATTER.format(procure.getOpenCommitment()) },
                { "Total", CURRENCY_FORMATTER.format(procure.getTotalPurchaseOrder()) } };
        for (int i = 0; i < cellValues.length; i++) {
            cell = new PdfPCell(new Phrase(cellValues[i][0]));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(cellValues[i][1]));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
        }

        document.add(table);

        addParagraph(document, writer, xmlWorker, procure.getDesc_8_1_B(), fontNormal, 12, 12, 12);

        outline2 = addOutline(outline1, writer, MPSRUI.TREE_8_2);
        addSectionTitle(document, MPSRUI.TREE_8_2, fontSection1Header, 6, 12, 12);

        // ----------------------------------------------------
        // section 8.2.1
        // ----------------------------------------------------

        addOutline(outline2, writer, MPSRUI.TREE_8_2_1);
        addSectionTitle(document, MPSRUI.TREE_8_2_1, fontSection2Header, 12, 12, 12);
        addParagraph(document, writer, xmlWorker, procure.getDesc_8_2_1(), fontNormal, 12, 0, 12);

        table = new PdfPTable(6);
        table.setTotalWidth(550);
        table.setLockedWidth(true);
        table.setWidths(new int[] { 1, 2, 1, 1, 2, 1 });
        table.setHorizontalAlignment(Element.ALIGN_CENTER);

        headers = new String[] { "Purchase Order", "Vendor", "Previous Amount", "This Month Amount",
                "This Month Description", "Total Amount" };
        for (String header : headers) {
            cell = new PdfPCell(new Phrase(header, fontPOTableHeader));
            cell.setBackgroundColor(BaseColor.BLUE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
        }

        double totalToDate = 0;

        for (int i = 0; i < approvedChanges.length; i++) {
            cell = new PdfPCell(new Phrase(approvedChanges[i].getPurchaseOrder(), fontPOTable));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(approvedChanges[i].getVendor(), fontPOTable));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            cell = new PdfPCell(
                    new Phrase(CURRENCY_FORMATTER.format(approvedChanges[i].getPreviousAmount()), fontPOTable));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(CURRENCY_FORMATTER.format(approvedChanges[i].getThisMonthAmount()),
                    fontPOTable));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(approvedChanges[i].getThisMonthDescription(), fontPOTable));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            cell = new PdfPCell(
                    new Phrase(CURRENCY_FORMATTER.format(approvedChanges[i].getTotalAmount()), fontPOTable));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            totalToDate += approvedChanges[i].getTotalAmount();
        }

        document.add(table);

        table = new PdfPTable(2);
        table.setTotalWidth(550);
        table.setLockedWidth(true);
        table.setWidths(new int[] { 7, 1 });
        table.setHorizontalAlignment(Element.ALIGN_CENTER);

        cell = new PdfPCell(new Phrase("Total To Date", fontPOTableSummary));
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setVerticalAlignment(Element.ALIGN_TOP);
        table.addCell(cell);

        cell = new PdfPCell(new Phrase(CURRENCY_FORMATTER.format(totalToDate), fontPOTableSummary));
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_TOP);
        table.addCell(cell);

        document.add(table);

        // ----------------------------------------------------
        // section 8.2.2
        // ----------------------------------------------------

        addOutline(outline2, writer, MPSRUI.TREE_8_2_2);
        addSectionTitle(document, MPSRUI.TREE_8_2_2, fontSection2Header, 12, 12, 12);
        addParagraph(document, writer, xmlWorker, procure.getDesc_8_2_2(), fontNormal, 12, 0, 12);

        table = new PdfPTable(6);
        table.setTotalWidth(550);
        table.setLockedWidth(true);
        table.setWidths(new int[] { 1, 2, 1, 1, 2, 1 });
        table.setHorizontalAlignment(Element.ALIGN_CENTER);

        headers = new String[] { "Purchase Order", "Vendor", "Previous Amount", "This Month Amount",
                "This Month Description", "Total Amount" };
        for (String header : headers) {
            cell = new PdfPCell(new Phrase(header, fontPOTableHeader));
            cell.setBackgroundColor(BaseColor.BLUE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
        }

        totalToDate = 0;

        for (int i = 0; i < pendingChanges.length; i++) {
            cell = new PdfPCell(new Phrase(pendingChanges[i].getPurchaseOrder(), fontPOTable));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(pendingChanges[i].getVendor(), fontPOTable));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            cell = new PdfPCell(
                    new Phrase(CURRENCY_FORMATTER.format(pendingChanges[i].getPreviousAmount()), fontPOTable));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            cell = new PdfPCell(
                    new Phrase(CURRENCY_FORMATTER.format(pendingChanges[i].getThisMonthAmount()), fontPOTable));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(pendingChanges[i].getThisMonthDescription(), fontPOTable));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            cell = new PdfPCell(
                    new Phrase(CURRENCY_FORMATTER.format(pendingChanges[i].getTotalAmount()), fontPOTable));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            totalToDate += pendingChanges[i].getTotalAmount();
        }

        document.add(table);

        table = new PdfPTable(2);
        table.setTotalWidth(550);
        table.setLockedWidth(true);
        table.setWidths(new int[] { 7, 1 });
        table.setHorizontalAlignment(Element.ALIGN_CENTER);

        cell = new PdfPCell(new Phrase("Total To Date", fontPOTableSummary));
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setVerticalAlignment(Element.ALIGN_TOP);
        table.addCell(cell);

        cell = new PdfPCell(new Phrase(CURRENCY_FORMATTER.format(totalToDate), fontPOTableSummary));
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_TOP);
        table.addCell(cell);

        document.add(table);

        // *******************************************************************************************//
        // 9 Construction Status
        // *******************************************************************************************//

        outline1 = addOutline(root, writer, MPSRUI.TREE_9);
        addSectionTitle(document, MPSRUI.TREE_9, fontChapterHeader, 0, 24, 12);

        addOutline(outline1, writer, MPSRUI.TREE_9_1);
        addSectionTitle(document, MPSRUI.TREE_9_1, fontSection1Header, 6, 12, 12);

        for (int i = 0; i < ipcs.length; i++) {
            addParagraph(document, writer, xmlWorker, ipcs[i].getWork(), fontWork, 12, 12, 0);
            addParagraph(document, writer, xmlWorker, ipcs[i].getDescription(), fontNormal, 12, 0, 0);
            addImage(document, MPSRUI.getFilePath(mpsrID, ipcs[i].getFileName()),
                    "Figure " + ipcs[i].getFigure() + " " + ipcs[i].getTitle(), fontImageCaption, 12, 3, 12);
        }

        // -----------------------------------------------------------------------------------------//

        addOutline(outline1, writer, MPSRUI.TREE_9_2);
        addSectionTitle(document, MPSRUI.TREE_9_2, fontSection1Header, 6, 12, 12);

        for (int i = 0; i < opcs.length; i++) {
            addParagraph(document, writer, xmlWorker, opcs[i].getWork(), fontWork, 12, 12, 0);
            addParagraph(document, writer, xmlWorker, opcs[i].getDescription(), fontNormal, 12, 0, 0);
            addImage(document, MPSRUI.getFilePath(mpsrID, opcs[i].getFileName()),
                    "Figure " + opcs[i].getFigure() + " " + opcs[i].getTitle(), fontImageCaption, 12, 3, 12);
        }

        // *******************************************************************************************//
        // Appendix
        // *******************************************************************************************//

        if (appendixs.length > 0) {

            document.add(Chunk.NEXTPAGE);
            outline1 = addOutline(root, writer, MPSRUI.TREE_APPENDIX);

            for (int i = 0; i < appendixs.length; i++) {
                addOutline(outline1, writer,
                        "Appendix " + appendixs[i].getNumber() + "  " + appendixs[i].getTitle());
                addSectionTitle(document,
                        "Appendix " + appendixs[i].getNumber() + "  " + appendixs[i].getTitle(),
                        fontChapterHeader, 0, 12, 12);
                addParagraph(document, writer, xmlWorker, appendixs[i].getDescription(), fontNormal, 12, 0, 0);

                importPages(document, writer, mpsrID, appendixs[i].getFileName());
            }
        }

        // *******************************************************************************************//
        // Attachment
        // *******************************************************************************************//

        if (attachments.length > 0) {

            document.setPageSize(DEFAULT_PAGE_SIZE);
            document.add(Chunk.NEXTPAGE);
            outline1 = addOutline(root, writer, MPSRUI.TREE_ATTACHMENT);

            for (int i = 0; i < attachments.length; i++) {
                addOutline(outline1, writer,
                        "Attachment " + attachments[i].getNumber() + "  " + attachments[i].getTitle());
                addSectionTitle(document,
                        "Attachment " + attachments[i].getNumber() + "  " + attachments[i].getTitle(),
                        fontChapterHeader, 0, 12, 12);
                addParagraph(document, writer, xmlWorker, attachments[i].getDescription(), fontNormal, 12, 0,
                        0);

                importPages(document, writer, mpsrID, attachments[i].getFileName());
            }
        }

        document.close();

        // *******************************************************************************************//

        // retrieve outline
        PdfReader readerOrig = new PdfReader(baosOrig.toByteArray());
        // int origNumberOfPages = readerOrig.getNumberOfPages();
        ColumnText ct = new ColumnText(null);
        ct.addElement(new Paragraph("Table of Contents", fontCoverTitle));
        List<HashMap<String, Object>> bookmarkList = SimpleBookmark.getBookmark(readerOrig);
        fillColumnText(bookmarkList, ct, 18, 0, fontSection2Header);

        // generate TOC after cover page
        ByteArrayOutputStream baosTOC = new ByteArrayOutputStream();
        PdfStamper stamperTOC = new PdfStamper(readerOrig, baosTOC);
        int tocPageEnd = 1;
        while (true) {
            stamperTOC.insertPage(++tocPageEnd, readerOrig.getPageSize(1));

            PdfContentByte underContent = stamperTOC.getUnderContent(tocPageEnd);

            generatePageHeader(document, underContent, icon, headerTexts);

            ct.setCanvas(stamperTOC.getOverContent(tocPageEnd));
            ct.setSimpleColumn(36, 36, 558, 693);
            if (!ColumnText.hasMoreText(ct.go()))
                break;
        }
        stamperTOC.close();

        // change page labels
        PdfPageLabels labels = new PdfPageLabels();
        labels.addPageLabel(1, PdfPageLabels.LOWERCASE_ROMAN_NUMERALS);
        labels.addPageLabel(tocPageEnd + 1, PdfPageLabels.DECIMAL_ARABIC_NUMERALS);

        // add labels
        ByteArrayOutputStream baosFinal = new ByteArrayOutputStream();
        PdfReader readerTOC = new PdfReader(baosTOC.toByteArray());
        // String selectPages = String.format("1-%s,%s-%s", tocPageEnd,
        // tocPageEnd + 1, origNumberOfPages + (tocPageEnd - 1));
        // readerTOC.selectPages(selectPages);
        PdfStamper stamperFinal = new PdfStamper(readerTOC, baosFinal);
        stamperFinal.getWriter().setPageLabels(labels);
        stamperFinal.close();

        // *******************************************************************************************//

        // send final PDF to browser
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Pragma", "public");
        response.setContentType("application/pdf");
        response.setContentLength(baosFinal.size());

        OutputStream os = response.getOutputStream();
        os.write(baosFinal.toByteArray());
        os.flush();
        os.close();

    } catch (DocumentException e) {
        e.printStackTrace();
    }

}

From source file:com.pma.mpsr.export.PDFGenerator.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)//from   ww  w.j a va2s. c  o m
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String mpsrID = request.getParameter("MPSR_ID");
    if (null == mpsrID)
        return;

    MPSRProjectInfo basicInfo = MPSRProjectInfo.getInstance(mpsrID);
    MPSRExecutiveSummary exeSummary = MPSRExecutiveSummary.getInstance(mpsrID);
    MPSRStatusSummary statusSummary = MPSRStatusSummary.getInstance(mpsrID);
    MPSRFunctionPerformance funcPerform = MPSRFunctionPerformance.getInstance(mpsrID);
    MPSRCostPerformance costPerform = MPSRCostPerformance.getInstance(mpsrID);
    MPSRSchedulePerformance[] schedulePerform = MPSRSchedulePerformance.getInstance(mpsrID);
    MPSRSafety safety = MPSRSafety.getInstance(mpsrID);
    MPSRAuthorization auth = MPSRAuthorization.getInstance(mpsrID);
    MPSRBudget budget = MPSRBudget.getInstance(mpsrID);
    MPSRCostReport[] costRpt = MPSRCostReport.getInstance(mpsrID);
    MPSRSchedule schedule = MPSRSchedule.getInstance(mpsrID);
    MPSRMilestone[] milestones = MPSRMilestone.getInstance(mpsrID);
    MPSRLPE lpe = MPSRLPE.getInstance(mpsrID);
    MPSRInsidePlantDesign[] ipds = MPSRInsidePlantDesign.getInstance(mpsrID);
    MPSROutsidePlantDesign[] opds = MPSROutsidePlantDesign.getInstance(mpsrID);
    MPSRProcure procure = MPSRProcure.getInstance(mpsrID);
    MPSRApprovedChanges[] approvedChanges = MPSRApprovedChanges.getInstance(mpsrID);
    MPSRPendingChanges[] pendingChanges = MPSRPendingChanges.getInstance(mpsrID);
    MPSRInsidePlantConstruction[] ipcs = MPSRInsidePlantConstruction.getInstance(mpsrID);
    MPSROutsidePlantConstruction[] opcs = MPSROutsidePlantConstruction.getInstance(mpsrID);
    MPSRAppendix[] appendixs = MPSRAppendix.getInstance(mpsrID);
    MPSRAttachment[] attachments = MPSRAttachment.getInstance(mpsrID);

    // response.setContentType("application/pdf");
    // response.setHeader("Content-Disposition",
    // "attachment; filename=\"test.pdf\"");

    Font fontNormal = null;
    Font fontCoverTitle = new Font(FontFamily.HELVETICA, 20, Font.BOLD);
    Font fontCoverTableHeader = new Font(FontFamily.HELVETICA, 16, Font.BOLD);
    Font fontCoverTableContent = new Font(FontFamily.HELVETICA, 16);
    Font fontChapterHeader = new Font(FontFamily.HELVETICA, 18, Font.BOLD);
    Font fontSection1Header = new Font(FontFamily.HELVETICA, 16, Font.BOLD);
    Font fontSection2Header = new Font(FontFamily.HELVETICA, 14, Font.BOLD);
    Font fontWork = new Font(FontFamily.HELVETICA, 12, Font.UNDERLINE);

    Font fontTableCaption = new Font(FontFamily.TIMES_ROMAN, 12, Font.BOLD);
    Font fontTableColumnHeader = new Font(FontFamily.HELVETICA, 12, Font.BOLD);
    Font fontTableColumnHeaderYellow = new Font(FontFamily.HELVETICA, 12, Font.BOLD);
    fontTableColumnHeaderYellow.setColor(BaseColor.YELLOW);
    Font fontTableRowTitle = new Font(FontFamily.HELVETICA, 12, Font.ITALIC);
    Font fontTableCellBold = new Font(FontFamily.HELVETICA, 12, Font.BOLD);
    Font fontTableNote = new Font(FontFamily.HELVETICA, 10, Font.ITALIC);
    Font fontImageCaption = new Font(FontFamily.TIMES_ROMAN, 9, Font.BOLD);

    Font fontPOTableHeader = new Font(FontFamily.HELVETICA, 10, Font.BOLD);
    fontPOTableHeader.setColor(BaseColor.YELLOW);
    Font fontPOTable = new Font(FontFamily.HELVETICA, 9);
    Font fontPOTableSummary = new Font(FontFamily.HELVETICA, 9, Font.BOLD);

    Font fontPageHeader = new Font(FontFamily.HELVETICA, 8);
    Font fontPageFooter = new Font(FontFamily.HELVETICA, 10);

    Phrase[] headerTexts = new Phrase[] { new Phrase("PMA - ELECTRIC DELIVERY", fontPageHeader),
            new Phrase("DELIVERY PROJECTS & CONSTRUCTION (DP&C)", fontPageHeader),
            new Phrase("PROJECT MONTHLY REPORT", fontPageHeader) };

    Paragraph paragraph = null;
    PdfPTable table = null;
    PdfPCell cell = null;

    Document document = new Document(DEFAULT_PAGE_SIZE, 36, 36, 9 * 10, 36);
    ByteArrayOutputStream baosOrig = new ByteArrayOutputStream();
    XMLWorkerHelper xmlWorker = XMLWorkerHelper.getInstance();

    try {
        PdfWriter writer = PdfWriter.getInstance(document, baosOrig);
        writer.setStrictImageSequence(true);
        writer.setLinearPageMode();
        writer.setViewerPreferences(PdfWriter.PageModeUseOutlines | PdfWriter.FitWindow);

        Image icon = getEmbeddedImage(getServletContext(), "/resource/image/pma.bmp");

        document.open();

        PdfOutline root = writer.getRootOutline();

        // *******************************************************************************************//

        // addOutline(root, writer, MPSRUI.TREE_0);

        for (int i = 0; i < 2; i++) {
            document.add(new Paragraph(" "));
        }

        String[] titles = { "PMA DELIVERY PROJECTS & CONSTRUCTION", "MONTHLY REPORT",
                basicInfo.getReportMonthYear(), basicInfo.getProjectTitle(),
                "PROJECT No. " + basicInfo.getProjectDefinition() };
        int[] spaceingAfters = { 48, 48, 48, 24, 48 };
        for (int i = 0; i < titles.length; i++) {
            paragraph = new Paragraph();
            paragraph.setSpacingAfter(spaceingAfters[i]);
            paragraph.setFont(fontCoverTitle);
            paragraph.setAlignment(Element.ALIGN_CENTER);
            paragraph.add(new Chunk(titles[i]));
            document.add(paragraph);
        }

        addCoverImage(document, MPSRUI.getFilePath(mpsrID, basicInfo.getFileName()));

        document.add(new Paragraph(" "));

        table = new PdfPTable(2);
        table.addCell(new Phrase("Client", fontCoverTableHeader));
        table.addCell(new Phrase(basicInfo.getProjectManager(), fontCoverTableContent));
        table.addCell(new Phrase("Location", fontCoverTableHeader));
        table.addCell(new Phrase(basicInfo.getProjectDirector(), fontCoverTableContent));
        document.add(table);

        // *******************************************************************************************//

        document.resetPageCount();
        document.add(Chunk.NEXTPAGE);
        writer.setPageEvent(new MPSRPageEventHelper(icon, headerTexts, fontPageFooter));

        // *******************************************************************************************//

        PdfOutline outline1 = addOutline(root, writer, MPSRUI.TREE_1);
        addSectionTitle(document, MPSRUI.TREE_1, fontChapterHeader, 0, 0, 12);

        PdfOutline outline2 = addOutline(outline1, writer, "1.1");

        addOutline(outline2, writer, MPSRUI.TREE_1_1_1);
        addSectionTitle(document, MPSRUI.TREE_1_1_1, fontSection2Header, 12, 12, 0);
        addParagraph(document, writer, xmlWorker, exeSummary.getDesc_1_1_1(), fontNormal, 12, 0, 12);

        addOutline(outline2, writer, MPSRUI.TREE_1_1_2);
        addSectionTitle(document, MPSRUI.TREE_1_1_2, fontSection2Header, 12, 12, 0);
        addParagraph(document, writer, xmlWorker, exeSummary.getDesc_1_1_2(), fontNormal, 12, 0, 12);

        addOutline(outline2, writer, MPSRUI.TREE_1_1_3);
        addSectionTitle(document, MPSRUI.TREE_1_1_3, fontSection2Header, 12, 12, 0);
        addParagraph(document, writer, xmlWorker, exeSummary.getDesc_1_1_3(), fontNormal, 12, 0, 12);

        addOutline(outline2, writer, MPSRUI.TREE_1_1_4);
        addSectionTitle(document, MPSRUI.TREE_1_1_4, fontSection2Header, 12, 12, 0);
        addParagraph(document, writer, xmlWorker, exeSummary.getDesc_1_1_4(), fontNormal, 12, 0, 12);

        // *******************************************************************************************//
        // 1.2 Status Summary
        // *******************************************************************************************//

        outline2 = addOutline(outline1, writer, MPSRUI.TREE_1_2);
        addSectionTitle(document, MPSRUI.TREE_1_2, fontSection1Header, 6, 12, 12);

        paragraph = new Paragraph();
        paragraph.add(basicInfo.getProjectTitle());
        paragraph.setSpacingAfter(4);
        document.add(paragraph);

        table = new PdfPTable(5);
        table.setTotalWidth(500);
        table.setLockedWidth(true);
        table.setWidths(new int[] { 3, 1, 1, 1, 1 });

        cell = new PdfPCell(
                new Phrase("Project #: " + basicInfo.getProjectDefinition(), fontTableColumnHeader));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell);
        String[] headers = { "Status", "Approved (Include RnC)", "To Date", "At Completion" };
        for (String header : headers) {
            cell = new PdfPCell(new Phrase(header, fontTableColumnHeader));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
        }

        String[][] cellValues = {
                { "Budget ($M)", statusSummary.getBudgetStatus(),
                        !"".equals(statusSummary.getBudgetApproved()) ? CURRENCY_FORMATTER
                                .format(Double.parseDouble(statusSummary.getBudgetApproved())) : "",
                        !"".equals(statusSummary.getBudgetToDate())
                                ? CURRENCY_FORMATTER.format(Double.parseDouble(statusSummary.getBudgetToDate()))
                                : "",
                        !"".equals(statusSummary.getBudgetAtCompletion()) ? CURRENCY_FORMATTER
                                .format(Double.parseDouble(statusSummary.getBudgetAtCompletion())) : "" },
                { "Schedule - Duration (months)", statusSummary.getScheduleStatus(),
                        statusSummary.getScheduleApproved(), statusSummary.getScheduleToDate(),
                        statusSummary.getScheduleAtCompletion() },
                { "In-Service Date", statusSummary.getInServiceDateStatus(),
                        statusSummary.getInServiceDateApproved(), statusSummary.getInServiceDateToDate(),
                        statusSummary.getInServiceDateAtCompletion() } };
        for (int i = 0; i < cellValues.length; i++) {
            table.addCell(new Phrase(cellValues[i][0]));
            cell = new PdfPCell(new Phrase(cellValues[i][1]));
            cell.setBackgroundColor(getBackgroundColor(cellValues[i][1]));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);
            for (int j = 2; j < 5; j++) {
                cell = new PdfPCell(new Phrase(cellValues[i][j]));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(cell);
            }
        }

        document.add(table);

        // -------------------------------------------------------------------//

        paragraph = new Paragraph("Legend:");
        paragraph.setSpacingAfter(4);
        paragraph.setIndentationLeft(25);
        document.add(paragraph);

        table = new PdfPTable(3);
        table.setTotalWidth(240);
        table.setLockedWidth(true);
        table.setHorizontalAlignment(Element.ALIGN_LEFT);
        String[] legends = { "On Target", "At Risk", "Off Target" };
        for (String legend : legends) {
            cell = new PdfPCell(new Phrase(legend));
            cell.setBackgroundColor(getBackgroundColor(legend));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setMinimumHeight(18);
            cell.setPadding(0);
            table.addCell(cell);
        }

        paragraph = new Paragraph();
        paragraph.add(table);
        paragraph.setIndentationLeft(25);
        document.add(paragraph);

        // *******************************************************************************************//
        // 1.2.1 Functional Area Performance Indicators
        // *******************************************************************************************//

        addOutline(outline2, writer, MPSRUI.TREE_1_2_1);
        addSectionTitle(document, MPSRUI.TREE_1_2_1, fontSection2Header, 12, 12, 12);

        table = new PdfPTable(4);
        table.setTotalWidth(550);
        table.setLockedWidth(true);
        table.setWidths(new int[] { 4, 1, 1, 4 });

        headers = new String[] { "Activities", "Current Status", "Trend",
                "Comments (main performance drives)" };
        for (String header : headers) {
            cell = new PdfPCell(new Phrase(header, fontTableColumnHeader));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
        }

        Image imgArrowUp = getEmbeddedImage(getServletContext(), "/VAADIN/themes/MPSR/img/Arrow_Up.png");
        Image imgArrowDown = getEmbeddedImage(getServletContext(), "/VAADIN/themes/MPSR/img/Arrow_Down.png");
        Image imgArrowEven = getEmbeddedImage(getServletContext(), "/VAADIN/themes/MPSR/img/Arrow_Even.png");
        Image[] images = { imgArrowUp, imgArrowDown, imgArrowEven };
        for (Image image : images) {
            image.scaleToFit(12, 12);
        }

        cellValues = new String[][] {
                { "Project - " + basicInfo.getProjectTitle(), funcPerform.getProjectStatus(),
                        funcPerform.getProjectTrend(), funcPerform.getProjectComment() },
                { "  Target Budget", funcPerform.getTargetBudgetStatus(), funcPerform.getTargetBudgetTrend(),
                        funcPerform.getTargetBudgetComment() },
                { "  Safety", funcPerform.getSafetyStatus(), funcPerform.getSafetyTrend(),
                        funcPerform.getSafetyComment() },
                { "  Licensing & Permitting", funcPerform.getLicensingStatus(), funcPerform.getLicensingTrend(),
                        funcPerform.getLicensingComment() },
                { "  Corporate Properties", funcPerform.getCorporateStatus(), funcPerform.getCorporateTrend(),
                        funcPerform.getCorporateComment() },
                { "  Inside Plant Design & Engineering", funcPerform.getIPDEStatus(),
                        funcPerform.getIPDETrend(), funcPerform.getIPDEComment() },
                { "  Public Outreach", funcPerform.getOutreachStatus(), funcPerform.getOutreachTrend(),
                        funcPerform.getOutreachComment() },
                { "  Procurement", funcPerform.getProcureStatus(), funcPerform.getProcureTrend(),
                        funcPerform.getProcureComment() },
                { "  Construction", funcPerform.getConstructionStatus(), funcPerform.getConstructionTrend(),
                        funcPerform.getConstructionComment() },
                { "  Environmental - Resource Recovery", funcPerform.getEnviromentStatus(),
                        funcPerform.getEnviromentTrend(), funcPerform.getEnviromentComment() },
                { "  Salvage", funcPerform.getSalvageStatus(), funcPerform.getSalvageTrend(),
                        funcPerform.getSalvageComment() },
                { "  Withdrawal", funcPerform.getWithdrawalStatus(), funcPerform.getWithdrawalTrend(),
                        funcPerform.getWithdrawalComment() } };
        for (int i = 0; i < cellValues.length; i++) {
            cell = new PdfPCell(new Phrase(cellValues[i][0]));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(cellValues[i][1]));
            cell.setBackgroundColor(getBackgroundColor(cellValues[i][1]));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            if ("Up".equals(cellValues[i][2])) {
                cell = new PdfPCell(imgArrowUp);
            } else if ("Down".equals(cellValues[i][2])) {
                cell = new PdfPCell(imgArrowDown);
            } else if ("Even".equals(cellValues[i][2])) {
                cell = new PdfPCell(imgArrowEven);
            } else {
                cell = new PdfPCell();
            }

            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(cellValues[i][3]));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            table.addCell(cell);
        }

        document.add(table);

        // *******************************************************************************************//

        document.setPageSize(DEFAULT_PAGE_SIZE.rotate());
        document.add(Chunk.NEXTPAGE);

        addOutline(outline2, writer, MPSRUI.TREE_1_2_2);
        addSectionTitle(document, MPSRUI.TREE_1_2_2, fontSection2Header, 12, 12, 12);
        addImage(document, MPSRUI.getFilePath(mpsrID, costPerform.getFileName()));

        // *******************************************************************************************//
        // 1.2.3 Schedule Performance
        // *******************************************************************************************//

        document.add(Chunk.NEXTPAGE);

        addOutline(outline2, writer, MPSRUI.TREE_1_2_3);
        addSectionTitle(document, MPSRUI.TREE_1_2_3, fontSection2Header, 12, 12, 12);

        table = new PdfPTable(9);
        table.setTotalWidth(750);
        table.setLockedWidth(true);
        table.setWidths(new int[] { 3, 1, 1, 1, 1, 1, 1, 1, 1 });
        table.setHorizontalAlignment(Element.ALIGN_CENTER);

        headers = new String[] { "WBS", "Original Duration", "Remaining Duration", "Baseline Start Date",
                "Baseline Finish Date", "Start Date", "Finish Date", "Total Float", "Status" };
        for (String header : headers) {
            cell = new PdfPCell(new Phrase(header, fontTableColumnHeaderYellow));
            cell.setBackgroundColor(BaseColor.BLUE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
        }

        for (int i = 0; i < schedulePerform.length; i++) {
            cell = new PdfPCell(new Phrase(schedulePerform[i].getWBS()));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(Double.toString(schedulePerform[i].getOriginalDuration())));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(Double.toString(schedulePerform[i].getRemainingDuration())));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(schedulePerform[i].getPlannedStartDate()));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(schedulePerform[i].getPlannedFinishDate()));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(schedulePerform[i].getStartDate()));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(schedulePerform[i].getFinishDate()));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(schedulePerform[i].getTotalFloat()));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(schedulePerform[i].getStatus()));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
        }

        table.setHeaderRows(1);

        document.add(table);

        // *******************************************************************************************//
        // 1.3 Project Change Control
        // *******************************************************************************************//

        document.setPageSize(DEFAULT_PAGE_SIZE);
        document.add(Chunk.NEXTPAGE);

        outline2 = addOutline(outline1, writer, MPSRUI.TREE_1_3);
        addSectionTitle(document, MPSRUI.TREE_1_3, fontSection1Header, 6, 12, 12);

        addOutline(outline2, writer, MPSRUI.TREE_1_3_1);
        addSectionTitle(document, MPSRUI.TREE_1_3_1, fontSection2Header, 12, 12, 0);
        addParagraph(document, writer, xmlWorker, exeSummary.getDesc_1_3_1(), fontNormal, 12, 0, 12);

        addOutline(outline2, writer, MPSRUI.TREE_1_3_2);
        addSectionTitle(document, MPSRUI.TREE_1_3_2, fontSection2Header, 12, 12, 0);
        addParagraph(document, writer, xmlWorker, exeSummary.getDesc_1_3_2(), fontNormal, 12, 0, 12);

        // *******************************************************************************************//
        // 2 Safety
        // *******************************************************************************************//

        addOutline(root, writer, MPSRUI.TREE_2);
        addSectionTitle(document, MPSRUI.TREE_2, fontChapterHeader, 0, 24, 12);
        addParagraph(document, writer, xmlWorker, safety.getDesc1(), fontNormal, 12, 0, 12);

        paragraph = new Paragraph("Table 2.1 Project Safety Summary", fontTableCaption);
        paragraph.setAlignment(Element.ALIGN_CENTER);
        paragraph.setSpacingAfter(6);
        document.add(paragraph);

        table = new PdfPTable(3);
        table.setTotalWidth(300);
        table.setLockedWidth(true);
        table.setWidths(new int[] { 1, 1, 1 });
        table.setHorizontalAlignment(Element.ALIGN_RIGHT);

        cell = new PdfPCell(new Phrase("Total Work Hours", fontTableColumnHeaderYellow));
        cell.setColspan(3);
        cell.setBackgroundColor(BaseColor.BLUE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell);

        headers = new String[] { "Current Period", "Calendar YTD", "Project To Date" };
        for (String header : headers) {
            cell = new PdfPCell(new Phrase(header, fontTableColumnHeader));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
        }

        cellValues = new String[][] { { INTEGER_FORMATTER.format(safety.getTotalWorkHoursCurrent()),
                INTEGER_FORMATTER.format(safety.getTotalWorkHoursYTD()),
                INTEGER_FORMATTER.format(safety.getTotalWorkHoursPTD()) } };
        for (int i = 0; i < cellValues.length; i++) {
            cell = new PdfPCell(new Phrase(cellValues[i][0]));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(cellValues[i][1]));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(cellValues[i][2], fontTableCellBold));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
        }

        document.add(table);

        // -----------------------------------

        table = new PdfPTable(4);
        table.setTotalWidth(500);
        table.setLockedWidth(true);
        table.setWidths(new int[] { 2, 1, 1, 1 });
        table.setHorizontalAlignment(Element.ALIGN_RIGHT);

        cell = new PdfPCell(new Phrase("Incidents", fontTableColumnHeaderYellow));
        cell.setColspan(4);
        cell.setBackgroundColor(BaseColor.BLUE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell);

        cellValues = new String[][] {
                { "OSHA Recordable", INTEGER_FORMATTER.format(safety.getOshaRecordableCurrent()),
                        INTEGER_FORMATTER.format(safety.getOshaRecordableYTD()),
                        INTEGER_FORMATTER.format(safety.getOshaRecordablePTD()) },
                { "First Aid", INTEGER_FORMATTER.format(safety.getFirstAid1Current()),
                        INTEGER_FORMATTER.format(safety.getFirstAid1YTD()),
                        INTEGER_FORMATTER.format(safety.getFirstAid1PTD()) },
                { "Near Miss", INTEGER_FORMATTER.format(safety.getNearMissCurrent()),
                        INTEGER_FORMATTER.format(safety.getNearMissYTD()),
                        INTEGER_FORMATTER.format(safety.getNearMissPTD()) },
                { "First Aid", INTEGER_FORMATTER.format(safety.getFirstAid2Current()),
                        INTEGER_FORMATTER.format(safety.getFirstAid2YTD()),
                        INTEGER_FORMATTER.format(safety.getFirstAid2PTD()) } };
        for (int i = 0; i < cellValues.length; i++) {
            cell = new PdfPCell(new Phrase(cellValues[i][0], fontTableRowTitle));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(cellValues[i][1]));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(cellValues[i][2]));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(cellValues[i][3], fontTableCellBold));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
        }

        cell = new PdfPCell(new Phrase("*Note - " + safety.getNote(), fontTableNote));
        cell.setColspan(4);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setVerticalAlignment(Element.ALIGN_TOP);
        table.addCell(cell);

        document.add(table);

        // *******************************************************************************************//
        // 3 Project Authorization
        // *******************************************************************************************//

        addOutline(root, writer, MPSRUI.TREE_3);
        addSectionTitle(document, MPSRUI.TREE_3, fontChapterHeader, 0, 24, 12);
        addParagraph(document, writer, xmlWorker, auth.getDesc1(), fontNormal, 12, 0, 12);

        table = new PdfPTable(10);
        table.setSpacingBefore(6);
        table.setTotalWidth(550);
        table.setLockedWidth(true);
        table.setWidths(new int[] { 3, 1, 1, 1, 1, 1, 1, 2, 1, 1 });
        table.setHorizontalAlignment(Element.ALIGN_CENTER);

        headers = new String[] { "$ Millions", "Prior", auth.getHeaderYear0(), auth.getHeaderYear1(),
                auth.getHeaderYear2(), auth.getHeaderYear3(), auth.getHeaderYear4(), auth.getHeaderPostYear(),
                "Total", "Auth" };
        for (String header : headers) {
            cell = new PdfPCell(new Phrase(header, fontTableColumnHeader));
            cell.setBackgroundColor(BaseColor.YELLOW);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
        }

        cellValues = new String[][] { { "Base", NUMBER_FORMATTER.format(auth.getBasePriorYear()),
                NUMBER_FORMATTER.format(auth.getBaseYear0()), NUMBER_FORMATTER.format(auth.getBaseYear1()),
                NUMBER_FORMATTER.format(auth.getBaseYear2()), NUMBER_FORMATTER.format(auth.getBaseYear3()),
                NUMBER_FORMATTER.format(auth.getBaseYear4()), NUMBER_FORMATTER.format(auth.getBasePostYear()),
                NUMBER_FORMATTER.format(auth.getBaseTotal()), "" },
                { "Risk & Contingency", NUMBER_FORMATTER.format(auth.getRnCPriorYear()),
                        NUMBER_FORMATTER.format(auth.getRnCYear0()),
                        NUMBER_FORMATTER.format(auth.getRnCYear1()),
                        NUMBER_FORMATTER.format(auth.getRnCYear2()),
                        NUMBER_FORMATTER.format(auth.getRnCYear3()),
                        NUMBER_FORMATTER.format(auth.getRnCYear4()),
                        NUMBER_FORMATTER.format(auth.getRnCPostYear()),
                        NUMBER_FORMATTER.format(auth.getRnCTotal()), "" },
                { "Total Project " + auth.getTotalProjectDate(), NUMBER_FORMATTER.format(auth.getPriorTotal()),
                        NUMBER_FORMATTER.format(auth.getYear0Total()),
                        NUMBER_FORMATTER.format(auth.getYear1Total()),
                        NUMBER_FORMATTER.format(auth.getYear2Total()),
                        NUMBER_FORMATTER.format(auth.getYear3Total()),
                        NUMBER_FORMATTER.format(auth.getYear4Total()),
                        NUMBER_FORMATTER.format(auth.getPostTotal()),
                        NUMBER_FORMATTER.format(auth.getTotalTotal()), "" },
                { "Current Request " + auth.getReq0RequestDate(),
                        NUMBER_FORMATTER.format(auth.getReq0PriorYear()),
                        NUMBER_FORMATTER.format(auth.getReq0Year0()),
                        NUMBER_FORMATTER.format(auth.getReq0Year1()),
                        NUMBER_FORMATTER.format(auth.getReq0Year2()),
                        NUMBER_FORMATTER.format(auth.getReq0Year3()),
                        NUMBER_FORMATTER.format(auth.getReq0Year4()),
                        NUMBER_FORMATTER.format(auth.getReq0PostYear()),
                        NUMBER_FORMATTER.format(auth.getReq0Total()),
                        NUMBER_FORMATTER.format(auth.getReq0Authorization()) },
                { "Request Date " + auth.getReq1RequestDate(), NUMBER_FORMATTER.format(auth.getReq1PriorYear()),
                        NUMBER_FORMATTER.format(auth.getReq1Year0()),
                        NUMBER_FORMATTER.format(auth.getReq1Year1()),
                        NUMBER_FORMATTER.format(auth.getReq1Year2()),
                        NUMBER_FORMATTER.format(auth.getReq1Year3()),
                        NUMBER_FORMATTER.format(auth.getReq1Year4()),
                        NUMBER_FORMATTER.format(auth.getReq1PostYear()),
                        NUMBER_FORMATTER.format(auth.getReq1Total()),
                        NUMBER_FORMATTER.format(auth.getReq1Authorization()) },
                { "Request Date " + auth.getReq2RequestDate(), NUMBER_FORMATTER.format(auth.getReq2PriorYear()),
                        NUMBER_FORMATTER.format(auth.getReq2Year0()),
                        NUMBER_FORMATTER.format(auth.getReq2Year1()),
                        NUMBER_FORMATTER.format(auth.getReq2Year2()),
                        NUMBER_FORMATTER.format(auth.getReq2Year3()),
                        NUMBER_FORMATTER.format(auth.getReq2Year4()),
                        NUMBER_FORMATTER.format(auth.getReq2PostYear()),
                        NUMBER_FORMATTER.format(auth.getReq2Total()),
                        NUMBER_FORMATTER.format(auth.getReq2Authorization()) },
                { "Target Budget", "", "", "", "", "", "", "", auth.getTargetBudget(), "" } };
        for (int i = 0; i < cellValues.length; i++) {

            cell = new PdfPCell(new Phrase(cellValues[i][0]));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            for (int j = 1; j < cellValues[i].length; j++) {
                cell = new PdfPCell(new Phrase(cellValues[i][j]));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                table.addCell(cell);
            }
        }

        document.add(table);

        // *******************************************************************************************//
        // 4 Project Budget
        // *******************************************************************************************//

        addOutline(root, writer, MPSRUI.TREE_4);
        addSectionTitle(document, MPSRUI.TREE_4, fontChapterHeader, 0, 24, 12);
        addParagraph(document, writer, xmlWorker, budget.getDesc1(), fontNormal, 12, 0, 12);

        table = new PdfPTable(2);
        table.setSpacingBefore(6);
        table.setTotalWidth(350);
        table.setLockedWidth(true);
        table.setWidths(new int[] { 5, 2 });
        table.setHorizontalAlignment(Element.ALIGN_CENTER);

        cellValues = new String[][] {
                { "Current Approved Budget (Base + RnC)",
                        CURRENCY_FORMATTER.format(budget.getPMBudget()) + "M" },
                { "Approved Phase Funding", CURRENCY_FORMATTER.format(budget.getPMActual()) + "M" },
                { "Expended To Date", CURRENCY_FORMATTER.format(budget.getPMCommitment()) + "M" },
                { "At Completion", CURRENCY_FORMATTER.format(budget.getPMAdditionalCost()) + "M" } };
        for (int i = 0; i < cellValues.length; i++) {
            cell = new PdfPCell(new Phrase(cellValues[i][0]));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(cellValues[i][1]));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
        }

        document.add(table);

        // ----------------------------------------------------
        // table 4.1
        // ----------------------------------------------------

        paragraph = new Paragraph("Table 4.1 Cost Report Summary", fontTableCaption);
        paragraph.setAlignment(Element.ALIGN_CENTER);
        paragraph.setSpacingAfter(6);
        document.add(paragraph);

        table = new PdfPTable(5);
        table.setTotalWidth(500);
        table.setLockedWidth(true);
        table.setWidths(new int[] { 1, 1, 1, 1, 1 });
        table.setHorizontalAlignment(Element.ALIGN_CENTER);

        headers = new String[] { "Work Element", "Description", "Estimate", "Actual", "EAC" };
        for (String header : headers) {
            cell = new PdfPCell(new Phrase(header, fontTableColumnHeaderYellow));
            cell.setBackgroundColor(BaseColor.BLUE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
        }

        for (int i = 0; i < costRpt.length; i++) {
            cell = new PdfPCell(new Phrase(costRpt[i].getWbs()));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(costRpt[i].getWbsDesc()));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(formatNumberString(costRpt[i].getEstimate())));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(formatNumberString(costRpt[i].getActual())));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(formatNumberString(costRpt[i].getEAC())));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
        }

        document.add(table);

        // *******************************************************************************************//
        // 5 Project Schedule
        // *******************************************************************************************//

        outline1 = addOutline(root, writer, MPSRUI.TREE_5);
        addSectionTitle(document, MPSRUI.TREE_5, fontChapterHeader, 0, 24, 12);

        addOutline(outline1, writer, MPSRUI.TREE_5_1);
        addSectionTitle(document, MPSRUI.TREE_5_1, fontSection1Header, 6, 12, 12);
        addParagraph(document, writer, xmlWorker, schedule.getDesc_5_1(), fontNormal, 12, 0, 12);

        addOutline(outline1, writer, MPSRUI.TREE_5_2);
        addSectionTitle(document, MPSRUI.TREE_5_2, fontSection1Header, 6, 12, 12);
        addParagraph(document, writer, xmlWorker, schedule.getDesc_5_2(), fontNormal, 12, 0, 12);

        addOutline(outline1, writer, MPSRUI.TREE_5_3);
        addSectionTitle(document, MPSRUI.TREE_5_3, fontSection1Header, 6, 12, 12);
        addParagraph(document, writer, xmlWorker, schedule.getDesc_5_3(), fontNormal, 12, 0, 12);

        addOutline(outline1, writer, MPSRUI.TREE_5_4);
        addSectionTitle(document, MPSRUI.TREE_5_4, fontSection1Header, 6, 12, 12);
        addParagraph(document, writer, xmlWorker, schedule.getDesc_5_4(), fontNormal, 12, 0, 12);

        // ----------------------------------------------------
        // table 5.1
        // ----------------------------------------------------

        paragraph = new Paragraph("Table 5.1 Planned Scorecard Milestones", fontTableCaption);
        paragraph.setAlignment(Element.ALIGN_CENTER);
        paragraph.setSpacingAfter(6);
        document.add(paragraph);

        table = new PdfPTable(3);
        table.setTotalWidth(500);
        table.setLockedWidth(true);
        table.setWidths(new int[] { 3, 1, 1 });
        table.setHorizontalAlignment(Element.ALIGN_CENTER);

        headers = new String[] { "Milestone", "Planned Date", "Finish Date" };
        for (String header : headers) {
            cell = new PdfPCell(new Phrase(header, fontTableColumnHeaderYellow));
            cell.setBackgroundColor(BaseColor.BLUE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
        }

        for (int i = 0; i < milestones.length; i++) {
            cell = new PdfPCell(new Phrase(milestones[i].getMilestone()));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(milestones[i].getPlannedDate()));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(milestones[i].getFinishDate()));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
        }

        document.add(table);

        // *******************************************************************************************//
        // 6 License & Permitting, and Environmental Status
        // *******************************************************************************************//

        outline1 = addOutline(root, writer, MPSRUI.TREE_6);
        addSectionTitle(document, MPSRUI.TREE_6, fontChapterHeader, 0, 24, 12);

        addOutline(outline1, writer, MPSRUI.TREE_6_1);
        addSectionTitle(document, MPSRUI.TREE_6_1, fontSection1Header, 6, 12, 12);
        addParagraph(document, writer, xmlWorker, lpe.getDesc_6_1(), fontNormal, 12, 0, 12);

        outline2 = addOutline(outline1, writer, MPSRUI.TREE_6_2);
        addSectionTitle(document, MPSRUI.TREE_6_2, fontSection1Header, 6, 12, 12);

        addOutline(outline2, writer, MPSRUI.TREE_6_2_1);
        addSectionTitle(document, MPSRUI.TREE_6_2_1, fontSection2Header, 12, 12, 12);
        addParagraph(document, writer, xmlWorker, lpe.getDesc_6_2_1(), fontNormal, 12, 0, 12);

        addOutline(outline2, writer, MPSRUI.TREE_6_2_2);
        addSectionTitle(document, MPSRUI.TREE_6_2_2, fontSection2Header, 12, 12, 12);
        addParagraph(document, writer, xmlWorker, lpe.getDesc_6_2_2(), fontNormal, 12, 0, 12);

        // *******************************************************************************************//
        // 7 Engineering Status
        // *******************************************************************************************//

        outline1 = addOutline(root, writer, MPSRUI.TREE_7);
        addSectionTitle(document, MPSRUI.TREE_7, fontChapterHeader, 0, 24, 12);

        addOutline(outline1, writer, MPSRUI.TREE_7_1);
        addSectionTitle(document, MPSRUI.TREE_7_1, fontSection1Header, 6, 12, 12);

        table = new PdfPTable(5);
        table.setTotalWidth(500);
        table.setLockedWidth(true);
        table.setWidths(new int[] { 2, 1, 1, 1, 3 });
        table.setHorizontalAlignment(Element.ALIGN_CENTER);

        headers = new String[] { "Package", "IFR", "IFC", "Indicator", "Note" };
        for (String header : headers) {
            cell = new PdfPCell(new Phrase(header, fontTableColumnHeaderYellow));
            cell.setBackgroundColor(BaseColor.BLUE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
        }

        for (int i = 0; i < ipds.length; i++) {
            cell = new PdfPCell(new Phrase(ipds[i].getPackage()));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(ipds[i].getIFR()));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(ipds[i].getIFC()));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(ipds[i].getIndicator()));
            cell.setBackgroundColor(getBackgroundColor(ipds[i].getIndicator()));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(ipds[i].getNote()));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);
        }

        document.add(table);

        // -----------------------------------------------------------------------------------//

        addOutline(outline1, writer, MPSRUI.TREE_7_2);
        addSectionTitle(document, MPSRUI.TREE_7_2, fontSection1Header, 6, 12, 12);

        table = new PdfPTable(5);
        table.setTotalWidth(500);
        table.setLockedWidth(true);
        table.setWidths(new int[] { 2, 1, 1, 1, 3 });
        table.setHorizontalAlignment(Element.ALIGN_CENTER);

        headers = new String[] { "Package", "IFR", "IFC", "Indicator", "Note" };
        for (String header : headers) {
            cell = new PdfPCell(new Phrase(header, fontTableColumnHeaderYellow));
            cell.setBackgroundColor(BaseColor.BLUE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
        }

        for (int i = 0; i < opds.length; i++) {
            cell = new PdfPCell(new Phrase(opds[i].getPackage()));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(opds[i].getIFR()));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(opds[i].getIFC()));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(opds[i].getIndicator()));
            cell.setBackgroundColor(getBackgroundColor(opds[i].getIndicator()));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(opds[i].getNote()));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);
        }

        document.add(table);

        // *******************************************************************************************//
        // 8 Procurement Status
        // *******************************************************************************************//

        outline1 = addOutline(root, writer, MPSRUI.TREE_8);
        addSectionTitle(document, MPSRUI.TREE_8, fontChapterHeader, 0, 24, 12);

        outline2 = addOutline(outline1, writer, MPSRUI.TREE_8_1);
        addSectionTitle(document, MPSRUI.TREE_8_1, fontSection1Header, 6, 12, 12);

        table = new PdfPTable(2);
        table.setTotalWidth(300);
        table.setLockedWidth(true);
        table.setWidths(new int[] { 1, 1 });
        table.setHorizontalAlignment(Element.ALIGN_CENTER);

        cellValues = new String[][] {
                { "Receipted to Date", CURRENCY_FORMATTER.format(procure.getReceiptedToDate()) },
                { "Open Commitments", CURRENCY_FORMATTER.format(procure.getOpenCommitment()) },
                { "Total", CURRENCY_FORMATTER.format(procure.getTotalPurchaseOrder()) } };
        for (int i = 0; i < cellValues.length; i++) {
            cell = new PdfPCell(new Phrase(cellValues[i][0]));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(cellValues[i][1]));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
        }

        document.add(table);

        addParagraph(document, writer, xmlWorker, procure.getDesc_8_1_B(), fontNormal, 12, 12, 12);

        outline2 = addOutline(outline1, writer, MPSRUI.TREE_8_2);
        addSectionTitle(document, MPSRUI.TREE_8_2, fontSection1Header, 6, 12, 12);

        // ----------------------------------------------------
        // section 8.2.1
        // ----------------------------------------------------

        addOutline(outline2, writer, MPSRUI.TREE_8_2_1);
        addSectionTitle(document, MPSRUI.TREE_8_2_1, fontSection2Header, 12, 12, 12);
        addParagraph(document, writer, xmlWorker, procure.getDesc_8_2_1(), fontNormal, 12, 0, 12);

        table = new PdfPTable(6);
        table.setTotalWidth(550);
        table.setLockedWidth(true);
        table.setWidths(new int[] { 1, 2, 1, 1, 2, 1 });
        table.setHorizontalAlignment(Element.ALIGN_CENTER);

        headers = new String[] { "Purchase Order", "Vendor", "Previous Amount", "This Month Amount",
                "This Month Description", "Total Amount" };
        for (String header : headers) {
            cell = new PdfPCell(new Phrase(header, fontPOTableHeader));
            cell.setBackgroundColor(BaseColor.BLUE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
        }

        double totalToDate = 0;

        for (int i = 0; i < approvedChanges.length; i++) {
            cell = new PdfPCell(new Phrase(approvedChanges[i].getPurchaseOrder(), fontPOTable));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(approvedChanges[i].getVendor(), fontPOTable));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            cell = new PdfPCell(
                    new Phrase(CURRENCY_FORMATTER.format(approvedChanges[i].getPreviousAmount()), fontPOTable));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(CURRENCY_FORMATTER.format(approvedChanges[i].getThisMonthAmount()),
                    fontPOTable));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(approvedChanges[i].getThisMonthDescription(), fontPOTable));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            cell = new PdfPCell(
                    new Phrase(CURRENCY_FORMATTER.format(approvedChanges[i].getTotalAmount()), fontPOTable));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            totalToDate += approvedChanges[i].getTotalAmount();
        }

        document.add(table);

        table = new PdfPTable(2);
        table.setTotalWidth(550);
        table.setLockedWidth(true);
        table.setWidths(new int[] { 7, 1 });
        table.setHorizontalAlignment(Element.ALIGN_CENTER);

        cell = new PdfPCell(new Phrase("Total To Date", fontPOTableSummary));
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setVerticalAlignment(Element.ALIGN_TOP);
        table.addCell(cell);

        cell = new PdfPCell(new Phrase(CURRENCY_FORMATTER.format(totalToDate), fontPOTableSummary));
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_TOP);
        table.addCell(cell);

        document.add(table);

        // ----------------------------------------------------
        // section 8.2.2
        // ----------------------------------------------------

        addOutline(outline2, writer, MPSRUI.TREE_8_2_2);
        addSectionTitle(document, MPSRUI.TREE_8_2_2, fontSection2Header, 12, 12, 12);
        addParagraph(document, writer, xmlWorker, procure.getDesc_8_2_2(), fontNormal, 12, 0, 12);

        table = new PdfPTable(6);
        table.setTotalWidth(550);
        table.setLockedWidth(true);
        table.setWidths(new int[] { 1, 2, 1, 1, 2, 1 });
        table.setHorizontalAlignment(Element.ALIGN_CENTER);

        headers = new String[] { "Purchase Order", "Vendor", "Previous Amount", "This Month Amount",
                "This Month Description", "Total Amount" };
        for (String header : headers) {
            cell = new PdfPCell(new Phrase(header, fontPOTableHeader));
            cell.setBackgroundColor(BaseColor.BLUE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell);
        }

        totalToDate = 0;

        for (int i = 0; i < pendingChanges.length; i++) {
            cell = new PdfPCell(new Phrase(pendingChanges[i].getPurchaseOrder(), fontPOTable));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(pendingChanges[i].getVendor(), fontPOTable));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            cell = new PdfPCell(
                    new Phrase(CURRENCY_FORMATTER.format(pendingChanges[i].getPreviousAmount()), fontPOTable));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            cell = new PdfPCell(
                    new Phrase(CURRENCY_FORMATTER.format(pendingChanges[i].getThisMonthAmount()), fontPOTable));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase(pendingChanges[i].getThisMonthDescription(), fontPOTable));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            cell = new PdfPCell(
                    new Phrase(CURRENCY_FORMATTER.format(pendingChanges[i].getTotalAmount()), fontPOTable));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setVerticalAlignment(Element.ALIGN_TOP);
            table.addCell(cell);

            totalToDate += pendingChanges[i].getTotalAmount();
        }

        document.add(table);

        table = new PdfPTable(2);
        table.setTotalWidth(550);
        table.setLockedWidth(true);
        table.setWidths(new int[] { 7, 1 });
        table.setHorizontalAlignment(Element.ALIGN_CENTER);

        cell = new PdfPCell(new Phrase("Total To Date", fontPOTableSummary));
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setVerticalAlignment(Element.ALIGN_TOP);
        table.addCell(cell);

        cell = new PdfPCell(new Phrase(CURRENCY_FORMATTER.format(totalToDate), fontPOTableSummary));
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_TOP);
        table.addCell(cell);

        document.add(table);

        // *******************************************************************************************//
        // 9 Construction Status
        // *******************************************************************************************//

        outline1 = addOutline(root, writer, MPSRUI.TREE_9);
        addSectionTitle(document, MPSRUI.TREE_9, fontChapterHeader, 0, 24, 12);

        addOutline(outline1, writer, MPSRUI.TREE_9_1);
        addSectionTitle(document, MPSRUI.TREE_9_1, fontSection1Header, 6, 12, 12);

        for (int i = 0; i < ipcs.length; i++) {
            addParagraph(document, writer, xmlWorker, ipcs[i].getWork(), fontWork, 12, 12, 0);
            addParagraph(document, writer, xmlWorker, ipcs[i].getDescription(), fontNormal, 12, 0, 0);
            addImage(document, MPSRUI.getFilePath(mpsrID, ipcs[i].getFileName()),
                    "Figure " + ipcs[i].getFigure() + " " + ipcs[i].getTitle(), fontImageCaption, 12, 3, 12);
        }

        // -----------------------------------------------------------------------------------------//

        addOutline(outline1, writer, MPSRUI.TREE_9_2);
        addSectionTitle(document, MPSRUI.TREE_9_2, fontSection1Header, 6, 12, 12);

        for (int i = 0; i < opcs.length; i++) {
            addParagraph(document, writer, xmlWorker, opcs[i].getWork(), fontWork, 12, 12, 0);
            addParagraph(document, writer, xmlWorker, opcs[i].getDescription(), fontNormal, 12, 0, 0);
            addImage(document, MPSRUI.getFilePath(mpsrID, opcs[i].getFileName()),
                    "Figure " + opcs[i].getFigure() + " " + opcs[i].getTitle(), fontImageCaption, 12, 3, 12);
        }

        // *******************************************************************************************//
        // Appendix
        // *******************************************************************************************//

        if (appendixs.length > 0) {

            document.add(Chunk.NEXTPAGE);
            outline1 = addOutline(root, writer, MPSRUI.TREE_APPENDIX);

            for (int i = 0; i < appendixs.length; i++) {
                addOutline(outline1, writer,
                        "Appendix " + appendixs[i].getNumber() + "  " + appendixs[i].getTitle());
                addSectionTitle(document,
                        "Appendix " + appendixs[i].getNumber() + "  " + appendixs[i].getTitle(),
                        fontChapterHeader, 0, 12, 12);
                addParagraph(document, writer, xmlWorker, appendixs[i].getDescription(), fontNormal, 12, 0, 0);

                importPages(document, writer, mpsrID, appendixs[i].getFileName());
            }
        }

        // *******************************************************************************************//
        // Attachment
        // *******************************************************************************************//

        if (attachments.length > 0) {

            document.setPageSize(DEFAULT_PAGE_SIZE);
            document.add(Chunk.NEXTPAGE);
            outline1 = addOutline(root, writer, MPSRUI.TREE_ATTACHMENT);

            for (int i = 0; i < attachments.length; i++) {
                addOutline(outline1, writer,
                        "Attachment " + attachments[i].getNumber() + "  " + attachments[i].getTitle());
                addSectionTitle(document,
                        "Attachment " + attachments[i].getNumber() + "  " + attachments[i].getTitle(),
                        fontChapterHeader, 0, 12, 12);
                addParagraph(document, writer, xmlWorker, attachments[i].getDescription(), fontNormal, 12, 0,
                        0);

                importPages(document, writer, mpsrID, attachments[i].getFileName());
            }
        }

        document.close();

        // *******************************************************************************************//

        // retrieve outline
        PdfReader readerOrig = new PdfReader(baosOrig.toByteArray());
        // int origNumberOfPages = readerOrig.getNumberOfPages();
        ColumnText ct = new ColumnText(null);
        ct.addElement(new Paragraph("Table of Contents", fontCoverTitle));
        List<HashMap<String, Object>> bookmarkList = SimpleBookmark.getBookmark(readerOrig);
        fillColumnText(bookmarkList, ct, 18, 0, fontSection2Header);

        // generate TOC after cover page
        ByteArrayOutputStream baosTOC = new ByteArrayOutputStream();
        PdfStamper stamperTOC = new PdfStamper(readerOrig, baosTOC);
        int tocPageEnd = 1;
        while (true) {
            stamperTOC.insertPage(++tocPageEnd, readerOrig.getPageSize(1));

            PdfContentByte underContent = stamperTOC.getUnderContent(tocPageEnd);

            generatePageHeader(document, underContent, icon, headerTexts);

            ct.setCanvas(stamperTOC.getOverContent(tocPageEnd));
            ct.setSimpleColumn(36, 36, 558, 693);
            if (!ColumnText.hasMoreText(ct.go()))
                break;
        }
        stamperTOC.close();

        // change page labels
        PdfPageLabels labels = new PdfPageLabels();
        labels.addPageLabel(1, PdfPageLabels.LOWERCASE_ROMAN_NUMERALS);
        labels.addPageLabel(tocPageEnd + 1, PdfPageLabels.DECIMAL_ARABIC_NUMERALS);

        // add labels
        ByteArrayOutputStream baosFinal = new ByteArrayOutputStream();
        PdfReader readerTOC = new PdfReader(baosTOC.toByteArray());
        // String selectPages = String.format("1-%s,%s-%s", tocPageEnd,
        // tocPageEnd + 1, origNumberOfPages + (tocPageEnd - 1));
        // readerTOC.selectPages(selectPages);
        PdfStamper stamperFinal = new PdfStamper(readerTOC, baosFinal);
        stamperFinal.getWriter().setPageLabels(labels);
        stamperFinal.close();

        // *******************************************************************************************//

        // send final PDF to browser
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Pragma", "public");
        response.setContentType("application/pdf");
        response.setContentLength(baosFinal.size());

        OutputStream os = response.getOutputStream();
        os.write(baosFinal.toByteArray());
        os.flush();
        os.close();

    } catch (DocumentException e) {
        e.printStackTrace();
    }

}

From source file:mobisocial.musubi.util.UriImage.java

/**
 * Returns the bytes for this UriImage. If the uri for the image is remote,
 * then this code must not be run on the main thread.
 *//*from  ww w . j  av  a 2  s  .  c om*/
public byte[] getResizedImageData(int widthLimit, int heightLimit, int byteLimit, boolean square)
        throws IOException {
    if (!mDecodedBounds) {
        decodeBoundsInfo();
        mDecodedBounds = true;
    }
    InputStream input = null;
    try {
        int inDensity = 0;
        int targetDensity = 0;
        BitmapFactory.Options read_options = new BitmapFactory.Options();
        read_options.inJustDecodeBounds = true;
        input = openInputStream(mUri);
        BitmapFactory.decodeStream(input, null, read_options);
        if (read_options.outWidth > widthLimit || read_options.outHeight > heightLimit) {
            //we need to scale
            if (read_options.outWidth / widthLimit > read_options.outHeight / heightLimit) {
                //width is the large edge
                if (read_options.outWidth * heightLimit > widthLimit * read_options.outHeight) {
                    //incoming image is wider than target
                    inDensity = read_options.outWidth;
                    targetDensity = widthLimit;
                } else {
                    //incoming image is taller than target
                    inDensity = read_options.outHeight;
                    targetDensity = heightLimit;

                }
            } else {
                //height is the long edge, swap the limits
                if (read_options.outWidth * widthLimit > heightLimit * read_options.outHeight) {
                    //incoming image is wider than target
                    inDensity = read_options.outWidth;
                    targetDensity = heightLimit;
                } else {
                    //incoming image is taller than target
                    inDensity = read_options.outHeight;
                    targetDensity = widthLimit;

                }
            }
        } else {
            //no scale
            if (read_options.outWidth > read_options.outHeight) {
                inDensity = targetDensity = read_options.outWidth;
            } else {
                inDensity = targetDensity = read_options.outHeight;
            }
        }

        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG,
                    "getResizedImageData: wlimit=" + widthLimit + ", hlimit=" + heightLimit + ", sizeLimit="
                            + byteLimit + ", mWidth=" + mWidth + ", mHeight=" + mHeight + ", initialRatio="
                            + targetDensity + "/" + inDensity);
        }

        ByteArrayOutputStream os = null;
        int attempts = 1;

        int lowMemoryReduce = 1;
        do {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inDensity = inDensity;
            options.inSampleSize = lowMemoryReduce;
            options.inScaled = lowMemoryReduce == 1;
            options.inTargetDensity = targetDensity;
            //no purgeable because we are only trying to resave this
            if (input != null)
                input.close();
            input = openInputStream(mUri);
            int quality = IMAGE_COMPRESSION_QUALITY;
            try {
                Bitmap b = BitmapFactory.decodeStream(input, null, options);
                if (b == null) {
                    return null;
                }
                if (options.outWidth > widthLimit + 1 || options.outHeight > heightLimit + 1) {
                    // The decoder does not support the inSampleSize option.
                    // Scale the bitmap using Bitmap library.
                    int scaledWidth;
                    int scaledHeight;
                    scaledWidth = options.outWidth * targetDensity / inDensity;
                    scaledHeight = options.outHeight * targetDensity / inDensity;

                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
                        Log.v(TAG, "getResizedImageData: retry scaling using " + "Bitmap.createScaledBitmap: w="
                                + scaledWidth + ", h=" + scaledHeight);
                    }

                    if (square) {
                        int w = b.getWidth();
                        int h = b.getHeight();
                        int dim = Math.min(w, h);
                        b = Bitmap.createBitmap(b, (w - dim) / 2, (h - dim) / 2, dim, dim);
                        scaledWidth = dim;
                        scaledHeight = dim;
                    }
                    Bitmap b2 = Bitmap.createScaledBitmap(b, scaledWidth, scaledHeight, false);
                    b.recycle();
                    b = b2;
                    if (b == null) {
                        return null;
                    }
                }

                Matrix matrix = new Matrix();
                if (mRotation != 0f) {
                    matrix.preRotate(mRotation);
                }

                Bitmap old = b;
                b = Bitmap.createBitmap(old, 0, 0, old.getWidth(), old.getHeight(), matrix, true);

                // Compress the image into a JPG. Start with MessageUtils.IMAGE_COMPRESSION_QUALITY.
                // In case that the image byte size is still too large reduce the quality in
                // proportion to the desired byte size. Should the quality fall below
                // MINIMUM_IMAGE_COMPRESSION_QUALITY skip a compression attempt and we will enter
                // the next round with a smaller image to start with.
                os = new ByteArrayOutputStream();
                b.compress(CompressFormat.JPEG, quality, os);
                int jpgFileSize = os.size();
                if (jpgFileSize > byteLimit) {
                    int reducedQuality = quality * byteLimit / jpgFileSize;
                    //always try to squish it before computing the new size
                    if (reducedQuality < MINIMUM_IMAGE_COMPRESSION_QUALITY) {
                        reducedQuality = MINIMUM_IMAGE_COMPRESSION_QUALITY;
                    }
                    quality = reducedQuality;

                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
                        Log.v(TAG, "getResizedImageData: compress(2) w/ quality=" + quality);
                    }

                    os = new ByteArrayOutputStream();
                    b.compress(CompressFormat.JPEG, quality, os);
                }
                b.recycle(); // done with the bitmap, release the memory
            } catch (java.lang.OutOfMemoryError e) {
                Log.w(TAG, "getResizedImageData - image too big (OutOfMemoryError), will try "
                        + " with smaller scale factor, cur scale factor", e);
                lowMemoryReduce *= 2;
                // fall through and keep trying with a smaller scale factor.
            }
            if (true || Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG,
                        "attempt=" + attempts + " size=" + (os == null ? 0 : os.size()) + " width="
                                + options.outWidth + " height=" + options.outHeight + " Ratio=" + targetDensity
                                + "/" + inDensity + " quality=" + quality);
            }
            //move halfway to the target
            targetDensity = (os == null) ? (int) (targetDensity * .8)
                    : (targetDensity * byteLimit / os.size() + targetDensity) / 2;
            attempts++;
        } while ((os == null || os.size() > byteLimit) && attempts < NUMBER_OF_RESIZE_ATTEMPTS);

        return os == null ? null : os.toByteArray();
    } catch (Throwable t) {
        Log.e(TAG, t.getMessage(), t);
        return null;
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                Log.e(TAG, e.getMessage(), e);
            }
        }
    }
}

From source file:mobisocial.noteshere.util.UriImage.java

/**
 * Returns the bytes for this UriImage. If the uri for the image is remote,
 * then this code must not be run on the main thread.
 *///from   ww  w .j  a  v  a2s .  c  om
public byte[] getResizedImageData(int widthLimit, int heightLimit, int byteLimit, boolean square)
        throws IOException {
    if (!mDecodedBounds) {
        decodeBoundsInfo();
        mDecodedBounds = true;
    }
    InputStream input = null;
    try {
        int inDensity = 0;
        int targetDensity = 0;
        BitmapFactory.Options read_options = new BitmapFactory.Options();
        read_options.inJustDecodeBounds = true;
        input = openInputStream(mUri);
        BitmapFactory.decodeStream(input, null, read_options);
        if (read_options.outWidth > widthLimit || read_options.outHeight > heightLimit) {
            //we need to scale
            if (read_options.outWidth / widthLimit > read_options.outHeight / heightLimit) {
                //width is the large edge
                if (read_options.outWidth * heightLimit > widthLimit * read_options.outHeight) {
                    //incoming image is wider than target
                    inDensity = read_options.outWidth;
                    targetDensity = widthLimit;
                } else {
                    //incoming image is taller than target
                    inDensity = read_options.outHeight;
                    targetDensity = heightLimit;

                }
            } else {
                //height is the long edge, swap the limits
                if (read_options.outWidth * widthLimit > heightLimit * read_options.outHeight) {
                    //incoming image is wider than target
                    inDensity = read_options.outWidth;
                    targetDensity = heightLimit;
                } else {
                    //incoming image is taller than target
                    inDensity = read_options.outHeight;
                    targetDensity = widthLimit;

                }
            }
        } else {
            //no scale
            if (read_options.outWidth > read_options.outHeight) {
                inDensity = targetDensity = read_options.outWidth;
            } else {
                inDensity = targetDensity = read_options.outHeight;
            }
        }

        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG,
                    "getResizedImageData: wlimit=" + widthLimit + ", hlimit=" + heightLimit + ", sizeLimit="
                            + byteLimit + ", mWidth=" + mWidth + ", mHeight=" + mHeight + ", initialRatio="
                            + targetDensity + "/" + inDensity);
        }

        ByteArrayOutputStream os = null;
        int attempts = 1;

        int lowMemoryReduce = 1;
        do {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inDensity = inDensity;
            options.inSampleSize = lowMemoryReduce;
            options.inScaled = lowMemoryReduce == 1;
            options.inTargetDensity = targetDensity;
            //no purgeable because we are only trying to resave this
            if (input != null)
                input.close();
            input = openInputStream(mUri);
            int quality = IMAGE_COMPRESSION_QUALITY;
            try {
                Bitmap b = BitmapFactory.decodeStream(input, null, options);
                if (b == null) {
                    return null;
                }
                if (options.outWidth > widthLimit + 1 || options.outHeight > heightLimit + 1) {
                    // The decoder does not support the inSampleSize option.
                    // Scale the bitmap using Bitmap library.
                    int scaledWidth;
                    int scaledHeight;
                    scaledWidth = options.outWidth * targetDensity / inDensity;
                    scaledHeight = options.outHeight * targetDensity / inDensity;

                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
                        Log.v(TAG, "getResizedImageData: retry scaling using " + "Bitmap.createScaledBitmap: w="
                                + scaledWidth + ", h=" + scaledHeight);
                    }

                    if (square) {
                        int w = b.getWidth();
                        int h = b.getHeight();
                        int dim = Math.min(w, h);
                        b = Bitmap.createBitmap(b, (w - dim) / 2, (h - dim) / 2, dim, dim);
                        scaledWidth = dim;
                        scaledHeight = dim;
                    }
                    Bitmap b2 = Bitmap.createScaledBitmap(b, scaledWidth, scaledHeight, false);
                    b.recycle();
                    b = b2;
                    if (b == null) {
                        return null;
                    }
                }

                Matrix matrix = new Matrix();
                if (mRotation != 0f) {
                    matrix.preRotate(mRotation);
                }

                Bitmap old = b;
                b = Bitmap.createBitmap(old, 0, 0, old.getWidth(), old.getHeight(), matrix, true);

                // Compress the image into a JPG. Start with MessageUtils.IMAGE_COMPRESSION_QUALITY.
                // In case that the image byte size is still too large reduce the quality in
                // proportion to the desired byte size. Should the quality fall below
                // MINIMUM_IMAGE_COMPRESSION_QUALITY skip a compression attempt and we will enter
                // the next round with a smaller image to start with.
                os = new ByteArrayOutputStream();
                b.compress(CompressFormat.JPEG, quality, os);
                int jpgFileSize = os.size();
                if (jpgFileSize > byteLimit) {
                    int reducedQuality = quality * byteLimit / jpgFileSize;
                    //always try to squish it before computing the new size
                    if (reducedQuality < MINIMUM_IMAGE_COMPRESSION_QUALITY) {
                        reducedQuality = MINIMUM_IMAGE_COMPRESSION_QUALITY;
                    }
                    quality = reducedQuality;

                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
                        Log.v(TAG, "getResizedImageData: compress(2) w/ quality=" + quality);
                    }

                    os = new ByteArrayOutputStream();
                    b.compress(CompressFormat.JPEG, quality, os);
                }
                b.recycle(); // done with the bitmap, release the memory
            } catch (java.lang.OutOfMemoryError e) {
                Log.w(TAG, "getResizedImageData - image too big (OutOfMemoryError), will try "
                        + " with smaller scale factor, cur scale factor", e);
                lowMemoryReduce *= 2;
                // fall through and keep trying with a smaller scale factor.
            }
            Log.v(TAG,
                    "attempt=" + attempts + " size=" + (os == null ? 0 : os.size()) + " width="
                            + options.outWidth + " height=" + options.outHeight + " Ratio=" + targetDensity
                            + "/" + inDensity + " quality=" + quality);
            //move halfway to the target
            targetDensity = (os == null) ? (int) (targetDensity * .8)
                    : (targetDensity * byteLimit / os.size() + targetDensity) / 2;
            attempts++;
        } while ((os == null || os.size() > byteLimit) && attempts < NUMBER_OF_RESIZE_ATTEMPTS);

        return os == null ? null : os.toByteArray();
    } catch (Throwable t) {
        Log.e(TAG, t.getMessage(), t);
        return null;
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                Log.e(TAG, e.getMessage(), e);
            }
        }
    }
}

From source file:org.elasticsearch.client.Request.java

static Request bulk(BulkRequest bulkRequest) throws IOException {
    Params parameters = Params.builder();
    parameters.withTimeout(bulkRequest.timeout());
    parameters.withRefreshPolicy(bulkRequest.getRefreshPolicy());

    // Bulk API only supports newline delimited JSON or Smile. Before executing
    // the bulk, we need to check that all requests have the same content-type
    // and this content-type is supported by the Bulk API.
    XContentType bulkContentType = null;
    for (int i = 0; i < bulkRequest.numberOfActions(); i++) {
        DocWriteRequest<?> request = bulkRequest.requests().get(i);

        DocWriteRequest.OpType opType = request.opType();
        if (opType == DocWriteRequest.OpType.INDEX || opType == DocWriteRequest.OpType.CREATE) {
            bulkContentType = enforceSameContentType((IndexRequest) request, bulkContentType);

        } else if (opType == DocWriteRequest.OpType.UPDATE) {
            UpdateRequest updateRequest = (UpdateRequest) request;
            if (updateRequest.doc() != null) {
                bulkContentType = enforceSameContentType(updateRequest.doc(), bulkContentType);
            }/*from  www  .  j a  va2  s. co  m*/
            if (updateRequest.upsertRequest() != null) {
                bulkContentType = enforceSameContentType(updateRequest.upsertRequest(), bulkContentType);
            }
        }
    }

    if (bulkContentType == null) {
        bulkContentType = XContentType.JSON;
    }

    byte separator = bulkContentType.xContent().streamSeparator();
    ContentType requestContentType = ContentType.create(bulkContentType.mediaType());

    ByteArrayOutputStream content = new ByteArrayOutputStream();
    for (DocWriteRequest<?> request : bulkRequest.requests()) {
        DocWriteRequest.OpType opType = request.opType();

        try (XContentBuilder metadata = XContentBuilder.builder(bulkContentType.xContent())) {
            metadata.startObject();
            {
                metadata.startObject(opType.getLowercase());
                if (Strings.hasLength(request.index())) {
                    metadata.field("_index", request.index());
                }
                if (Strings.hasLength(request.type())) {
                    metadata.field("_type", request.type());
                }
                if (Strings.hasLength(request.id())) {
                    metadata.field("_id", request.id());
                }
                if (Strings.hasLength(request.routing())) {
                    metadata.field("_routing", request.routing());
                }
                if (Strings.hasLength(request.parent())) {
                    metadata.field("_parent", request.parent());
                }
                if (request.version() != Versions.MATCH_ANY) {
                    metadata.field("_version", request.version());
                }

                VersionType versionType = request.versionType();
                if (versionType != VersionType.INTERNAL) {
                    if (versionType == VersionType.EXTERNAL) {
                        metadata.field("_version_type", "external");
                    } else if (versionType == VersionType.EXTERNAL_GTE) {
                        metadata.field("_version_type", "external_gte");
                    } else if (versionType == VersionType.FORCE) {
                        metadata.field("_version_type", "force");
                    }
                }

                if (opType == DocWriteRequest.OpType.INDEX || opType == DocWriteRequest.OpType.CREATE) {
                    IndexRequest indexRequest = (IndexRequest) request;
                    if (Strings.hasLength(indexRequest.getPipeline())) {
                        metadata.field("pipeline", indexRequest.getPipeline());
                    }
                } else if (opType == DocWriteRequest.OpType.UPDATE) {
                    UpdateRequest updateRequest = (UpdateRequest) request;
                    if (updateRequest.retryOnConflict() > 0) {
                        metadata.field("_retry_on_conflict", updateRequest.retryOnConflict());
                    }
                    if (updateRequest.fetchSource() != null) {
                        metadata.field("_source", updateRequest.fetchSource());
                    }
                }
                metadata.endObject();
            }
            metadata.endObject();

            BytesRef metadataSource = metadata.bytes().toBytesRef();
            content.write(metadataSource.bytes, metadataSource.offset, metadataSource.length);
            content.write(separator);
        }

        BytesRef source = null;
        if (opType == DocWriteRequest.OpType.INDEX || opType == DocWriteRequest.OpType.CREATE) {
            IndexRequest indexRequest = (IndexRequest) request;
            BytesReference indexSource = indexRequest.source();
            XContentType indexXContentType = indexRequest.getContentType();

            try (XContentParser parser = XContentHelper.createParser(NamedXContentRegistry.EMPTY, indexSource,
                    indexXContentType)) {
                try (XContentBuilder builder = XContentBuilder.builder(bulkContentType.xContent())) {
                    builder.copyCurrentStructure(parser);
                    source = builder.bytes().toBytesRef();
                }
            }
        } else if (opType == DocWriteRequest.OpType.UPDATE) {
            source = XContentHelper.toXContent((UpdateRequest) request, bulkContentType, false).toBytesRef();
        }

        if (source != null) {
            content.write(source.bytes, source.offset, source.length);
            content.write(separator);
        }
    }

    HttpEntity entity = new ByteArrayEntity(content.toByteArray(), 0, content.size(), requestContentType);
    return new Request(HttpPost.METHOD_NAME, "/_bulk", parameters.getParams(), entity);
}

From source file:org.dbgl.gui.EditProfileDialog.java

protected boolean init() {
    try {//  w  w  w  .  ja  v  a2  s. com
        dbversionsList = dbase.readDosboxVersionsList();
        developersList = dbase.readDevelopersList();
        publishersList = dbase.readPublishersList();
        genresList = dbase.readGenresList();
        yearsList = dbase.readYearsList();
        templatesList = dbase.readTemplatesList();
        statusList = dbase.readStatusList();
        for (int i = 0; i < AMOUNT_OF_CUSTOM_STRINGS; i++) {
            customList.add(dbase.readCustomList(i));
        }

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(bos);

        if (result instanceof Profile) {
            Profile profile = (Profile) result;
            dbversionIndex = DosboxVersion.findIndexById(dbversionsList, profile.getDbversionId());
            DosboxVersion dbversion = dbversionsList.get(dbversionIndex);
            Conf cc = new Conf(profile, dbversion, ps);
            if ((cc.getAutoexec().isIncomplete()) && (!GeneralPurposeDialogs.confirmMessage(getParent(),
                    settings.msg("dialog.profile.confirm.profileincomplete",
                            new Object[] { FileUtils.DOSBOX_CONF, dbversion.getCanonicalConfFile() })))) {
                return false;
            }
            java.util.List<NativeCommand> nativeCommands = dbase.readNativeCommandsList(profile.getId(), -1);
            multiProfileList.add(new ExpProfile(profile.getId(), cc,
                    FileUtils.makeRelativeToDosroot(cc.getAutoexec().getCanonicalMainDir()), nativeCommands,
                    profile));
        } else if (isMultiEdit()) {
            dbversionIndex = DosboxVersion.findIndexById(dbversionsList, multiProfileCombined.getDbversionId());
        } else {
            dbversionIndex = DosboxVersion.indexOfDefault(dbversionsList);
            DosboxVersion dbversion = dbversionsList.get(dbversionIndex);
            templateIndex = Template.indexOfDefault(templatesList);
            Conf cc = null;
            java.util.List<NativeCommand> nativeCommands = null;
            if ((result instanceof String) && FileUtils.isConfFile((String) result)) {
                cc = new Conf(FileUtils.canonicalToDosroot((String) result), (Template) null, dbversion, ps);
                nativeCommands = dbase.readNativeCommandsList(-1, -1);
            } else if (templateIndex != -1) {
                cc = new Conf((File) null, templatesList.get(templateIndex), dbversion, ps);
                nativeCommands = dbase.readNativeCommandsList(-1, templatesList.get(templateIndex).getId());
            } else {
                cc = new Conf((File) null, (Template) null, dbversion, ps);
                nativeCommands = dbase.readNativeCommandsList(-1, -1);
            }
            multiProfileList.add(new ExpProfile(cc, nativeCommands));
        }
        if (bos.size() > 0) {
            GeneralPurposeDialogs.warningMessage(getParent(), bos.toString());
            bos.reset();
        }
        return true;

    } catch (Exception e) {
        GeneralPurposeDialogs.warningMessage(getParent(), e);
        return false;
    }
}

From source file:net.lightbody.bmp.proxy.jetty.http.handler.DumpHandler.java

public void handle(String pathInContext, String pathParams, HttpRequest request, HttpResponse response)
        throws HttpException, IOException {
    if (!isStarted())
        return;/*www .  ja  v a  2  s.com*/

    // Only handle GET, HEAD and POST
    if (!HttpRequest.__GET.equals(request.getMethod()) && !HttpRequest.__HEAD.equals(request.getMethod())
            && !HttpRequest.__POST.equals(request.getMethod()))
        return;

    log.debug("Dump");

    response.setField(HttpFields.__ContentType, HttpFields.__TextHtml);
    OutputStream out = response.getOutputStream();
    ByteArrayOutputStream buf = new ByteArrayOutputStream(2048);
    Writer writer = new OutputStreamWriter(buf, StringUtil.__ISO_8859_1);
    writer.write("<HTML><H1>Dump HttpHandler</H1>");
    writer.write("<PRE>\npath=" + request.getPath() + "\ncontextPath=" + getHttpContext().getContextPath()
            + "\npathInContext=" + pathInContext + "\n</PRE>\n");
    writer.write("<H3>Header:</H3><PRE>");
    writer.write(request.toString());
    writer.write("</PRE>\n<H3>Parameters:</H3>\n<PRE>");
    Set names = request.getParameterNames();
    Iterator iter = names.iterator();
    while (iter.hasNext()) {
        String name = iter.next().toString();
        List values = request.getParameterValues(name);
        if (values == null || values.size() == 0) {
            writer.write(name);
            writer.write("=\n");
        } else if (values.size() == 1) {
            writer.write(name);
            writer.write("=");
            writer.write((String) values.get(0));
            writer.write("\n");
        } else {
            for (int i = 0; i < values.size(); i++) {
                writer.write(name);
                writer.write("[" + i + "]=");
                writer.write((String) values.get(i));
                writer.write("\n");
            }
        }
    }

    String cookie_name = request.getParameter("CookieName");
    if (cookie_name != null && cookie_name.trim().length() > 0) {
        String cookie_action = request.getParameter("Button");
        try {
            Cookie cookie = new Cookie(cookie_name.trim(), request.getParameter("CookieVal"));
            if ("Clear Cookie".equals(cookie_action))
                cookie.setMaxAge(0);
            response.addSetCookie(cookie);
        } catch (IllegalArgumentException e) {
            writer.write("</PRE>\n<H3>BAD Set-Cookie:</H3>\n<PRE>");
            writer.write(e.toString());
            LogSupport.ignore(log, e);
        }
    }

    writer.write("</PRE>\n<H3>Cookies:</H3>\n<PRE>");
    Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0) {
        for (int c = 0; c < cookies.length; c++) {
            Cookie cookie = cookies[c];
            writer.write(cookie.getName());
            writer.write("=");
            writer.write(cookie.getValue());
            writer.write("\n");
        }
    }

    writer.write("</PRE>\n<H3>Attributes:</H3>\n<PRE>");
    Enumeration attributes = request.getAttributeNames();
    if (attributes != null && attributes.hasMoreElements()) {
        while (attributes.hasMoreElements()) {
            String attr = attributes.nextElement().toString();
            writer.write(attr);
            writer.write("=");
            writer.write(request.getAttribute(attr).toString());
            writer.write("\n");
        }
    }

    writer.write("</PRE>\n<H3>Content:</H3>\n<PRE>");
    byte[] content = new byte[4096];
    int len;
    try {
        InputStream in = request.getInputStream();
        while ((len = in.read(content)) >= 0)
            writer.write(new String(content, 0, len));
    } catch (IOException e) {
        LogSupport.ignore(log, e);
        writer.write(e.toString());
    }

    // You wouldn't normally set a trailer like this, but
    // we don't want to commit the output to force trailers as
    // it makes test harness messy
    request.getAcceptableTransferCodings();

    // commit now
    writer.flush();
    response.setIntField(HttpFields.__ContentLength, buf.size() + 1000);
    buf.writeTo(out);
    out.flush();

    // Now add the response
    buf.reset();
    writer.write("</PRE>\n<H3>Response:</H3>\n<PRE>");
    writer.write(response.toString());
    writer.write("</PRE></HTML>");
    writer.flush();
    for (int pad = 998 - buf.size(); pad-- > 0;)
        writer.write(" ");
    writer.write("\015\012");
    writer.flush();
    buf.writeTo(out);

    request.setHandled(true);
}

From source file:org.kuali.kfs.module.tem.document.web.struts.TravelActionBase.java

/**
 *
 * @param request//from ww w  . ja v  a 2s.  c o  m
 * @param response
 * @param reportFile
 * @param fileName
 * @throws IOException
 */
@SuppressWarnings("rawtypes")
protected void displayPDF(HttpServletRequest request, HttpServletResponse response, File reportFile,
        StringBuilder fileName) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    String contentDisposition = "";
    try {
        ArrayList master = new ArrayList();
        PdfCopy writer = null;

        // create a reader for the document
        String reportName = reportFile.getAbsolutePath();
        PdfReader reader = new PdfReader(reportName);
        reader.consolidateNamedDestinations();

        // retrieve the total number of pages
        int n = reader.getNumberOfPages();
        List bookmarks = SimpleBookmark.getBookmark(reader);
        if (bookmarks != null) {
            master.addAll(bookmarks);
        }

        // step 1: create a document-object
        com.lowagie.text.Document pdfDoc = new com.lowagie.text.Document(reader.getPageSizeWithRotation(1));
        // step 2: create a writer that listens to the document
        writer = new PdfCopy(pdfDoc, baos);
        // step 3: open the document
        pdfDoc.open();
        // step 4: add content
        PdfImportedPage page;
        for (int i = 0; i < n;) {
            ++i;
            page = writer.getImportedPage(reader, i);
            writer.addPage(page);
        }
        writer.freeReader(reader);
        if (!master.isEmpty()) {
            writer.setOutlines(master);
        }
        // step 5: we close the document
        pdfDoc.close();

        StringBuffer sbContentDispValue = new StringBuffer();
        String useJavascript = request.getParameter("useJavascript");
        if (useJavascript == null || useJavascript.equalsIgnoreCase("false")) {
            sbContentDispValue.append("attachment");
        } else {
            sbContentDispValue.append("inline");
        }
        sbContentDispValue.append("; filename=");
        sbContentDispValue.append(fileName);

        contentDisposition = sbContentDispValue.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }

    response.setContentType("application/pdf");
    response.setHeader("Content-Disposition", contentDisposition);
    response.setHeader("Expires", "0");
    response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
    response.setHeader("Pragma", "public");
    response.setContentLength(baos.size());

    // write to output
    ServletOutputStream sos;
    sos = response.getOutputStream();
    baos.writeTo(sos);
    sos.flush();
    sos.close();
}

From source file:com.dh.perfectoffer.event.framework.net.network.NetworkConnectionImpl.java

/**
 * Call the webservice using the given parameters to construct the request
 * and return the result./*  w  w w.jav  a  2 s  .co m*/
 * 
 * @param context
 *            The context to use for this operation. Used to generate the
 *            user agent if needed.
 * @param urlValue
 *            The webservice URL.
 * @param method
 *            The request method to use.
 * @param parameterList
 *            The parameters to add to the request.
 * @param headerMap
 *            The headers to add to the request.
 * @param isGzipEnabled
 *            Whether the request will use gzip compression if available on
 *            the server.
 * @param userAgent
 *            The user agent to set in the request. If null, a default
 *            Android one will be created.
 * @param postText
 *            The POSTDATA text to add in the request.
 * @param credentials
 *            The credentials to use for authentication.
 * @param isSslValidationEnabled
 *            Whether the request will validate the SSL certificates.
 * @return The result of the webservice call.
 */
public static ConnectionResult execute(Context context, String urlValue, Method method,
        ArrayList<BasicNameValuePair> parameterList, HashMap<String, String> headerMap, boolean isGzipEnabled,
        String userAgent, String postText, UsernamePasswordCredentials credentials,
        boolean isSslValidationEnabled, String contentType, List<byte[]> fileByteDates,
        List<String> fileMimeTypes, int httpErrorResCodeFilte, boolean isMulFiles) throws ConnectionException {
    HttpURLConnection connection = null;
    try {
        // Prepare the request information
        if (userAgent == null) {
            userAgent = UserAgentUtils.get(context);
        }
        if (headerMap == null) {
            headerMap = new HashMap<String, String>();
        }
        headerMap.put(HTTP.USER_AGENT, userAgent);
        if (isGzipEnabled) {
            headerMap.put(ACCEPT_ENCODING_HEADER, "gzip");
        }
        headerMap.put(ACCEPT_CHARSET_HEADER, UTF8_CHARSET);
        if (credentials != null) {
            headerMap.put(AUTHORIZATION_HEADER, createAuthenticationHeader(credentials));
        }

        StringBuilder paramBuilder = new StringBuilder();
        if (parameterList != null && !parameterList.isEmpty()) {
            for (int i = 0, size = parameterList.size(); i < size; i++) {
                BasicNameValuePair parameter = parameterList.get(i);
                String name = parameter.getName();
                String value = parameter.getValue();
                if (TextUtils.isEmpty(name)) {
                    // Empty parameter name. Check the next one.
                    continue;
                }
                if (value == null) {
                    value = "";
                }
                paramBuilder.append(URLEncoder.encode(name, UTF8_CHARSET));
                paramBuilder.append("=");
                paramBuilder.append(URLEncoder.encode(value, UTF8_CHARSET));
                paramBuilder.append("&");
            }
        }

        // ?
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        // Create the connection object
        URL url = null;
        String outputText = null;
        switch (method) {
        case GET:
        case DELETE:
            String fullUrlValue = urlValue;
            if (paramBuilder.length() > 0) {
                fullUrlValue += "?" + paramBuilder.toString();
            }
            url = new URL(fullUrlValue);
            connection = HttpUrlConnectionHelper.openUrlConnection(url);
            break;
        case PUT:
        case POST:
            url = new URL(urlValue);
            connection = HttpUrlConnectionHelper.openUrlConnection(url);
            connection.setDoOutput(true);

            if (paramBuilder.length() > 0 && NetworkConnection.CT_DEFALUT.equals(contentType)) { // form
                // ?
                // headerMap.put(HTTP.CONTENT_TYPE,
                // "application/x-www-form-urlencoded");
                outputText = paramBuilder.toString();
                headerMap.put(HTTP.CONTENT_TYPE, contentType);
                headerMap.put(HTTP.CONTENT_LEN, String.valueOf(outputText.getBytes().length));
            } else if (postText != null && (NetworkConnection.CT_JSON.equals(contentType)
                    || NetworkConnection.CT_XML.equals(contentType))) { // body
                // ?
                // headerMap.put(HTTP.CONTENT_TYPE, "application/json");
                // //add ?json???
                headerMap.put(HTTP.CONTENT_TYPE, contentType); // add
                // ?json???
                headerMap.put(HTTP.CONTENT_LEN, String.valueOf(postText.getBytes().length));
                outputText = postText;
                // Log.e("newtewewerew",
                // "1111application/json------------------outputText222222:::"+outputText+"-------method::"+method+"----paramBuilder.length() :"+paramBuilder.length()+"----postText:"+postText
                // );
            } else if (NetworkConnection.CT_MULTIPART.equals(contentType)) { // 
                String[] Array = urlValue.split("/");
                /*Boolean isFiles = false;
                if (Array[Array.length - 1].equals("clientRemarkPic")) {
                   isFiles = true;
                }*/
                if (null == fileByteDates || fileByteDates.size() <= 0) {
                    throw new ConnectionException("file formdata no bytes data",
                            NetworkConnection.EXCEPTION_CODE_FORMDATA_NOBYTEDATE);
                }
                headerMap.put(HTTP.CONTENT_TYPE, contentType + ";boundary=" + BOUNDARY);
                String bulidFormText = bulidFormText(parameterList);
                bos.write(bulidFormText.getBytes());
                for (int i = 0; i < fileByteDates.size(); i++) {
                    long currentTimeMillis = System.currentTimeMillis();
                    StringBuffer sb = new StringBuffer("");
                    sb.append(PREFIX).append(BOUNDARY).append(LINEND);
                    // sb.append("Content-Type:application/octet-stream" +
                    // LINEND);
                    // sb.append("Content-Disposition: form-data; name=\""+nextInt+"\"; filename=\""+nextInt+".png\"").append(LINEND);;
                    if (isMulFiles)
                        sb.append("Content-Disposition: form-data; name=\"files\";filename=\"pic"
                                + currentTimeMillis + ".png\"").append(LINEND);
                    else
                        sb.append("Content-Disposition: form-data; name=\"file\";filename=\"pic"
                                + currentTimeMillis + ".png\"").append(LINEND);
                    // sb.append("Content-Type:image/png" + LINEND);
                    sb.append("Content-Type:" + fileMimeTypes.get(i) + LINEND);
                    // sb.append("Content-Type:image/png" + LINEND);
                    sb.append(LINEND);
                    bos.write(sb.toString().getBytes());
                    bos.write(fileByteDates.get(i));
                    bos.write(LINEND.getBytes());
                }
                byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
                bos.write(end_data);
                bos.flush();
                headerMap.put(HTTP.CONTENT_LEN, bos.size() + "");
            }
            // L.e("newtewewerew",
            // "2222------------------outputText222222:::"+outputText+"-------method::"+method+"----paramBuilder.length() :"+paramBuilder.length()+"----postText:"+postText
            // );
            break;
        }

        // Set the request method
        connection.setRequestMethod(method.toString());

        // If it's an HTTPS request and the SSL Validation is disabled
        if (url.getProtocol().equals("https") && !isSslValidationEnabled) {
            HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
            httpsConnection.setSSLSocketFactory(getAllHostsValidSocketFactory());
            httpsConnection.setHostnameVerifier(getAllHostsValidVerifier());
        }

        // Add the headers
        if (!headerMap.isEmpty()) {
            for (Entry<String, String> header : headerMap.entrySet()) {
                connection.addRequestProperty(header.getKey(), header.getValue());
            }
        }

        // Set the connection and read timeout
        connection.setConnectTimeout(OPERATION_TIMEOUT);
        connection.setReadTimeout(OPERATION_TIMEOUT);
        // Set the outputStream content for POST and PUT requests
        if ((method == Method.POST || method == Method.PUT)) {
            OutputStream output = null;
            try {
                if (NetworkConnection.CT_MULTIPART.equals(contentType)) {
                    output = connection.getOutputStream();
                    output.write(bos.toByteArray());
                } else {
                    if (null != outputText) {
                        L.e("newtewewerew", method + "------------------outputText:::" + outputText);
                        output = connection.getOutputStream();
                        output.write(outputText.getBytes());
                    }
                }

            } finally {
                if (output != null) {
                    try {
                        output.close();
                    } catch (IOException e) {
                        // Already catching the first IOException so nothing
                        // to do here.
                    }
                }
            }
        }

        // Log the request
        if (L.canLog(Log.DEBUG)) {
            L.d(TAG, "Request url: " + urlValue);
            L.d(TAG, "Method: " + method.toString());

            if (parameterList != null && !parameterList.isEmpty()) {
                L.d(TAG, "Parameters:");
                for (int i = 0, size = parameterList.size(); i < size; i++) {
                    BasicNameValuePair parameter = parameterList.get(i);
                    String message = "- \"" + parameter.getName() + "\" = \"" + parameter.getValue() + "\"";
                    L.d(TAG, message);
                }
                L.d(TAG, "Parameters String: \"" + paramBuilder.toString() + "\"");
            }

            if (postText != null) {
                L.d(TAG, "Post data: " + postText);
            }

            if (headerMap != null && !headerMap.isEmpty()) {
                L.d(TAG, "Headers:");
                for (Entry<String, String> header : headerMap.entrySet()) {
                    L.d(TAG, "- " + header.getKey() + " = " + header.getValue());
                }
            }
        }

        String contentEncoding = connection.getHeaderField(HTTP.CONTENT_ENCODING);

        int responseCode = connection.getResponseCode();
        boolean isGzip = contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip");
        L.d(TAG, "Response code: " + responseCode);

        if (responseCode == HttpStatus.SC_MOVED_PERMANENTLY) {
            String redirectionUrl = connection.getHeaderField(LOCATION_HEADER);
            throw new ConnectionException("New location : " + redirectionUrl, redirectionUrl);
        }

        InputStream errorStream = connection.getErrorStream();
        if (errorStream != null) {
            String error = convertStreamToString(errorStream, isGzip);
            // L.e("responseCode:"+responseCode+" httpErrorResCodeFilte:"+httpErrorResCodeFilte+" responseCode==httpErrorResCodeFilte:"+(responseCode==httpErrorResCodeFilte));
            if (responseCode == httpErrorResCodeFilte) { // 400???...
                logResBodyAndHeader(connection, error);
                return new ConnectionResult(connection.getHeaderFields(), error, responseCode);
            } else {
                throw new ConnectionException(error, responseCode);
            }
        }

        String body = convertStreamToString(connection.getInputStream(), isGzip);

        // ?? ?
        if (null != body && body.contains("\r")) {
            body = body.replace("\r", "");
        }

        if (null != body && body.contains("\n")) {
            body = body.replace("\n", "");
        }

        logResBodyAndHeader(connection, body);

        return new ConnectionResult(connection.getHeaderFields(), body, responseCode);
    } catch (IOException e) {
        L.e(TAG, "IOException", e);
        throw new ConnectionException(e);
    } catch (KeyManagementException e) {
        L.e(TAG, "KeyManagementException", e);
        throw new ConnectionException(e);
    } catch (NoSuchAlgorithmException e) {
        L.e(TAG, "NoSuchAlgorithmException", e);
        throw new ConnectionException(e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}