Example usage for com.lowagie.text.pdf PdfPTable getDefaultCell

List of usage examples for com.lowagie.text.pdf PdfPTable getDefaultCell

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfPTable getDefaultCell.

Prototype

public PdfPCell getDefaultCell() 

Source Link

Document

Gets the default PdfPCell that will be used as reference for all the addCell methods except addCell(PdfPCell).

Usage

From source file:org.oscarehr.web.reports.ocan.NeedRatingOverTimeReportGenerator.java

License:Open Source License

public void generateReport(OutputStream os) throws Exception {
    Document d = new Document(PageSize.A4.rotate());
    d.setMargins(20, 20, 20, 20);/*from  www. j  a  va  2  s .  c  o  m*/
    PdfWriter writer = PdfWriter.getInstance(d, os);
    writer.setStrictImageSequence(true);
    d.open();

    //header
    Paragraph p = new Paragraph("Needs Over Time (Consumer and Staff)", titleFont);
    p.setAlignment(Element.ALIGN_CENTER);
    d.add(p);
    d.add(Chunk.NEWLINE);

    //purpose
    Paragraph purpose = new Paragraph();
    purpose.add(new Chunk("Purpose of Report:", boldText));
    purpose.add(new Phrase(
            "The purpose of this report is to show change over time in a specific Need Rating for an individual Consumer. It adds up the number of needs across all Domains grouped by Need Rating (e.g. Unmet Needs, Met Needs, No Needs, Unknown) for all selected OCANs that were conducted with the Consumer and displays the results in an individual need rating line graph. Each line graph that is displayed compares the Consumer and the Staff's perspective. The staff may share this report with their Consumer as well.",
            normalText));
    d.add(purpose);
    d.add(Chunk.NEWLINE);

    //report parameters
    PdfPTable table = new PdfPTable(2);
    table.setWidthPercentage(100);
    table.getDefaultCell().setBorder(0);
    table.addCell(
            makeCell(createFieldNameAndValuePhrase("Consumer Name:", getConsumerName()), Element.ALIGN_LEFT));
    table.addCell(makeCell(createFieldNameAndValuePhrase("Report Date:", dateFormatter.format(getReportDate())),
            Element.ALIGN_RIGHT));
    table.addCell(makeCell(createFieldNameAndValuePhrase("Staff Name:", getStaffName()), Element.ALIGN_LEFT));
    table.addCell("");
    d.add(table);
    d.add(Chunk.NEWLINE);

    //loop here...groups of 3
    int loopNo = 1;
    List<OcanNeedRatingOverTimeSummaryOfNeedsBean> summaryBeanList = new ArrayList<OcanNeedRatingOverTimeSummaryOfNeedsBean>();
    summaryBeanList.addAll(this.summaryOfNeedsBeanList);

    while (true) {
        if (summaryBeanList.size() == 0) {
            break;
        }
        List<OcanNeedRatingOverTimeSummaryOfNeedsBean> currentBeanList = new ArrayList<OcanNeedRatingOverTimeSummaryOfNeedsBean>();
        for (int x = 0; x < 3; x++) {
            if (summaryBeanList.size() == 0) {
                break;
            }
            currentBeanList.add(summaryBeanList.remove(0));
        }

        //summary of needs
        PdfPTable summaryOfNeedsTable = null;
        if (currentBeanList.size() == 1) {
            summaryOfNeedsTable = new PdfPTable(3);
            summaryOfNeedsTable.setWidthPercentage(100f - 52.8f);
            summaryOfNeedsTable.setWidths(new float[] { 0.26f, 0.12f, 0.12f });
        }
        if (currentBeanList.size() == 2) {
            summaryOfNeedsTable = new PdfPTable(6);
            summaryOfNeedsTable.setWidthPercentage(100f - 26.4f);
            summaryOfNeedsTable.setWidths(new float[] { 0.26f, 0.12f, 0.12f, 0.024f, 0.12f, 0.12f });
        }
        if (currentBeanList.size() == 3) {
            summaryOfNeedsTable = new PdfPTable(9);
            summaryOfNeedsTable.setWidthPercentage(100f);
            summaryOfNeedsTable
                    .setWidths(new float[] { 0.26f, 0.12f, 0.12f, 0.024f, 0.12f, 0.12f, 0.024f, 0.12f, 0.12f });
        }
        summaryOfNeedsTable.setHorizontalAlignment(Element.ALIGN_LEFT);
        summaryOfNeedsTable.setHeaderRows(3);

        addSummaryOfNeedsHeader(summaryOfNeedsTable, currentBeanList, loopNo);
        addSummaryOfNeedsRow(summaryOfNeedsTable, "Unmet Needs", "unmet", currentBeanList);
        addSummaryOfNeedsRow(summaryOfNeedsTable, "Met Needs", "met", currentBeanList);
        addSummaryOfNeedsRow(summaryOfNeedsTable, "No Needs", "no", currentBeanList);
        addSummaryOfNeedsRow(summaryOfNeedsTable, "Unknown Needs", "unknown", currentBeanList);

        d.add(summaryOfNeedsTable);
        d.add(Chunk.NEWLINE);

        if (summaryBeanList.size() == 0) {
            break;
        }
        loopNo++;
    }

    //BREAKDOWN OF SUMMARY OF NEEDS

    //loop here...groups of 3
    loopNo = 1;
    List<OcanNeedRatingOverTimeNeedBreakdownBean> breakdownBeanList = new ArrayList<OcanNeedRatingOverTimeNeedBreakdownBean>();
    breakdownBeanList.addAll(this.needBreakdownListByOCAN);
    OcanNeedRatingOverTimeNeedBreakdownBean lastBreakDownBean = null;
    while (true) {
        if (breakdownBeanList.size() == 0) {
            break;
        }
        List<OcanNeedRatingOverTimeNeedBreakdownBean> currentBeanList = new ArrayList<OcanNeedRatingOverTimeNeedBreakdownBean>();
        for (int x = 0; x < 3; x++) {
            if (breakdownBeanList.size() == 0) {
                break;
            }
            currentBeanList.add(breakdownBeanList.remove(0));
        }

        //summary of needs
        PdfPTable summaryOfNeedsTable = null;
        if (currentBeanList.size() == 1) {
            if (lastBreakDownBean == null) {
                summaryOfNeedsTable = new PdfPTable(3);
                summaryOfNeedsTable.setWidthPercentage(100f - 52.8f);
                summaryOfNeedsTable.setWidths(new float[] { 0.26f, 0.12f, 0.12f });
            } else {
                summaryOfNeedsTable = new PdfPTable(4);
                summaryOfNeedsTable.setWidthPercentage(100f - 52.8f);
                summaryOfNeedsTable.setWidths(new float[] { 0.26f - 0.024f, 0.024f, 0.12f, 0.12f });
            }
        }
        if (currentBeanList.size() == 2) {
            if (lastBreakDownBean == null) {
                summaryOfNeedsTable = new PdfPTable(6);
                summaryOfNeedsTable.setWidthPercentage(100f - 26.4f);
                summaryOfNeedsTable.setWidths(new float[] { 0.26f, 0.12f, 0.12f, 0.024f, 0.12f, 0.12f });
            } else {
                summaryOfNeedsTable = new PdfPTable(7);
                summaryOfNeedsTable.setWidthPercentage(100f - 26.4f);
                summaryOfNeedsTable
                        .setWidths(new float[] { 0.26f - 0.024f, 0.024f, 0.12f, 0.12f, 0.024f, 0.12f, 0.12f });
            }
        }
        if (currentBeanList.size() == 3) {
            if (lastBreakDownBean == null) {
                summaryOfNeedsTable = new PdfPTable(9);
                summaryOfNeedsTable.setWidthPercentage(100f);
                summaryOfNeedsTable.setWidths(
                        new float[] { 0.26f, 0.12f, 0.12f, 0.024f, 0.12f, 0.12f, 0.024f, 0.12f, 0.12f });
            } else {
                summaryOfNeedsTable = new PdfPTable(10);
                summaryOfNeedsTable.setWidthPercentage(100f);
                summaryOfNeedsTable.setWidths(new float[] { 0.26f - 0.024f, 0.024f, 0.12f, 0.12f, 0.024f, 0.12f,
                        0.12f, 0.024f, 0.12f, 0.12f });
            }
        }
        summaryOfNeedsTable.setHorizontalAlignment(Element.ALIGN_LEFT);

        addSummaryOfNeedsDomainHeader(summaryOfNeedsTable, currentBeanList, loopNo);
        for (int x = 0; x < domains.size(); x++) {
            addSummaryOfNeedsDomainRow(summaryOfNeedsTable, x, getDomains(), currentBeanList,
                    lastBreakDownBean);
        }

        d.add(summaryOfNeedsTable);
        d.add(Chunk.NEWLINE);

        if (breakdownBeanList.size() == 0) {
            break;
        }
        if (currentBeanList.size() == 3) {
            lastBreakDownBean = currentBeanList.get(2);
        }
        loopNo++;
    }

    JFreeChart chart = generateNeedsOverTimeChart();
    BufferedImage image = chart.createBufferedImage((int) PageSize.A4.rotate().getWidth() - 40, 350);
    Image image2 = Image.getInstance(image, null);
    d.add(image2);

    d.close();
}

From source file:org.oscarehr.web.reports.ocan.SummaryOfActionsAndCommentsReportGenerator.java

License:Open Source License

public void generateReport(OutputStream os) throws Exception {
    Document d = new Document(PageSize.A4.rotate());
    d.setMargins(20, 20, 20, 20);//from   w ww. j a  v a 2s . com
    PdfWriter writer = PdfWriter.getInstance(d, os);
    writer.setStrictImageSequence(true);
    d.open();

    //header
    Paragraph p = new Paragraph("Summary of Actions and Comments", titleFont);
    p.setAlignment(Element.ALIGN_CENTER);
    d.add(p);
    d.add(Chunk.NEWLINE);

    //purpose
    Paragraph purpose = new Paragraph();
    purpose.add(new Chunk("Purpose of Report:", boldText));
    purpose.add(new Phrase(
            "This report displays a summary of Actions and Comments (both for the Consumer and the Staff) that were recorded in the selected OCANs for an individual Consumer. The report lists all the Actions and Comments associated to OCANs and Domains that were chosen by the Staff to be displayed. The Actions also list who is responsible for the Action and the Review Date for the Action. The Domains are categorized by need rating within within the current OCAN as well as displaying the need ratings from the previous OCANs. In the case of different need ratings by the Consumer and the Mental Health Worker, the higher need rating determines the category. The need ratings from highest to lowest are Unmet Needs, Met Needs, No Needs, and Unknown. The need rating given by the Consumer and the Staff are also displayed next to the Comments for each OCAN. This information can be passed along to other organizations if requested.",
            normalText));
    d.add(purpose);
    d.add(Chunk.NEWLINE);

    //report parameters
    PdfPTable table = new PdfPTable(2);
    table.setWidthPercentage(100);
    table.getDefaultCell().setBorder(0);
    table.addCell(
            makeCell(createFieldNameAndValuePhrase("Consumer Name:", getConsumerName()), Element.ALIGN_LEFT));
    table.addCell(makeCell(createFieldNameAndValuePhrase("Report Date:", dateFormatter.format(getReportDate())),
            Element.ALIGN_RIGHT));
    table.addCell(makeCell(createFieldNameAndValuePhrase("Staff Name:", getStaffName()), Element.ALIGN_LEFT));
    table.addCell("");
    d.add(table);
    d.add(Chunk.NEWLINE);

    if (reportBean == null) {
        d.close();
        return;
    }

    List<SummaryOfActionsAndCommentsDomainBean> unMetCategory = reportBean.getUnmetNeeds();
    List<SummaryOfActionsAndCommentsDomainBean> metCategory = reportBean.getMetNeeds();
    List<SummaryOfActionsAndCommentsDomainBean> noCategory = reportBean.getNoNeeds();
    List<SummaryOfActionsAndCommentsDomainBean> unknownCategory = reportBean.getUnknown();

    PdfPTable unmetTable = null;
    if (unMetCategory.size() > 0) {
        unmetTable = createNeedHeader("Unmet Needs");
    }
    for (SummaryOfActionsAndCommentsDomainBean domain : unMetCategory) {
        if (domain.getOcanBeans().size() > 0) {
            createDomainHeader(unmetTable, domain.getDomainName());
            for (SummaryOfActionsAndCommentsOCANBean ocanBean : domain.getOcanBeans()) {
                createOcanEntry(unmetTable, ocanBean);
            }
        }
    }
    if (unmetTable != null) {
        d.add(unmetTable);
        d.add(Chunk.NEWLINE);
    }

    PdfPTable metTable = null;
    if (metCategory.size() > 0) {
        metTable = createNeedHeader("Met Needs");
    }
    for (SummaryOfActionsAndCommentsDomainBean domain : metCategory) {
        if (domain.getOcanBeans().size() > 0) {
            createDomainHeader(metTable, domain.getDomainName());
            for (SummaryOfActionsAndCommentsOCANBean ocanBean : domain.getOcanBeans()) {
                createOcanEntry(metTable, ocanBean);
            }
        }
    }
    if (metTable != null) {
        d.add(metTable);
        d.add(Chunk.NEWLINE);
    }

    PdfPTable noTable = null;
    if (noCategory.size() > 0) {
        noTable = createNeedHeader("No Needs");
    }
    for (SummaryOfActionsAndCommentsDomainBean domain : noCategory) {
        if (domain.getOcanBeans().size() > 0) {
            createDomainHeader(noTable, domain.getDomainName());
            for (SummaryOfActionsAndCommentsOCANBean ocanBean : domain.getOcanBeans()) {
                createOcanEntry(noTable, ocanBean);
            }
        }
    }
    if (noTable != null) {
        d.add(noTable);
        d.add(Chunk.NEWLINE);
    }

    PdfPTable unknownTable = null;
    if (unknownCategory.size() > 0) {
        unknownTable = createNeedHeader("Unknown");
    }
    for (SummaryOfActionsAndCommentsDomainBean domain : unknownCategory) {
        if (domain.getOcanBeans().size() > 0) {
            createDomainHeader(unknownTable, domain.getDomainName());
            for (SummaryOfActionsAndCommentsOCANBean ocanBean : domain.getOcanBeans()) {
                createOcanEntry(unknownTable, ocanBean);
            }
        }
    }
    if (unknownTable != null) {
        d.add(unknownTable);
    }

    d.close();
}

From source file:org.posterita.businesslogic.administration.CustomerManager.java

License:Open Source License

public static String fidelityCard(Properties ctx, ArrayList<CustomerBean> customerList)
        throws OperationException {
    String reportName = RandomStringGenerator.randomstring() + ".pdf";
    String reportPath = ReportManager.getReportPath(reportName);

    boolean shouldPrintCard = false;

    for (CustomerBean b : customerList) {
        if (b.getIsActive()) {
            shouldPrintCard = true;/*from   ww w  .ja  va2s . com*/
            break;
        }
    }

    if (!shouldPrintCard) {
        throw new NoCustomerFoundException("Cannot print fidelity card. Cause no active customers were found.");
    }

    Document document = new Document(PageSize.A4, 3, 3, 2, 4);//l,r,t,b

    try {
        //          step 2:
        // we create a writer that listens to the document
        // and directs a PDF-stream to a file
        PdfWriter.getInstance(document, new FileOutputStream(reportPath));

        // step 3: we open the document
        document.open();

        PdfPTable main = new PdfPTable(2);
        main.setWidthPercentage(71.0f);
        main.getDefaultCell().setBorderColor(Color.gray);

        PdfPCell cell = new PdfPCell();
        cell.setMinimumHeight(150.0f);

        Font smallFont = FontFactory.getFont(FontFactory.HELVETICA, 7, Font.BOLD);
        //Font spaceFont = FontFactory.getFont(FontFactory.HELVETICA,6,Font.BOLD);
        //Font spaceFont2 = FontFactory.getFont(FontFactory.HELVETICA,15,Font.BOLD);

        //ResourceBundle rb = ResourceBundle.getBundle("MessageResources");

        for (CustomerBean bean : customerList) {
            if (bean.getIsActive()) {
                String name = bean.getPartnerName();
                String name1 = "";
                String add2 = "";
                String add1 = "";
                String city = "";

                if (bean.getAddress1() != null)
                    add1 = bean.getAddress1();

                if (bean.getAddress2() != null)
                    add2 = bean.getAddress2();

                if (bean.getCity() != null)
                    city = bean.getCity();

                String Address = "   " + add1;
                String Add2 = " " + add2;
                String Add3 = "   " + city;

                String BackPriv1Path = PathInfo.PROJECT_HOME + "/images/BackPriv1.jpg";
                String backPriv2Path = PathInfo.PROJECT_HOME + "/images/backPriv2.jpg";
                String frontImgPath = PathInfo.PROJECT_HOME + "/images/pc.png";

                float WIDTH = 205;
                float HEIGHT = 135;

                Image Back1 = Image.getInstance(BackPriv1Path);
                Back1.scaleAbsolute(WIDTH - 40, HEIGHT / 3);
                Image Back2 = Image.getInstance(backPriv2Path);
                Back2.scaleAbsolute(WIDTH, HEIGHT / 3);
                Image frontImg = Image.getInstance(frontImgPath);
                frontImg.scaleAbsolute(WIDTH, HEIGHT);

                if (bean.getSurname() != null && bean.getSurname().trim().length() > 0)
                    name1 = "   " + name + " " + name1 + bean.getSurname();

                byte[] barcode = BarcodeManager.getBarcodeAsByte(bean.getBpartnerId().toString());
                Image barcodeImg = Image.getInstance(barcode);
                barcodeImg.setRotation(1.57f);
                barcodeImg.scaleAbsolute(HEIGHT - 55f, WIDTH / 5);

                //document.add(barcodeImg);
                PdfPTable card = new PdfPTable(2);
                card.getDefaultCell().setBorderWidth(0.0f);

                PdfPCell c = null;
                card.setWidthPercentage(50.0f);

                PdfPTable t = new PdfPTable(1);
                PdfPTable nametable = new PdfPTable(1);

                c = new PdfPCell(Back1);
                c.setBorderWidth(0.0f);
                nametable.addCell(c);

                c = new PdfPCell(new Phrase(name1, smallFont));
                c.setHorizontalAlignment(Element.ALIGN_CENTER);
                c.setVerticalAlignment(Element.ALIGN_CENTER);
                c.setBorderWidth(0.0f);
                nametable.addCell(c);

                c = new PdfPCell(new Phrase(Address, smallFont));
                c.setHorizontalAlignment(Element.ALIGN_CENTER);
                c.setVerticalAlignment(Element.ALIGN_CENTER);
                c.setBorderWidth(0.0f);
                //c.setColspan(2);
                nametable.addCell(c);

                c = new PdfPCell(new Phrase(Add2, smallFont));
                c.setHorizontalAlignment(Element.ALIGN_CENTER);
                c.setVerticalAlignment(Element.ALIGN_CENTER);
                c.setBorderWidth(0.0f);
                //c.setColspan(2);
                nametable.addCell(c);

                c = new PdfPCell(new Phrase(Add3, smallFont));
                c.setHorizontalAlignment(Element.ALIGN_CENTER);
                c.setVerticalAlignment(Element.ALIGN_CENTER);
                c.setBorderWidth(0.0f);
                //c.setColspan(2);
                nametable.addCell(c);

                //nametable.getDefaultCell();
                nametable.getDefaultCell().setBorderWidth(0.0f);
                nametable.setHorizontalAlignment(Element.ALIGN_CENTER);
                card.addCell(nametable);

                c = new PdfPCell(barcodeImg);
                c.setBorderWidth(0.0f);
                //c.setColspan(2);
                c.setHorizontalAlignment(Element.ALIGN_RIGHT);
                c.setVerticalAlignment(Element.ALIGN_MIDDLE);
                c.setPadding(5.0f);
                card.addCell(c);

                c = new PdfPCell(Back2);
                c.setBorderWidth(0.0f);
                c.setColspan(2);
                card.addCell(c);

                c = new PdfPCell(new Phrase(name1, smallFont));
                c.setBorderWidth(0.0f);
                t.addCell(c);

                c = new PdfPCell(new Phrase(Address, smallFont));
                c.setBorderWidth(0.0f);
                t.addCell(c);

                c = new PdfPCell(new Phrase(Add3, smallFont));
                c.setBorderWidth(0.0f);
                t.addCell(c);

                PdfPTable card1 = new PdfPTable(1);
                card.getDefaultCell().setBorderWidth(0.0f);

                PdfPCell c1 = null;
                card.setWidthPercentage(50.0f);

                c1 = new PdfPCell(frontImg);
                c1.setBorderWidth(0.0f);
                card1.addCell(c1);

                main.addCell(card);
                main.addCell(card1);
            }

        }
        document.add(main);

    }
    // TODO handle the following exception neatly
    catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }

    // step 5: we close the document
    document.close();
    return reportName;
}

From source file:org.posterita.businesslogic.performanceanalysis.POSReportManager.java

License:Open Source License

public static String getCompleteOrderPDFReport(Properties ctx, int orderId, String trxName)
        throws OperationException {
    String docStatus = null;// w w w.ja  v a  2 s .com
    String dateOrdered = null;
    String orderType = null;
    String orgName = null;
    String orgAddress = null;
    String salesRep = null;
    String paymentBy = null;
    String customerName = null;
    String customerAddress = null;
    String documentNo = null;
    String currency = "Rs ";
    NumberFormat formatter = new DecimalFormat("###,###,##0.00");

    currency = POSTerminalManager.getDefaultSalesCurrency(ctx).getCurSymbol() + " ";
    MOrder order = new MOrder(ctx, orderId, trxName);

    // getting payment info
    int[] invoiceIds = MInvoice.getAllIDs(MInvoice.Table_Name,
            "AD_CLIENT_ID=" + Env.getAD_Client_ID(ctx) + " and C_ORDER_ID=" + order.get_ID(), null);
    double paymentByCash = 0.0;
    double paymentByCard = 0.0;
    double paymentByCheque = 0.0;

    MInvoice invoice = null;
    String paymentRule = null;
    boolean isMixed = false;

    for (int i = 0; i < invoiceIds.length; i++) {
        invoice = new MInvoice(ctx, invoiceIds[i], trxName);

        if (i == 0) {
            paymentRule = invoice.getPaymentRule();
        } else {
            if (!paymentRule.equalsIgnoreCase(invoice.getPaymentRule())) {
                isMixed = true;
            }
        }

        if (invoice.getPaymentRule().equals(MOrder.PAYMENTRULE_Cash)) {
            paymentByCash += invoice.getGrandTotal().doubleValue();
            paymentBy = Constants.PAYMENT_RULE_CASH;
        }

        if (invoice.getPaymentRule().equals(MOrder.PAYMENTRULE_CreditCard)) {
            paymentByCard += invoice.getGrandTotal().doubleValue();
            paymentBy = Constants.PAYMENT_RULE_CARD;
        }

        if (invoice.getPaymentRule().equals(MOrder.PAYMENTRULE_DirectDebit)) {
            paymentByCard += invoice.getGrandTotal().doubleValue();
            paymentBy = Constants.PAYMENT_RULE_CARD;
        }

        if (invoice.getPaymentRule().equals(MOrder.PAYMENTRULE_Check)) {
            paymentByCheque += invoice.getGrandTotal().doubleValue();
            paymentBy = Constants.PAYMENT_RULE_CHEQUE;
        }

    } // for

    if (isMixed) {
        paymentBy = "Mixed (Cash:" + formatter.format(paymentByCash) + " Card:"
                + formatter.format(paymentByCard) + " Cheque:" + formatter.format(paymentByCheque) + ")";
    }

    // getting orgInfo
    MOrg org = new MOrg(ctx, order.getAD_Org_ID(), trxName);
    int location_id = org.getInfo().getC_Location_ID();
    MLocation location = new MLocation(ctx, location_id, trxName);

    orgName = org.getName();

    String address1 = (location.getAddress1() == null) ? " " : location.getAddress1();
    String address2 = (location.getAddress2() == null) ? " " : location.getAddress2();
    orgAddress = (address1 + " " + address2).trim();

    // getting order type
    orderType = order.getOrderType();

    // getting orderInfo
    docStatus = order.getDocStatusName();
    documentNo = order.getDocumentNo();

    Date d = new Date(order.getCreated().getTime());
    SimpleDateFormat s = new SimpleDateFormat(TimestampConvertor.DEFAULT_DATE_PATTERN1);
    dateOrdered = s.format(d);

    // getting salesrep
    int saleRep_id = order.getSalesRep_ID();
    MUser user = new MUser(ctx, saleRep_id, trxName);
    salesRep = user.getName();

    // getting customer info
    int bpartner_id = order.getBill_BPartner_ID();
    BPartnerBean bean = BPartnerManager.getBpartner(ctx, bpartner_id, trxName);

    String name1 = (bean.getPartnerName() == null) ? " " : bean.getPartnerName();
    String name2 = (bean.getName2() == null) ? " " : bean.getName2();
    customerName = (name1 + " " + name2).trim();

    address1 = (bean.getAddress1() == null) ? " " : bean.getAddress1();
    address2 = (bean.getAddress2() == null) ? " " : bean.getAddress2();
    customerAddress = (address1 + " " + address2).trim();

    ArrayList<WebOrderLineBean> orderLineList = POSManager.populateOrderLines(ctx, order);

    // ----------------------------------- generating pdf
    // --------------------------------------
    String reportName = RandomStringGenerator.randomstring() + ".pdf";
    String reportPath = ReportManager.getReportPath(reportName);

    Font titleFont = new Font(Font.TIMES_ROMAN, 18, Font.BOLD);
    Font subtitleFont = new Font(Font.TIMES_ROMAN, 14, Font.BOLD);

    Font headerFont = new Font(Font.TIMES_ROMAN, 11, Font.BOLD);
    Font simpleFont = new Font(Font.TIMES_ROMAN, 10);

    float cellBorderWidth = 0.0f;

    // step 1: creation of a document-object
    Document document = new Document(PageSize.A4, 30, 30, 20, 40);// l,r,t,b
    // document.getPageSize().set;

    System.out.println(document.leftMargin());

    try {
        // step 2:
        // we create a writer that listens to the document
        // and directs a PDF-stream to a file
        PdfWriter.getInstance(document, new FileOutputStream(reportPath));

        // step 3: we open the document
        document.open();
        // step 4: we add a paragraph to the document

        Image logo = null;

        String imageURI = PathInfo.PROJECT_HOME + "images/logo.gif";
        // "images/pos/openBLUE_POS_Logo.gif";

        try {
            byte logoData[] = OrganisationManager.getLogo(ctx, null);
            logo = Image.getInstance(logoData);
        } catch (LogoException ex) {
            logo = Image.getInstance(imageURI);
        }

        logo.setAbsolutePosition(document.left(), document.top() - logo.getHeight());
        document.add(logo);

        PdfPTable table = new PdfPTable(2);
        PdfPCell cell = null;

        //
        table.getDefaultCell().setPadding(5.0f);
        table.setWidthPercentage(100.0f);

        // header cell
        Paragraph title = new Paragraph();
        title.add(new Chunk(orgName, subtitleFont));
        title.add(new Chunk("\n"));
        title.add(new Chunk(orgAddress, subtitleFont));

        // cell = new PdfPCell(new Paragraph(new
        // Chunk("Title1",titleFont)));
        cell = new PdfPCell(title);

        cell.setColspan(2);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
        cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
        cell.setFixedHeight(logo.getHeight());
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        cell = new PdfPCell(new Paragraph(""));
        cell.setBorderWidth(cellBorderWidth);
        cell.setFixedHeight(10);
        cell.setColspan(2);
        table.addCell(cell);

        // doc type
        cell = new PdfPCell(new Paragraph(new Chunk(orderType, titleFont)));

        cell.setColspan(2);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // spacing
        cell = new PdfPCell(new Paragraph(""));
        cell.setBorderWidth(cellBorderWidth);
        cell.setFixedHeight(10);
        cell.setColspan(2);
        table.addCell(cell);

        // row 1
        cell = new PdfPCell(new Paragraph(new Chunk(customerName, headerFont)));
        cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        cell = new PdfPCell(new Paragraph(new Chunk("Sales Rep: " + salesRep, headerFont)));
        cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // row 2
        cell = new PdfPCell(new Paragraph(new Chunk(customerAddress, headerFont)));
        cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // spacing
        cell = new PdfPCell(new Paragraph(""));
        cell.setBorderWidth(cellBorderWidth);
        cell.setFixedHeight(10);
        cell.setColspan(2);
        table.addCell(cell);

        // row 3
        cell = new PdfPCell(new Paragraph(new Chunk("Ref No: " + documentNo, headerFont)));
        cell.setColspan(2);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // row 4
        cell = new PdfPCell(new Paragraph(new Chunk("Doc Status: " + docStatus, headerFont)));
        cell.setColspan(2);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // row 5
        cell = new PdfPCell(new Paragraph(new Chunk("Payment By: " + paymentBy, headerFont)));
        cell.setColspan(2);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // row 6
        cell = new PdfPCell(new Paragraph(new Chunk("Date: " + dateOrdered, headerFont)));
        cell.setColspan(2);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // spacing
        cell = new PdfPCell(new Paragraph(""));
        cell.setColspan(2);
        cell.setFixedHeight(10);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // spacing
        cell = new PdfPCell(new Paragraph(""));
        cell.setColspan(2);
        cell.setFixedHeight(10);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // ------------------------------------------------------
        cell = new PdfPCell();
        cell.setColspan(2);
        cell.setBorderWidth(cellBorderWidth);

        PdfPTable t = new PdfPTable(6);
        t.getDefaultCell().setPadding(3.0f);
        t.setWidthPercentage(100.0f);

        int[] widths = { 1, 4, 1, 2, 2, 2 };
        t.setWidths(widths);

        // setting headers
        t.addCell(new Paragraph(new Chunk("SerNo", headerFont)));
        t.addCell(new Paragraph(new Chunk("Name", headerFont)));
        t.addCell(new Paragraph(new Chunk("Qty", headerFont)));
        t.addCell(new Paragraph(new Chunk("Price", headerFont)));
        t.addCell(new Paragraph(new Chunk("VAT", headerFont)));
        t.addCell(new Paragraph(new Chunk("Total", headerFont)));

        // setting table data
        // --------------------------------writing table
        // data------------------------------
        int serNo = 0;
        int totalQty = 0;
        double totalAmt = 0.0;
        double totalTaxAmt = 0.0;
        double grandTotal = 0.0;

        BigDecimal qty = null;
        BigDecimal lineAmt = null;
        BigDecimal taxAmt = null;
        BigDecimal lineTotalAmt = null;

        for (WebOrderLineBean orderlineBean : orderLineList) {
            serNo++;
            qty = orderlineBean.getQtyOrdered();
            lineAmt = orderlineBean.getLineNetAmt();
            taxAmt = orderlineBean.getTaxAmt();
            lineTotalAmt = orderlineBean.getLineTotalAmt();

            totalQty += qty.intValue();
            totalAmt += lineAmt.doubleValue();
            totalTaxAmt += taxAmt.doubleValue();
            grandTotal += lineTotalAmt.doubleValue();

            t.addCell(new Paragraph(new Chunk(serNo + "", simpleFont)));
            t.addCell(new Paragraph(new Chunk(orderlineBean.getProductName(), simpleFont)));
            t.addCell(new Paragraph(new Chunk(qty.intValue() + "", simpleFont)));
            t.addCell(new Paragraph(new Chunk(formatter.format(lineAmt.doubleValue()), simpleFont)));
            t.addCell(new Paragraph(new Chunk(formatter.format(taxAmt.doubleValue()), simpleFont)));
            t.addCell(new Paragraph(new Chunk(formatter.format(lineTotalAmt.doubleValue()), simpleFont)));
        }
        // -----------------------------------------------------------------------------------

        // setting table footer
        t.getDefaultCell().setBackgroundColor(new Color(240, 240, 240));

        PdfPCell c = new PdfPCell(new Paragraph(new Chunk("ORDER TOTAL", headerFont)));
        c.setColspan(2);
        c.setBackgroundColor(new Color(240, 240, 240));
        t.addCell(c);

        t.addCell(new Paragraph(new Chunk(totalQty + "", simpleFont)));
        t.addCell(new Paragraph(new Chunk(currency + formatter.format(totalAmt), simpleFont)));
        t.addCell(new Paragraph(new Chunk(currency + formatter.format(totalTaxAmt), simpleFont)));
        t.addCell(new Paragraph(new Chunk(currency + formatter.format(grandTotal), simpleFont)));

        t.setSplitRows(true);
        cell.addElement(t);
        // ------------------------------------------------------

        // table.addCell(cell);
        table.setSplitRows(true);

        document.add(table);
        document.add(t);

    } catch (Exception e) {
        throw new OperationException(e);
    }

    // step 5: we close the document
    document.close();

    return reportName;
}

From source file:org.posterita.businesslogic.performanceanalysis.POSReportManager.java

License:Open Source License

public static String getShipmentPDFReport(Properties ctx, int minoutId, String trxName)
        throws OperationException {
    String docStatus = null;/*  ww w.  j  a  v  a  2  s .co  m*/
    String dateOrdered = null;
    String docType = null;
    String orgName = null;
    String orgAddress = null;
    String salesRep = null;
    String phone = "      ";
    String fax = "       ";

    String customerName = null;
    String customerAddress = null;
    String documentNo = null;

    MInOut minout = MinOutManager.loadMInOut(ctx, minoutId, trxName);

    // getting orgInfo
    MOrg org = new MOrg(ctx, minout.getAD_Org_ID(), trxName);
    int location_id = org.getInfo().getC_Location_ID();
    MLocation location = new MLocation(ctx, location_id, trxName);
    MBPartner orgPartner = new MBPartner(ctx, org.getLinkedC_BPartner_ID(trxName), trxName);
    MBPartnerLocation meLocation[] = MBPartnerLocation.getForBPartner(ctx, orgPartner.get_ID());

    if (meLocation.length != 1)
        throw new OperationException("Should have only 1 location for organisation business partner!!");

    MBPartnerLocation orgLocation = meLocation[0];

    if (orgLocation.getPhone() != null)
        phone = orgLocation.getPhone();

    if (orgLocation.getFax() != null)
        fax = orgLocation.getFax();
    ;

    orgName = org.getName();

    String address1 = (location.getAddress1() == null) ? " " : location.getAddress1();
    String address2 = (location.getAddress2() == null) ? " " : location.getAddress2();
    orgAddress = (address1 + " " + address2).trim();

    // getting order type
    MDocType doctype = MDocType.get(ctx, minout.getC_DocType_ID());
    docType = doctype.getName();

    // getting orderInfo
    docStatus = minout.getDocStatusName();
    documentNo = minout.getDocumentNo();

    Date d = new Date(minout.getCreated().getTime());
    SimpleDateFormat s = new SimpleDateFormat(TimestampConvertor.DEFAULT_DATE_PATTERN1);
    dateOrdered = s.format(d);

    // getting salesrep
    int saleRep_id = minout.getSalesRep_ID();
    MUser user = new MUser(ctx, saleRep_id, trxName);
    salesRep = user.getName();

    // getting customer info
    int bpartner_id = minout.getC_BPartner_ID();
    BPartnerBean bean = BPartnerManager.getBpartner(ctx, bpartner_id, trxName);

    String name1 = (bean.getPartnerName() == null) ? " " : bean.getPartnerName();
    String name2 = (bean.getName2() == null) ? " " : bean.getName2();
    customerName = (name1 + " " + name2).trim();

    address1 = (bean.getAddress1() == null) ? " " : bean.getAddress1();
    address2 = (bean.getAddress2() == null) ? " " : bean.getAddress2();
    customerAddress = (address1 + " " + address2).trim();

    ArrayList<WebMinOutLineBean> orderLineList = MinOutManager.getWebMinOutLines(ctx, minout);

    // ----------------------------------- generating pdf
    // --------------------------------------
    String reportName = RandomStringGenerator.randomstring() + ".pdf";
    String reportPath = ReportManager.getReportPath(reportName);

    Font titleFont = new Font(Font.TIMES_ROMAN, 18, Font.BOLD);
    Font subtitleFont = new Font(Font.TIMES_ROMAN, 14, Font.BOLD);

    Font headerFont = new Font(Font.TIMES_ROMAN, 11, Font.BOLD);
    Font simpleFont = new Font(Font.TIMES_ROMAN, 10);

    float cellBorderWidth = 0.0f;

    // step 1: creation of a document-object
    Document document = new Document(PageSize.A4, 30, 30, 20, 40);// l,r,t,b
    // document.getPageSize().set;

    System.out.println(document.leftMargin());

    try {
        // step 2:
        // we create a writer that listens to the document
        // and directs a PDF-stream to a file
        PdfWriter.getInstance(document, new FileOutputStream(reportPath));

        // step 3: we open the document
        document.open();
        // step 4: we add a paragraph to the document

        Image logo = null;

        // TODO: make this part dynamic <------------------------------
        // IMPORTANT !!!!!!!!!!!!!!!!!!!!!!!!!!!
        String imageURI = PathInfo.PROJECT_HOME + "images/pos/openBLUE_POS_Logo.gif";
        logo = Image.getInstance(imageURI);

        // MAttachment attachment = new
        // MAttachment(ctx,MOrg.Table_ID,org.getID(),null);
        // logo = Image.getInstance(attachment.getEntries()[0].getData());

        try {
            byte logoData[] = OrganisationManager.getLogo(ctx, null);
            logo = Image.getInstance(logoData);
        } catch (LogoException ex) {
            logo = Image.getInstance(imageURI);
        }

        logo.setAbsolutePosition(document.left(), document.top() - logo.getHeight());
        document.add(logo);

        PdfPTable table = new PdfPTable(2);
        PdfPCell cell = null;

        //
        table.getDefaultCell().setPadding(5.0f);
        table.setWidthPercentage(100.0f);

        // header cell
        Paragraph title = new Paragraph();
        title.add(new Chunk(orgName, subtitleFont));
        title.add(new Chunk("\n"));
        title.add(new Chunk(orgAddress, subtitleFont));
        title.add(new Chunk("\n"));
        title.add(new Chunk("Phone: " + phone, subtitleFont));
        title.add(new Chunk("\n"));
        title.add(new Chunk("Fax: " + fax, subtitleFont));

        // cell = new PdfPCell(new Paragraph(new
        // Chunk("Title1",titleFont)));
        cell = new PdfPCell(title);

        cell.setColspan(2);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
        cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
        cell.setFixedHeight(logo.getHeight());
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        cell = new PdfPCell(new Paragraph(""));
        cell.setBorderWidth(cellBorderWidth);
        cell.setFixedHeight(10);
        cell.setColspan(2);
        table.addCell(cell);

        // doc type
        cell = new PdfPCell(new Paragraph(new Chunk(docType, titleFont)));

        cell.setColspan(2);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // spacing
        cell = new PdfPCell(new Paragraph(""));
        cell.setBorderWidth(cellBorderWidth);
        cell.setFixedHeight(10);
        cell.setColspan(2);
        table.addCell(cell);

        // row 1
        cell = new PdfPCell(new Paragraph(new Chunk(customerName, headerFont)));
        cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        cell = new PdfPCell(new Paragraph(new Chunk("Sales Rep: " + salesRep, headerFont)));
        cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // row 2
        cell = new PdfPCell(new Paragraph(new Chunk(customerAddress, headerFont)));
        cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // spacing
        cell = new PdfPCell(new Paragraph(""));
        cell.setBorderWidth(cellBorderWidth);
        cell.setFixedHeight(10);
        cell.setColspan(2);
        table.addCell(cell);

        // row 3
        cell = new PdfPCell(new Paragraph(new Chunk("No: " + documentNo, headerFont)));
        cell.setColspan(2);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // row 4
        cell = new PdfPCell(new Paragraph(new Chunk("Doc Status: " + docStatus, headerFont)));
        cell.setColspan(2);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        /*
         * //row 5 cell = new PdfPCell(new Paragraph(new Chunk("Payment By:
         * "+paymentBy,headerFont))); cell.setColspan(2);
         * cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
         * cell.setBorderWidth(cellBorderWidth); table.addCell(cell);
         */

        // row 6
        cell = new PdfPCell(new Paragraph(new Chunk("Date: " + dateOrdered, headerFont)));
        cell.setColspan(2);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // spacing
        cell = new PdfPCell(new Paragraph(""));
        cell.setColspan(2);
        cell.setFixedHeight(10);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // spacing
        cell = new PdfPCell(new Paragraph(""));
        cell.setColspan(2);
        cell.setFixedHeight(10);
        cell.setBorderWidth(cellBorderWidth);
        table.addCell(cell);

        // ------------------------------------------------------
        cell = new PdfPCell();
        cell.setColspan(2);
        cell.setBorderWidth(cellBorderWidth);

        PdfPTable t = new PdfPTable(3);
        t.getDefaultCell().setPadding(3.0f);
        t.setWidthPercentage(100.0f);

        int[] widths = { 1, 10, 1 };
        t.setWidths(widths);

        // setting headers
        t.addCell(new Paragraph(new Chunk("SerNo", headerFont)));
        t.addCell(new Paragraph(new Chunk("Name", headerFont)));
        t.addCell(new Paragraph(new Chunk("Qty", headerFont)));

        // setting table data
        // --------------------------------writing table
        // data------------------------------
        int serNo = 0;

        BigDecimal qty = null;

        for (WebMinOutLineBean orderlineBean : orderLineList) {
            serNo++;
            qty = orderlineBean.getQtyOrdered();

            t.addCell(new Paragraph(new Chunk(serNo + "", simpleFont)));
            t.addCell(new Paragraph(new Chunk(orderlineBean.getProductName(), simpleFont)));
            t.addCell(new Paragraph(new Chunk(qty.intValue() + "", simpleFont)));
        }
        // -----------------------------------------------------------------------------------

        // table.addCell(cell);
        table.setSplitRows(true);

        document.add(table);
        document.add(t);

    } catch (Exception e) {
        throw new OperationException(e);
    }

    // step 5: we close the document
    document.close();

    return reportName;
}

From source file:org.posterita.businesslogic.performanceanalysis.POSReportManager.java

License:Open Source License

public static String endOfTheDayPDF(Properties ctx, CloseTillBean bean) throws OperationException {
    String reportName = RandomStringGenerator.randomstring() + ".pdf";
    String reportPath = ReportManager.getReportPath(reportName);

    double beginningBalance = (bean.getBeginningBalance() == null ? 0
            : bean.getBeginningBalance().doubleValue());
    double statementDifference = (bean.getNetCashTrx() == null ? 0 : bean.getNetCashTrx().doubleValue());
    double transferAmount = (bean.getBalanceEntered() == null ? 0 : bean.getBalanceEntered().doubleValue());
    double differenceAmount = (bean.getDifference() == null ? 0 : bean.getDifference().doubleValue());
    double endingBalance = (bean.getEndingBalance() == null ? 0 : bean.getEndingBalance().doubleValue());
    double tillCashTotal = (bean.getCashTotal() == null ? 0 : bean.getCashTotal().doubleValue());
    double cashBeanCardTotal = (bean.getCardTotal() == null ? 0 : bean.getCardTotal().doubleValue());
    double tillCardTotal = (bean.getCardTotal() == null ? 0 : bean.getCardTotal().doubleValue());
    double cardDifference = (bean.getCardDifference() == null ? 0 : bean.getCardDifference().doubleValue());
    double cashBeanChequeTotal = (bean.getChequeTotal() == null ? 0 : bean.getChequeTotal().doubleValue());
    double tillChequeTotal = (bean.getChequeTotal() == null ? 0 : bean.getChequeTotal().doubleValue());
    double chequeDifference = (bean.getChequeDifference() == null ? 0
            : bean.getChequeDifference().doubleValue());
    double grandTotal = (bean.getGrandTotal() == null ? 0 : bean.getGrandTotal().doubleValue());

    Font titleFont = new Font(Font.TIMES_ROMAN, 8, Font.BOLD);
    Font subtitleFont = new Font(Font.TIMES_ROMAN, 8, Font.BOLD);

    // Font headerFont = new Font(Font.TIMES_ROMAN, 8,Font.BOLD);
    Font simpleFont = new Font(Font.TIMES_ROMAN, 8);

    final float NO_BORDER = 0.0f;
    // final float THIN_BORDER = 1.0f;

    String currency = "Rs ";
    NumberFormat formatter = new DecimalFormat("###,###,##0.00");
    PdfPCell cell = null;/*from ww  w. j  av a 2s.c  o  m*/

    // step 1: creation of a document-object
    Document document = new Document(PageSize.A7, 3, 3, 2, 4);// l,r,t,b
    // document.getPageSize().set;

    System.out.println(document.leftMargin());

    try {
        currency = POSTerminalManager.getDefaultSalesCurrency(ctx).getCurSymbol();
        PdfWriter.getInstance(document, new FileOutputStream(reportPath));

        document.open();

        PdfPTable layoutTbl = new PdfPTable(1);
        layoutTbl.getDefaultCell().setBorderWidth(NO_BORDER);
        layoutTbl.getDefaultCell().setPadding(2.0f);

        SimpleDateFormat sdf = new SimpleDateFormat(TimestampConvertor.DEFAULT_DATE_PATTERN1);
        Date today = new Date(System.currentTimeMillis());

        // 1.add title
        Paragraph title = new Paragraph(new Chunk("End of the Day Report", titleFont));
        title.setAlignment(Paragraph.ALIGN_CENTER);
        cell = new PdfPCell(title);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setBorderWidth(NO_BORDER);
        layoutTbl.addCell(cell);

        Paragraph subTitle = new Paragraph(new Chunk(sdf.format(today), subtitleFont));
        subTitle.setAlignment(Paragraph.ALIGN_CENTER);
        cell = new PdfPCell(subTitle);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setBorderWidth(NO_BORDER);
        layoutTbl.addCell(cell);

        // spacing
        cell = new PdfPCell(new Paragraph(""));
        cell.setFixedHeight(10);
        cell.setBorderWidth(NO_BORDER);
        layoutTbl.addCell(cell);

        // display report data
        PdfPTable table = new PdfPTable(2);
        Phrase phrase = null;

        // row 1
        phrase = new Phrase("Till No:", simpleFont);
        table.addCell(phrase);

        phrase = new Phrase(bean.getTillName(), simpleFont);
        table.addCell(phrase);

        // row 2
        phrase = new Phrase("Begining Balance:", simpleFont);
        table.addCell(phrase);

        phrase = new Phrase(currency + formatter.format(beginningBalance), simpleFont);
        table.addCell(phrase);

        // row 3
        phrase = new Phrase("Net Cash Trx:", simpleFont);
        table.addCell(phrase);

        phrase = new Phrase(currency + formatter.format(statementDifference), simpleFont);
        table.addCell(phrase);

        phrase = new Phrase("Till Balance Entered:", simpleFont);
        table.addCell(phrase);

        phrase = new Phrase(currency + formatter.format(transferAmount), simpleFont);
        table.addCell(phrase);

        phrase = new Phrase("Difference:", simpleFont);
        table.addCell(phrase);

        phrase = new Phrase(currency + formatter.format(differenceAmount), simpleFont);
        table.addCell(phrase);

        phrase = new Phrase("Ending Balance:", simpleFont);
        table.addCell(phrase);

        phrase = new Phrase(currency + formatter.format(endingBalance), simpleFont);
        table.addCell(phrase);

        phrase = new Phrase("Cash Total:", simpleFont);
        table.addCell(phrase);

        phrase = new Phrase(currency + formatter.format(tillCashTotal), simpleFont);
        table.addCell(phrase);

        phrase = new Phrase("Card Amt Entered:", simpleFont);
        table.addCell(phrase);

        phrase = new Phrase(currency + formatter.format(cashBeanCardTotal), simpleFont);
        table.addCell(phrase);

        phrase = new Phrase("Card Total:", simpleFont);
        table.addCell(phrase);

        phrase = new Phrase(currency + formatter.format(tillCardTotal), simpleFont);
        table.addCell(phrase);

        phrase = new Phrase("Card Difference:", simpleFont);
        table.addCell(phrase);

        phrase = new Phrase(currency + formatter.format(cardDifference), simpleFont);
        table.addCell(phrase);

        phrase = new Phrase("Cheque Amt Entered:", simpleFont);
        table.addCell(phrase);

        phrase = new Phrase(currency + formatter.format(cashBeanChequeTotal), simpleFont);
        table.addCell(phrase);

        phrase = new Phrase("Cheque Total:", simpleFont);
        table.addCell(phrase);

        phrase = new Phrase(currency + formatter.format(tillChequeTotal), simpleFont);
        table.addCell(phrase);

        phrase = new Phrase("Cheque Difference:", simpleFont);
        table.addCell(phrase);

        phrase = new Phrase(currency + formatter.format(chequeDifference), simpleFont);
        table.addCell(phrase);

        phrase = new Phrase("Grand Total:", simpleFont);
        table.addCell(phrase);

        phrase = new Phrase(currency + formatter.format(grandTotal), simpleFont);
        table.addCell(phrase);

        layoutTbl.addCell(table);

        document.add(layoutTbl);

    } catch (Exception e) {
        throw new OperationException(e);
    }

    document.close();

    return reportName;

}

From source file:org.posterita.core.CrossTabReportGenerator.java

License:Open Source License

protected void writeDocument(Document document) throws OperationException {
    try {/*from   ww  w .  j  ava 2s .c om*/
        int noOfRows = dataSource.size();
        String longestText = "";
        int columnCount = 0;

        Object[] obj = null;

        Object[] header = (Object[]) dataSource.get(0);
        columnCount = header.length;

        PdfPTable table = new PdfPTable(columnCount);
        table.setWidthPercentage(100);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.getDefaultCell().setPaddingBottom(5);
        table.getDefaultCell().setPaddingTop(5);

        //adding the headers
        for (int i = 0; i < columnCount; i++) {
            if (i == 0) {
                longestText = header[i].toString();
                table.addCell(new Paragraph(header[i].toString()));
            } else {
                Image img = getTextAsImage(header[i].toString());
                img.setRotationDegrees(90);
                img.setAlignment(Image.ALIGN_BOTTOM);

                PdfPCell cell = new PdfPCell(img);
                cell.setPadding(4);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
                //cell.setBackgroundColor(new Color(0, 0, 255));

                table.addCell(cell);
            }
        }

        //adding the data 
        for (int j = 1; j < noOfRows; j++) {
            obj = (Object[]) dataSource.get(j);

            for (int k = 0; k < columnCount; k++) {
                if (k == 0) {
                    String text = obj[0].toString();

                    if (new Chunk(text, HEADER_FONT).getWidthPoint() > new Chunk(longestText, HEADER_FONT)
                            .getWidthPoint()) {
                        longestText = text;
                    }

                    Chunk txtck = new Chunk(obj[0].toString(), HEADER_FONT);
                    PdfPCell cell = new PdfPCell(new Paragraph(txtck));

                    if (j == noOfRows - 1) {
                        cell.setBackgroundColor(new Color(170, 170, 170));
                    }

                    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                    cell.setPaddingBottom(5);
                    cell.setPaddingTop(5);
                    cell.setPaddingLeft(5);

                    table.addCell(cell);
                } else {
                    Chunk txtck = new Chunk(obj[k].toString(), DATA_FONT);

                    if (k == columnCount - 1) {
                        PdfPCell cell = new PdfPCell(new Paragraph(txtck));
                        cell.setBackgroundColor(new Color(170, 170, 170));
                        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                        cell.setPaddingBottom(5);
                        cell.setPaddingTop(5);

                        table.addCell(cell);
                    } else {
                        PdfPCell cell = new PdfPCell(new Paragraph(txtck));
                        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                        cell.setPaddingBottom(5);
                        cell.setPaddingTop(5);

                        if (j == noOfRows - 1) {
                            cell.setBackgroundColor(new Color(170, 170, 170));
                        }

                        table.addCell(cell);
                    }
                }

            }

        }

        //setting table width
        Chunk dataChk = new Chunk("9999", DATA_FONT);
        Chunk headerChk = new Chunk(longestText, HEADER_FONT);

        float dataChkLength = dataChk.getWidthPoint() + 2 * CELLPADDING;
        float headerChkLength = headerChk.getWidthPoint() + 2 * CELLPADDING;

        float tableWidth = headerChkLength + dataChkLength * columnCount;
        float actualTableWidth = document.getPageSize().getWidth() - 2 * MARGIN;

        float columnWidth = dataChkLength;

        if (tableWidth < actualTableWidth) {
            columnWidth = (actualTableWidth - headerChkLength) / (columnCount - 1);
        }

        float[] widths = new float[columnCount];
        widths[0] = headerChkLength + 2 * CELLPADDING;

        for (int i = 1; i < columnCount; i++) {
            widths[i] = columnWidth;
        }

        table.setWidths(widths);

        //writing the table      
        document.add(table);
    } catch (DocumentException e) {
        throw new OperationException(e);
    }

}

From source file:org.revager.export.InvitationPDFExporter.java

License:Open Source License

/**
 * Write the title page of the PDF document.
 * //from  w  ww  . ja v a  2  s .c  o  m
 * @throws ExportException
 *             If an error occurs while creating the title page
 */
private void writeTitlePage() throws ExportException {
    try {
        Font plainFontTitle = new Font(
                BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED), 12);

        Font boldFontTitle = new Font(
                BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.EMBEDDED), 12);

        Font boldItalicFontTitle = new Font(
                BaseFont.createFont(BaseFont.HELVETICA_BOLDOBLIQUE, BaseFont.CP1252, BaseFont.EMBEDDED), 12);

        Font plainFont = new Font(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED),
                10);

        Font boldFont = new Font(
                BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.EMBEDDED), 10);

        Font boldItalicFont = new Font(
                BaseFont.createFont(BaseFont.HELVETICA_BOLDOBLIQUE, BaseFont.CP1252, BaseFont.EMBEDDED), 10);

        Font italicFont = new Font(
                BaseFont.createFont(BaseFont.HELVETICA_OBLIQUE, BaseFont.CP1252, BaseFont.EMBEDDED), 10);

        Font italicFontSmall = new Font(
                BaseFont.createFont(BaseFont.HELVETICA_OBLIQUE, BaseFont.CP1252, BaseFont.EMBEDDED), 9);

        Phrase phraseStrut = new Phrase(" ");
        phraseStrut.setLeading(leading);

        /*
         * date and time of the meeting
         */
        String meetingDate = sdfDate.format(meeting.getPlannedDate().getTime());

        String meetingTime = sdfTime.format(meeting.getPlannedStart().getTime()) + " - "
                + sdfTime.format(meeting.getPlannedEnd().getTime()) + " ["
                + meeting.getPlannedEnd().getTimeZone().getDisplayName() + "]";
        ;

        /*
         * Base table
         */
        PdfPTable table = new PdfPTable(new float[] { 0.04f, 0.96f });
        table.setWidthPercentage(100);
        table.setSplitRows(false);
        table.getDefaultCell().setBorderWidth(0);
        table.getDefaultCell().setPadding(0);

        /*
         * recipient of the invitation
         */
        PdfPCell cell = new PdfPCell();
        cell.setBorder(0);
        cell.setColspan(2);
        cell.setPadding(padding);

        cell.addElement(phraseStrut);

        PdfPTable tableRecipient = new PdfPTable(2);
        tableRecipient.setWidthPercentage(100);
        tableRecipient.setSplitRows(false);
        tableRecipient.getDefaultCell().setBorderWidth(0);
        tableRecipient.getDefaultCell().setPadding(0);

        PdfPCell cellRecipient = new PdfPCell();
        cellRecipient.setBorder(0);
        cellRecipient.setPadding(0);
        cellRecipient.addElement(new Phrase(translate("To:"), plainFontTitle));
        cellRecipient.addElement(new Phrase(attendee.getName(), boldFontTitle));

        tableRecipient.addCell(cellRecipient);

        PdfPCell cellDate = new PdfPCell(new Phrase(sdfDate.format(new Date().getTime()), plainFont));
        cellDate.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cellDate.setBorder(0);
        cellDate.setPadding(0);
        cellDate.setPaddingTop(7);

        tableRecipient.addCell(cellDate);

        cell.addElement(tableRecipient);

        cell.addElement(phraseStrut);
        cell.addElement(phraseStrut);
        cell.addElement(phraseStrut);

        /*
         * subject
         */
        cell.addElement(new Phrase(translate("Invitation for the Meeting on") + " " + meetingDate,
                boldItalicFontTitle));

        cell.addElement(phraseStrut);

        /*
         * invitation text
         */
        Phrase phrase = new Phrase(
                Data.getInstance().getAppData().getSetting(AppSettingKey.PDF_INVITATION_TEXT), plainFont);
        phrase.setLeading(leading);

        cell.addElement(phrase);

        cell.addElement(phraseStrut);

        table.addCell(cell);

        /*
         * meeting date, time and location
         */
        cell = new PdfPCell(new Phrase(meetingDate, boldItalicFont));
        cell.setBorder(0);
        cell.setColspan(2);
        cell.setPadding(padding);
        cell.setPaddingBottom(0);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);

        table.addCell(cell);

        cell = new PdfPCell(new Phrase(meetingTime, italicFont));
        cell.setBorder(0);
        cell.setColspan(2);
        cell.setPadding(padding);
        cell.setPaddingBottom(0);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);

        table.addCell(cell);

        if (!meeting.getPlannedLocation().equals("")) {
            cell = new PdfPCell(
                    new Phrase(translate("Location") + ": " + meeting.getPlannedLocation(), italicFont));
            cell.setBorder(0);
            cell.setColspan(2);
            cell.setPadding(padding);
            cell.setPaddingBottom(0);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);

            table.addCell(cell);
        }

        /*
         * role; review title and description
         */
        cell = new PdfPCell();
        cell.setBorder(0);
        cell.setColspan(2);
        cell.setPadding(padding);

        cell.addElement(phraseStrut);
        cell.addElement(phraseStrut);

        phrase = new Phrase();
        phrase.setLeading(leading);
        phrase.add(new Chunk(MessageFormat.format(translate("You are invited as {0} to this review ({1})."),
                translate(attendee.getRole().toString()), getReviewTitle()), boldFont));

        cell.addElement(phrase);

        cell.addElement(phraseStrut);

        cell.addElement(new Phrase(resiData.getReview().getDescription(), italicFont));

        cell.addElement(phraseStrut);

        /*
         * Predecessor meeting
         */
        if (meetMgmt.getPredecessorMeeting(meeting) != null) {
            String preMeetingDate = sdfDate
                    .format(meetMgmt.getPredecessorMeeting(meeting).getProtocol().getDate().getTime());

            cell.addElement(new Phrase(MessageFormat
                    .format(translate("This meeting ties up to the review meeting of {0}."), preMeetingDate),
                    plainFont));

            cell.addElement(phraseStrut);
        }

        /*
         * If there is a product name defined
         */
        if (!Data.getInstance().getResiData().getReview().getProduct().getName().trim().equals("")) {
            /*
             * the product of this review
             */
            cell.addElement(new Phrase(translate("The following product will be reviewed:"), plainFont));
            cell.addElement(phraseStrut);

            table.addCell(cell);

            /*
             * Write name and version of the reviewed product
             */
            Phrase phrName = new Phrase(Data.getInstance().getResiData().getReview().getProduct().getName(),
                    boldItalicFont);
            phrName.setLeading(leading);

            PdfPCell cellName = new PdfPCell(phrName);
            cellName.setColspan(2);
            cellName.setBorderWidth(0);
            cellName.setPadding(padding);
            cellName.setPaddingBottom(0);
            cellName.setHorizontalAlignment(Element.ALIGN_CENTER);

            table.addCell(cellName);

            /*
             * If there is a product version defined
             */
            if (!Data.getInstance().getResiData().getReview().getProduct().getVersion().trim().equals("")) {
                Phrase phrVersion = new Phrase(
                        translate("Product Version") + ": "
                                + Data.getInstance().getResiData().getReview().getProduct().getVersion(),
                        italicFont);
                phrVersion.setLeading(leading);

                PdfPCell cellVersion = new PdfPCell(phrVersion);
                cellVersion.setColspan(2);
                cellVersion.setBorderWidth(0);
                cellVersion.setPadding(padding);
                cellVersion.setPaddingBottom(0);
                cellVersion.setHorizontalAlignment(Element.ALIGN_CENTER);

                table.addCell(cellVersion);
            }

            table.addCell(createVerticalStrut(PDFTools.cmToPt(0.7f), 2));
        } else {
            table.addCell(cell);
        }

        boolean showBottomStrut = false;

        /*
         * List point used for lists
         */
        Phrase phraseListPoint = new Phrase("", boldFont);
        phraseListPoint.setLeading(leading);

        PdfPCell cellListPoint = new PdfPCell();
        cellListPoint.addElement(phraseListPoint);
        cellListPoint.setBorderWidth(0);
        cellListPoint.setPadding(padding);
        cellListPoint.setPaddingLeft(padding * 2);
        cellListPoint.setPaddingBottom(0);

        /*
         * Textual references
         */
        for (String ref : Application.getInstance().getReviewMgmt().getProductReferences()) {
            Phrase phraseRef = new Phrase(ref, italicFontSmall);
            phraseRef.setLeading(leading);

            PdfPCell cellRef = new PdfPCell();
            cellRef.addElement(phraseRef);
            cellRef.setBorderWidth(0);
            cellRef.setPadding(padding);
            cellRef.setPaddingBottom(0);

            table.addCell(cellListPoint);

            table.addCell(cellRef);

            showBottomStrut = true;
        }

        /*
         * External file references
         */
        for (File ref : Application.getInstance().getReviewMgmt().getExtProdReferences()) {
            Phrase phraseRef = new Phrase();
            phraseRef.add(new Chunk(ref.getName(), italicFontSmall));
            phraseRef.add(new Chunk(" (" + translate("File Attachment") + ")", italicFontSmall));
            phraseRef.setFont(plainFont);
            phraseRef.setLeading(leading);

            PdfPCell cellRef = new PdfPCell();
            cellRef.addElement(phraseRef);
            cellRef.setBorderWidth(0);
            cellRef.setPadding(padding);
            cellRef.setPaddingBottom(0);

            table.addCell(cellListPoint);

            if (attachProdExtRefs) {
                cellRef.setCellEvent(new PDFCellEventExtRef(pdfWriter, ref));
            }

            table.addCell(cellRef);

            showBottomStrut = true;
        }

        if (showBottomStrut) {
            table.addCell(createVerticalStrut(PDFTools.cmToPt(0.4f), 2));
        }

        /*
         * "please prepare" for the reviwers; on questions ask moderators
         */
        cell = new PdfPCell();
        cell.setBorder(0);
        cell.setColspan(2);
        cell.setPadding(padding);

        phrase = new Phrase();
        phrase.setLeading(leading);

        if (attendee.getAspects() != null) {
            phrase.add(new Chunk(translate(
                    "Please prepare for the review meeting by checking the product for the aspects which are associated to you.")
                    + " ", plainFont));
        }

        List<Attendee> moderators = new ArrayList<Attendee>();
        for (Attendee a : Application.getInstance().getAttendeeMgmt().getAttendees()) {
            if (a.getRole() == Role.MODERATOR) {
                moderators.add(a);
            }
        }

        if (moderators.size() == 1 && attendee.getRole() != Role.MODERATOR) {
            phrase.add(new Chunk(translate(
                    "Please do not hesitate to contact the review moderator if you have any questions:") + " ",
                    plainFont));
        } else if (moderators.size() > 1 && attendee.getRole() != Role.MODERATOR) {
            phrase.add(new Chunk(translate(
                    "Please do not hesitate to contact one of the review moderators if you have any questions:")
                    + " ", plainFont));
        }

        cell.addElement(phrase);

        Phrase phraseStrutSmall = new Phrase(" ");
        phraseStrutSmall.setLeading(leading / 2);

        if (moderators.size() > 0 && attendee.getRole() != Role.MODERATOR) {
            for (Attendee mod : moderators) {
                cell.addElement(phraseStrutSmall);
                cell.addElement(new Phrase(mod.getName(), boldFont));
                cell.addElement(new Phrase(mod.getContact(), italicFont));
            }
        }

        table.addCell(cell);

        pdfDoc.add(table);
    } catch (Exception e) {
        /*
         * Not part of unit testing because this exception is only thrown if
         * an internal error occurs.
         */
        throw new ExportException(translate("Cannot generate front page of the PDF document."));
    }
}

From source file:org.revager.export.InvitationPDFExporter.java

License:Open Source License

/**
 * Write the aspects./*www  . j av  a 2  s.  co  m*/
 * 
 * @throws ExportException
 *             If an error occurs while writing the aspects
 */
private void writeAspects() throws ExportException {
    /*
     * If the role of the attendee is not reviewer show all aspects
     */
    List<Aspect> aspects = null;

    if (attendee.getRole() == Role.REVIEWER) {
        aspects = attMgmt.getAspects(attendee);
    } else {
        aspects = aspMgmt.getAspects();
    }

    if (aspects.size() == 0) {
        return;
    }

    try {
        Font descriptionFont = new Font(
                BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED), 10);

        Font directiveFont = new Font(
                BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.EMBEDDED), 10);

        Font categoryFont = new Font(
                BaseFont.createFont(BaseFont.HELVETICA_OBLIQUE, BaseFont.CP1252, BaseFont.EMBEDDED), 10);

        Font reviewerFont = new Font(
                BaseFont.createFont(BaseFont.HELVETICA_OBLIQUE, BaseFont.CP1252, BaseFont.EMBEDDED), 9);

        /*
         * Build base table for all attendees
         */
        PdfPTable tableAspects = new PdfPTable(1);
        tableAspects.setWidthPercentage(100);
        tableAspects.setSplitRows(false);
        tableAspects.getDefaultCell().setBorderWidth(0);
        tableAspects.getDefaultCell().setPadding(0);

        boolean grayBackground = true;

        for (Aspect asp : aspects) {
            /*
             * Build table for one aspect
             */
            PdfPTable tableAspect = new PdfPTable(new float[] { 0.70f, 0.30f });
            tableAspect.setWidthPercentage(100);
            tableAspect.getDefaultCell().setBorderWidth(0);
            tableAspect.getDefaultCell().setPadding(0);

            PdfPCell cellAspect = new PdfPCell();
            cellAspect.setPadding(0);
            cellAspect.setBorder(0);

            Phrase phraseStrut = new Phrase(" ");
            phraseStrut.setLeading(leading * 0.4f);

            /*
             * directive and description of the aspect
             */
            PdfPCell cell = new PdfPCell();
            cell.setBorderWidth(0);
            cell.setPadding(padding * 0.4f);
            cell.setPaddingBottom(padding * 1.5f);
            cell.addElement(new Phrase(asp.getDirective(), directiveFont));
            cell.addElement(phraseStrut);
            cell.addElement(new Phrase(asp.getDescription(), descriptionFont));

            /*
             * the reviewers of this aspect (moderator only)
             */
            if (attendee.getRole() == Role.MODERATOR) {
                cell.addElement(phraseStrut);
                cell.addElement(phraseStrut);

                String separator = "";

                Phrase phraseReviewers = new Phrase();
                phraseReviewers.setLeading(leading);
                phraseReviewers.setFont(reviewerFont);

                for (Attendee att : attMgmt.getAttendees()) {
                    if (attMgmt.hasAspect(asp, att)) {
                        phraseReviewers.add(new Chunk(separator + att.getName(), reviewerFont));

                        separator = "    ";
                    }
                }

                cell.addElement(phraseReviewers);
            }

            tableAspect.addCell(cell);

            /*
             * category of the aspect
             */
            cell = new PdfPCell(new Phrase(asp.getCategory(), categoryFont));
            cell.setBorderWidth(0);
            cell.setPadding(padding * 0.4f);
            cell.setPaddingTop(padding * 1.1f);
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

            tableAspect.addCell(cell);

            cellAspect.addElement(tableAspect);
            cellAspect.setPadding(0);
            cellAspect.setPaddingLeft(padding);
            cellAspect.setPaddingRight(padding);

            if (grayBackground == true) {
                grayBackground = false;
                cellAspect.setBackgroundColor(cellBackground);
            } else {
                grayBackground = true;
            }

            /*
             * Add aspect to the list
             */
            tableAspects.addCell(cellAspect);
        }

        PdfPCell cellBottomLine = new PdfPCell();
        cellBottomLine.setPadding(0);
        cellBottomLine.setBorderWidth(0);
        cellBottomLine.setBorderWidthBottom(1);
        cellBottomLine.setBorderColor(cellBackground);

        tableAspects.addCell(cellBottomLine);

        /*
         * Add the attendee base table to the document
         */
        pdfDoc.add(tableAspects);
    } catch (Exception e) {
        /*
         * Not part of unit testing because this exception is only thrown if
         * an internal error occurs.
         */
        throw new ExportException(translate("Cannot put aspects into the PDF document."));
    }
}

From source file:org.revager.export.ProtocolPDFExporter.java

License:Open Source License

/**
 * Write the title page of the protocol.
 * /*  w  w  w  .j  a  v  a  2s .  c o  m*/
 * @param meetings
 *            the meetings
 * @param attachProdExtRefs
 *            true, if the external reference of the product should be part
 *            of the protocol
 * 
 * @throws ExportException
 *             If an error occurs while writing the title page
 */
protected void writeTitlePage(List<Meeting> meetings, boolean attachProdExtRefs) throws ExportException {
    try {
        Font plainFont = new Font(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED),
                10);

        Font plainFontSmall = new Font(
                BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED), 8);

        Font boldFont = new Font(
                BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.EMBEDDED), 11);

        Font italicFont = new Font(
                BaseFont.createFont(BaseFont.HELVETICA_OBLIQUE, BaseFont.CP1252, BaseFont.EMBEDDED), 10);

        Font italicFontSmall = new Font(
                BaseFont.createFont(BaseFont.HELVETICA_OBLIQUE, BaseFont.CP1252, BaseFont.EMBEDDED), 8);

        Font boldItalicFont = new Font(
                BaseFont.createFont(BaseFont.HELVETICA_BOLDOBLIQUE, BaseFont.CP1252, BaseFont.EMBEDDED), 11);

        Font boldItalicFontSmall = new Font(
                BaseFont.createFont(BaseFont.HELVETICA_BOLDOBLIQUE, BaseFont.CP1252, BaseFont.EMBEDDED), 8);

        Font protocolFontTitle = new Font(
                BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.EMBEDDED), 20);

        Font reviewFontTitle = new Font(
                BaseFont.createFont(BaseFont.HELVETICA_OBLIQUE, BaseFont.CP1252, BaseFont.EMBEDDED), 15);

        Font meetingFontTitle = new Font(
                BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED), 13);

        /*
         * Title of the protocol
         */
        PdfPTable tableTitlePage = new PdfPTable(new float[] { 0.6f, 0.4f });
        tableTitlePage.setWidthPercentage(100);
        tableTitlePage.setSplitRows(false);
        tableTitlePage.getDefaultCell().setBorder(0);
        tableTitlePage.getDefaultCell().setPadding(0);

        String protocolTitle = translate("Findings List of the Review");

        if (meetings.size() == 1) {
            protocolTitle = translate("Findings List of the Review Meeting");
        }

        PdfPCell cellProtocol = new PdfPCell(new Phrase(protocolTitle, protocolFontTitle));
        cellProtocol.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellProtocol.setColspan(2);
        cellProtocol.setBorderWidth(0);
        cellProtocol.setPaddingTop(PDFTools.cmToPt(0.4f));
        cellProtocol.setPaddingBottom(PDFTools.cmToPt(0.2f));

        tableTitlePage.addCell(cellProtocol);

        /*
         * Name of the review
         */
        PdfPCell cellRevName = new PdfPCell(
                new Phrase(Application.getInstance().getReviewMgmt().getReviewName(), reviewFontTitle));
        cellRevName.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellRevName.setColspan(2);
        cellRevName.setBorderWidth(0);
        cellRevName.setPaddingBottom(PDFTools.cmToPt(1.6f));

        tableTitlePage.addCell(cellRevName);

        /*
         * Review meeting date and location
         */
        if (meetings.size() == 1) {
            sdfDate.setTimeZone(meetings.get(0).getProtocol().getDate().getTimeZone());
            sdfTime.setTimeZone(meetings.get(0).getProtocol().getDate().getTimeZone());

            String meetingDate = sdfDate.format(meetings.get(0).getProtocol().getDate().getTime());

            String meetingTime = sdfTime.format(meetings.get(0).getProtocol().getStart().getTime()) + " - "
                    + sdfTime.format(meetings.get(0).getProtocol().getEnd().getTime()) + " ["
                    + meetings.get(0).getProtocol().getEnd().getTimeZone().getDisplayName() + "]";

            Phrase phraseMeeting = new Phrase(meetingDate + " (" + meetingTime + ")", meetingFontTitle);

            PdfPCell cellMeeting = new PdfPCell(phraseMeeting);
            cellMeeting.setColspan(2);
            cellMeeting.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellMeeting.setPadding(0);
            cellMeeting.setBorderWidth(0);

            tableTitlePage.addCell(cellMeeting);

            String location = meetings.get(0).getProtocol().getLocation();

            if (location.trim().equals("")) {
                location = "--";
            }
            cellMeeting = new PdfPCell(new Phrase(translate("Location") + ": " + location, meetingFontTitle));
            cellMeeting.setColspan(2);
            cellMeeting.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellMeeting.setPadding(0);
            cellMeeting.setBorderWidth(0);
            cellMeeting.setPaddingTop(PDFTools.cmToPt(0.15f));
            cellMeeting.setPaddingBottom(PDFTools.cmToPt(1.9f));

            tableTitlePage.addCell(cellMeeting);
        }

        /*
         * Review description and comments
         */
        PdfPCell cellRevDesc = new PdfPCell(new Phrase(translate("Review Description:"), boldItalicFont));
        cellRevDesc.setBorderWidth(0);
        cellRevDesc.setPadding(padding);

        tableTitlePage.addCell(cellRevDesc);

        cellRevDesc = new PdfPCell(new Phrase(translate("Review Comments"), boldFont));
        cellRevDesc.setBorderWidth(0);
        cellRevDesc.setPadding(padding);
        cellRevDesc.setBackgroundColor(cellBackground);

        tableTitlePage.addCell(cellRevDesc);

        String revDesc = Application.getInstance().getReviewMgmt().getReviewDescription();
        if (revDesc.trim().equals("")) {
            revDesc = "--";
        }

        Phrase phrDesc = new Phrase(revDesc, plainFont);
        phrDesc.setLeading(leading);
        cellRevDesc = new PdfPCell();
        cellRevDesc.addElement(phrDesc);
        cellRevDesc.setBorderWidth(0);
        cellRevDesc.setPadding(padding);
        cellRevDesc.setPaddingBottom(padding * 1.8f);

        tableTitlePage.addCell(cellRevDesc);

        String revComm = Application.getInstance().getReviewMgmt().getReviewComments();
        if (revComm.trim().equals("")) {
            revComm = "--";
        }

        Phrase phrComm = new Phrase(revComm, italicFont);
        phrComm.setLeading(leading);
        cellRevDesc = new PdfPCell();
        cellRevDesc.addElement(phrComm);
        cellRevDesc.setBorderWidth(0);
        cellRevDesc.setPadding(padding);
        cellRevDesc.setPaddingBottom(padding * 1.8f);
        cellRevDesc.setBackgroundColor(cellBackground);

        tableTitlePage.addCell(cellRevDesc);

        tableTitlePage.addCell(createVerticalStrut(PDFTools.cmToPt(1.0f), 2));

        /*
         * Product title
         */
        PdfPTable tableProduct = new PdfPTable(new float[] { 0.07f, 0.93f });
        tableProduct.setWidthPercentage(100);
        tableProduct.setSplitRows(false);
        tableProduct.getDefaultCell().setBorderWidth(0);
        tableProduct.getDefaultCell().setPadding(0);

        PdfPCell cellProdTitle = new PdfPCell(new Phrase(translate("Reviewed Product:"), boldItalicFont));
        cellProdTitle.setColspan(2);
        cellProdTitle.setPadding(padding);
        cellProdTitle.setBorder(0);

        tableProduct.addCell(cellProdTitle);

        /*
         * List point used for lists
         */
        Phrase phraseListPoint = new Phrase("", boldFont);
        phraseListPoint.setLeading(leading);

        PdfPCell cellListPoint = new PdfPCell();
        cellListPoint.addElement(phraseListPoint);
        cellListPoint.setBorderWidth(0);
        cellListPoint.setPadding(padding);
        cellListPoint.setPaddingLeft(padding * 2);
        cellListPoint.setPaddingBottom(0);

        /*
         * Write name and version of the reviewed product
         */
        String prodName = Data.getInstance().getResiData().getReview().getProduct().getName();

        if (prodName.trim().equals("")) {
            prodName = "--";
        }

        Phrase phrName = new Phrase(translate("Product Name") + ": " + prodName, plainFont);
        phrName.setLeading(leading);

        PdfPCell cellName = new PdfPCell();
        cellName.addElement(phrName);
        cellName.setBorderWidth(0);
        cellName.setPadding(padding);
        cellName.setPaddingBottom(0);

        tableProduct.addCell(cellListPoint);

        tableProduct.addCell(cellName);

        String prodVersion = Data.getInstance().getResiData().getReview().getProduct().getVersion();

        if (prodVersion.trim().equals("")) {
            prodVersion = "--";
        }

        Phrase phrVersion = new Phrase(translate("Product Version") + ": " + prodVersion, plainFont);
        phrVersion.setLeading(leading);

        PdfPCell cellVersion = new PdfPCell();
        cellVersion.addElement(phrVersion);
        cellVersion.setBorderWidth(0);
        cellVersion.setPadding(padding);
        cellVersion.setPaddingBottom(0);

        tableProduct.addCell(cellListPoint);

        tableProduct.addCell(cellVersion);

        if (Application.getInstance().getReviewMgmt().getNumberOfProdRefs() > 0) {
            /*
             * Table of product references
             */
            PdfPCell cellRefTitle = new PdfPCell(new Phrase(translate("Product References:"), boldItalicFont));
            cellRefTitle.setBorderWidth(0);
            cellRefTitle.setPadding(padding);
            cellRefTitle.setPaddingTop(padding * 4);
            cellRefTitle.setColspan(2);

            tableProduct.addCell(cellRefTitle);

            /*
             * Textual references
             */
            for (String ref : Application.getInstance().getReviewMgmt().getProductReferences()) {
                Phrase phraseRef = new Phrase(ref, plainFont);
                phraseRef.setLeading(leading);

                PdfPCell cellRef = new PdfPCell();
                cellRef.addElement(phraseRef);
                cellRef.setBorderWidth(0);
                cellRef.setPadding(padding);
                cellRef.setPaddingBottom(0);

                tableProduct.addCell(cellListPoint);

                tableProduct.addCell(cellRef);
            }

            /*
             * External file references
             */
            for (File ref : Application.getInstance().getReviewMgmt().getExtProdReferences()) {
                Phrase phraseRef = new Phrase();
                phraseRef.add(new Chunk(ref.getName(), plainFont));
                phraseRef.add(new Chunk(" (" + translate("File Attachment") + ")", italicFont));
                phraseRef.setFont(plainFont);
                phraseRef.setLeading(leading);

                PdfPCell cellRef = new PdfPCell();
                cellRef.addElement(phraseRef);
                cellRef.setBorderWidth(0);
                cellRef.setPadding(padding);
                cellRef.setPaddingBottom(0);

                tableProduct.addCell(cellListPoint);

                if (attachProdExtRefs) {
                    cellRef.setCellEvent(new PDFCellEventExtRef(pdfWriter, ref));
                }

                tableProduct.addCell(cellRef);
            }
        }

        /*
         * Add the product table to the base table
         */
        PdfPCell cellProduct = new PdfPCell(tableProduct);
        cellProduct.setBorder(0);
        cellProduct.setPadding(0);

        tableTitlePage.addCell(cellProduct);

        /*
         * List the meetings of this review
         */
        PdfPCell cellInfos = new PdfPCell();
        cellInfos.setBorder(0);
        cellInfos.setPadding(0);

        /*
         * meeting list title or meeting info title
         */
        PdfPTable tableInfos = new PdfPTable(new float[] { 0.09f, 0.91f });
        tableInfos.setWidthPercentage(100);
        tableInfos.setSplitRows(false);
        tableInfos.getDefaultCell().setBorderWidth(0);
        tableInfos.getDefaultCell().setPadding(0);

        String title = translate("Meeting Information:");

        if (meetings.size() > 1) {
            title = translate("Findings Lists of the Review Meetings:");
        }

        PdfPCell cellInfosTitle = new PdfPCell(new Phrase(title, boldFont));
        cellInfosTitle.setColspan(2);
        cellInfosTitle.setPadding(padding);
        cellInfosTitle.setBorder(0);

        tableInfos.addCell(cellInfosTitle);

        if (meetings.size() > 1) {
            /*
             * list the meetings of this review (for review protocols)
             */
            for (Meeting m : meetings) {
                Protocol protocol = m.getProtocol();
                if (protocol != null) {
                    String meetingDate = sdfDate.format(protocol.getDate().getTime());

                    String meetingTime = sdfTime.format(protocol.getStart().getTime()) + " - "
                            + sdfTime.format(protocol.getEnd().getTime()) + " ["
                            + protocol.getEnd().getTimeZone().getDisplayName() + "]";
                    String protLoc = protocol.getLocation();
                    if (protLoc.trim().equals("")) {
                        protLoc = "--";
                    }

                    Phrase phraseMeet = new Phrase(
                            translate("Date") + ": " + meetingDate + "\n" + translate("Time") + ": "
                                    + meetingTime + "\n" + translate("Location") + ": " + protLoc,
                            italicFont);

                    Paragraph paraMeet = new Paragraph();
                    paraMeet.setLeading(leading);

                    Anchor anchor = new Anchor(phraseMeet);
                    anchor.setReference("#" + Long.toString(
                            protocol.getDate().getTimeInMillis() + protocol.getStart().getTimeInMillis()));

                    paraMeet.add(anchor);

                    PdfPCell cellMeet = new PdfPCell();
                    cellMeet.addElement(paraMeet);
                    cellMeet.setBorderWidth(0);
                    cellMeet.setPadding(padding);

                    tableInfos.addCell(cellListPoint);

                    tableInfos.addCell(cellMeet);
                }
            }
        } else {
            Protocol prot = meetings.get(0).getProtocol();
            Duration meetDur = DatatypeFactory.newInstance()
                    .newDuration(prot.getEnd().getTimeInMillis() - prot.getStart().getTimeInMillis());

            Phrase phraseMeetInfo = new Phrase(
                    translate("Duration of the meeting") + ":\n" + meetDur.getHours() + " "
                            + translate("Hour(s)") + ", " + meetDur.getMinutes() + " " + translate("Minute(s)"),
                    italicFont);
            phraseMeetInfo.setLeading(leading);

            PdfPCell cellMeetInfo = new PdfPCell();
            cellMeetInfo.addElement(phraseMeetInfo);
            cellMeetInfo.setBorderWidth(0);
            cellMeetInfo.setPadding(padding);

            tableInfos.addCell(cellListPoint);

            tableInfos.addCell(cellMeetInfo);

            /*
             * meeting number of findings
             */
            phraseMeetInfo = new Phrase(translate("Number of findings") + ": " + prot.getFindings().size(),
                    italicFont);
            phraseMeetInfo.setLeading(leading);

            cellMeetInfo = new PdfPCell();
            cellMeetInfo.addElement(phraseMeetInfo);
            cellMeetInfo.setBorderWidth(0);
            cellMeetInfo.setPadding(padding);

            tableInfos.addCell(cellListPoint);

            tableInfos.addCell(cellMeetInfo);

            /*
             * meeting number of attendees
             */
            phraseMeetInfo = new Phrase(
                    translate("Number of attendees") + ": " + protMgmt.getAttendees(prot).size(), italicFont);
            phraseMeetInfo.setLeading(leading);

            cellMeetInfo = new PdfPCell();
            cellMeetInfo.addElement(phraseMeetInfo);
            cellMeetInfo.setBorderWidth(0);
            cellMeetInfo.setPadding(padding);

            tableInfos.addCell(cellListPoint);

            tableInfos.addCell(cellMeetInfo);
        }

        cellInfos.addElement(tableInfos);
        cellInfos.setBackgroundColor(cellBackground);
        cellInfos.setPaddingBottom(padding);

        tableTitlePage.addCell(cellInfos);

        /*
         * Insert vertical strut
         */
        tableTitlePage.addCell(createVerticalStrut(PDFTools.cmToPt(1.0f), 2));

        /*
         * Write general impression and recommendation
         */
        PdfPTable tableRevInfo = new PdfPTable(new float[] { 0.5f, 0.5f });
        tableRevInfo.setWidthPercentage(100);
        tableRevInfo.setSplitRows(false);
        tableRevInfo.getDefaultCell().setBorderWidth(0);
        tableRevInfo.getDefaultCell().setPadding(0);

        /*
         * Insert vertical strut
         */
        tableRevInfo.addCell(createVerticalStrut(PDFTools.cmToPt(0.5f), 2));

        PdfPCell cellImpr = new PdfPCell(
                new Phrase(translate("General impressions of the product:"), boldFont));
        cellImpr.setBorderWidth(0);
        cellImpr.setPadding(padding);
        cellImpr.setBorderColor(verticalBorderColor);
        cellImpr.setBorderWidthLeft(verticalBorderWidth);

        tableRevInfo.addCell(cellImpr);

        PdfPCell cellReco = new PdfPCell(
                new Phrase(translate("Final recommendation for the product:"), boldFont));
        cellReco.setBorderWidth(0);
        cellReco.setPadding(padding);
        cellReco.setBorderColor(verticalBorderColor);
        cellReco.setBorderWidthLeft(verticalBorderWidth);

        tableRevInfo.addCell(cellReco);

        String impression = Application.getInstance().getReviewMgmt().getImpression();
        if (impression.trim().equals("")) {
            impression = "--";
        }

        Phrase phrImpr = new Phrase(impression, italicFont);
        phrImpr.setLeading(leading);
        cellImpr = new PdfPCell();
        cellImpr.addElement(phrImpr);
        cellImpr.setBorderWidth(0);
        cellImpr.setPadding(padding);
        cellImpr.setPaddingBottom(padding * 1.8f);
        cellImpr.setBorderColor(verticalBorderColor);
        cellImpr.setBorderWidthLeft(verticalBorderWidth);

        tableRevInfo.addCell(cellImpr);

        String recommendation = Application.getInstance().getReviewMgmt().getRecommendation();
        if (recommendation.trim().equals("")) {
            recommendation = "--";
        }

        Phrase phrReco = new Phrase(recommendation, italicFont);
        phrReco.setLeading(leading);
        cellReco = new PdfPCell();
        cellReco.addElement(phrReco);
        cellReco.setBorderWidth(0);
        cellReco.setPadding(padding);
        cellReco.setPaddingBottom(padding * 1.8f);
        cellReco.setBorderColor(verticalBorderColor);
        cellReco.setBorderWidthLeft(verticalBorderWidth);

        tableRevInfo.addCell(cellReco);

        /*
         * Add vertical strut
         */
        tableRevInfo.addCell(createVerticalStrut(PDFTools.cmToPt(0.8f), 2));

        /*
         * Write possible severities for this review
         */
        String severities = "";
        String separator = "";
        for (String sev : Application.getInstance().getSeverityMgmt().getSeverities()) {
            severities = severities + separator + sev;
            separator = "; ";
        }

        Phrase phrSeverities = new Phrase();
        phrSeverities.add(new Chunk(
                translate("The severities of the findings in this review (descending order of importance):"),
                italicFontSmall));
        phrSeverities.add(new Chunk(" " + severities, boldItalicFontSmall));
        phrSeverities.setLeading(leading);
        PdfPCell cellSevs = new PdfPCell();
        cellSevs.setColspan(2);
        cellSevs.addElement(phrSeverities);
        cellSevs.setBorderWidth(0);
        cellSevs.setPadding(padding);

        tableRevInfo.addCell(cellSevs);

        /*
         * Short review statistics
         */
        if (meetings.size() > 1) {
            Phrase phrRevStat = new Phrase(MessageFormat.format(translate(
                    "This review consists of {0} attendees, {1} findings, {2} meetings and {3} aspects."),
                    Application.getInstance().getReviewMgmt().getNumberOfAttendees(),
                    Application.getInstance().getReviewMgmt().getNumberOfFindings(),
                    Application.getInstance().getReviewMgmt().getNumberOfMeetings(),
                    Application.getInstance().getReviewMgmt().getNumberOfAspects()), italicFontSmall);
            phrRevStat.setLeading(leading);
            PdfPCell cellRevStat = new PdfPCell();
            cellRevStat.setColspan(2);
            cellRevStat.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellRevStat.addElement(phrRevStat);
            cellRevStat.setBorderWidth(0);
            cellRevStat.setPadding(padding);
            cellRevStat.setPaddingTop(0);

            tableRevInfo.addCell(cellRevStat);
        }

        /*
         * Write the date of creation
         */
        String creationDate = sdfDate.format(new Date().getTime());

        Phrase phrCreationDate = new Phrase(
                translate("This finding has been created with RevAger on") + " " + creationDate,
                plainFontSmall);
        phrCreationDate.setLeading(leading);
        PdfPCell cellCrDate = new PdfPCell();
        cellCrDate.setColspan(2);
        cellCrDate.setHorizontalAlignment(Element.ALIGN_CENTER);
        cellCrDate.addElement(phrCreationDate);
        cellCrDate.setBorderWidth(0);
        cellCrDate.setPadding(0);
        cellCrDate.setPaddingLeft(padding);
        cellCrDate.setPaddingRight(padding);

        tableRevInfo.addCell(cellCrDate);

        /*
         * Add content to the base table
         */
        PdfPCell cellRevInfo = new PdfPCell();
        cellRevInfo.setColspan(2);
        cellRevInfo.setBorder(0);
        cellRevInfo.setPadding(0);
        cellRevInfo.addElement(tableRevInfo);

        tableTitlePage.addCell(cellRevInfo);

        pdfDoc.add(tableTitlePage);
    } catch (Exception e) {
        /*
         * Not part of unit testing because this exception is only thrown if
         * an internal error occurs.
         */
        throw new ExportException(translate("Cannot generate front page of the PDF document."));
    }
}