Example usage for com.lowagie.text.pdf PdfPCell setVerticalAlignment

List of usage examples for com.lowagie.text.pdf PdfPCell setVerticalAlignment

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfPCell setVerticalAlignment.

Prototype

public void setVerticalAlignment(int verticalAlignment) 

Source Link

Document

Sets the vertical alignment for the cell.

Usage

From source file:org.mapfish.print.config.layout.CellConfig.java

License:Open Source License

protected void apply(PdfPCell cell, RenderingContext context, PJsonObject params) {
    if (paddingLeft != null)
        cell.setPaddingLeft(paddingLeft.floatValue());
    if (paddingRight != null)
        cell.setPaddingRight(paddingRight.floatValue());
    if (paddingTop != null)
        cell.setPaddingTop(paddingTop.floatValue());
    if (paddingBottom != null)
        cell.setPaddingBottom(paddingBottom.floatValue());

    if (borderWidthLeft != null)
        cell.setBorderWidthLeft(borderWidthLeft.floatValue());
    if (borderWidthRight != null)
        cell.setBorderWidthRight(borderWidthRight.floatValue());
    if (borderWidthTop != null)
        cell.setBorderWidthTop(borderWidthTop.floatValue());
    if (borderWidthBottom != null)
        cell.setBorderWidthBottom(borderWidthBottom.floatValue());

    if (getBorderColorLeftVal(context, params) != null)
        cell.setBorderColorLeft(getBorderColorLeftVal(context, params));
    if (getBorderColorRightVal(context, params) != null)
        cell.setBorderColorRight(getBorderColorRightVal(context, params));
    if (getBorderColorTopVal(context, params) != null)
        cell.setBorderColorTop(getBorderColorTopVal(context, params));
    if (getBorderColorBottomVal(context, params) != null)
        cell.setBorderColorBottom(getBorderColorBottomVal(context, params));

    if (getBackgroundColorVal(context, params) != null)
        cell.setBackgroundColor(getBackgroundColorVal(context, params));

    if (align != null)
        cell.setHorizontalAlignment(align.getCode());
    if (vertAlign != null)
        cell.setVerticalAlignment(vertAlign.getCode());

}

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

License:Open Source License

private void addSummaryOfNeedsHeader(PdfPTable summaryOfNeedsTable,
        List<OcanNeedRatingOverTimeSummaryOfNeedsBean> currentBeanList, int loopNo) {

    PdfPCell headerCell = new PdfPCell();
    headerCell.setPhrase(new Phrase("Summary of Needs" + (loopNo > 1 ? " (Contd.)" : ""),
            new Font(Font.HELVETICA, 20, Font.BOLD)));

    headerCell.setColspan(currentBeanList.size() * 3);
    headerCell.setVerticalAlignment(Element.ALIGN_TOP);
    headerCell.setBorder(0);/*from w w  w  .  ja va  2 s  .c o  m*/
    headerCell.setHorizontalAlignment(Element.ALIGN_CENTER);
    summaryOfNeedsTable.addCell(headerCell);

    Font f = new Font(Font.HELVETICA, 14, Font.BOLD, Color.WHITE);
    //row1
    PdfPCell c2 = null;

    c2 = new PdfPCell();
    c2.setBorder(0);
    summaryOfNeedsTable.addCell(c2);
    if (currentBeanList.size() > 0) {
        c2 = new PdfPCell();
        c2.setColspan(2);
        c2.setBackgroundColor(Color.BLUE);
        c2.setPhrase(new Phrase(currentBeanList.get(0).getOcanName() + "\n"
                + dateFormatter.format(currentBeanList.get(0).getOcanDate()), f));
        c2.setHorizontalAlignment(Element.ALIGN_CENTER);
        summaryOfNeedsTable.addCell(c2);
    }
    if (currentBeanList.size() > 1) {
        c2 = new PdfPCell();
        c2.setBackgroundColor(Color.BLACK);
        summaryOfNeedsTable.addCell(c2);
        c2 = new PdfPCell();
        c2.setColspan(2);
        c2.setBackgroundColor(Color.BLUE);
        c2.setPhrase(new Phrase(currentBeanList.get(1).getOcanName() + "\n"
                + dateFormatter.format(currentBeanList.get(1).getOcanDate()), f));
        c2.setHorizontalAlignment(Element.ALIGN_CENTER);
        summaryOfNeedsTable.addCell(c2);
    }
    if (currentBeanList.size() > 2) {
        c2 = new PdfPCell();
        c2.setBackgroundColor(Color.BLACK);
        summaryOfNeedsTable.addCell(c2);
        c2 = new PdfPCell();
        c2.setColspan(2);
        c2.setBackgroundColor(Color.BLUE);
        c2.setPhrase(new Phrase(currentBeanList.get(2).getOcanName() + "\n"
                + dateFormatter.format(currentBeanList.get(2).getOcanDate()), f));
        c2.setHorizontalAlignment(Element.ALIGN_CENTER);
        summaryOfNeedsTable.addCell(c2);
    }

    //row2
    c2 = new PdfPCell();
    c2.setBorder(0);
    summaryOfNeedsTable.addCell(c2);

    if (currentBeanList.size() > 0) {
        c2 = new PdfPCell();
        c2.setBackgroundColor(Color.BLUE);
        c2.setPhrase(new Phrase("Consumer", f));
        c2.setHorizontalAlignment(Element.ALIGN_CENTER);
        summaryOfNeedsTable.addCell(c2);
        c2 = new PdfPCell();
        c2.setBackgroundColor(Color.BLUE);
        c2.setPhrase(new Phrase("Staff", f));
        c2.setHorizontalAlignment(Element.ALIGN_CENTER);
        summaryOfNeedsTable.addCell(c2);
    }
    if (currentBeanList.size() > 1) {
        c2 = new PdfPCell();
        c2.setBackgroundColor(Color.BLACK);
        summaryOfNeedsTable.addCell(c2);
        c2 = new PdfPCell();
        c2.setBackgroundColor(Color.BLUE);
        c2.setPhrase(new Phrase("Consumer", f));
        c2.setHorizontalAlignment(Element.ALIGN_CENTER);
        summaryOfNeedsTable.addCell(c2);
        c2 = new PdfPCell();
        c2.setBackgroundColor(Color.BLUE);
        c2.setPhrase(new Phrase("Staff", f));
        c2.setHorizontalAlignment(Element.ALIGN_CENTER);
        summaryOfNeedsTable.addCell(c2);
    }
    if (currentBeanList.size() > 2) {
        c2 = new PdfPCell();
        c2.setBackgroundColor(Color.BLACK);
        summaryOfNeedsTable.addCell(c2);
        c2 = new PdfPCell();
        c2.setBackgroundColor(Color.BLUE);
        c2.setPhrase(new Phrase("Consumer", f));
        c2.setHorizontalAlignment(Element.ALIGN_CENTER);
        summaryOfNeedsTable.addCell(c2);
        c2 = new PdfPCell();
        c2.setBackgroundColor(Color.BLUE);
        c2.setPhrase(new Phrase("Staff", f));
        c2.setHorizontalAlignment(Element.ALIGN_CENTER);
        summaryOfNeedsTable.addCell(c2);
    }
}

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 w w w .j a v  a2 s . c o m*/
            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. j a va  2s . c o m*/
    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;//from   w  w w  . j  av  a2  s. com
    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.core.CrossTabReportGenerator.java

License:Open Source License

protected void writeDocument(Document document) throws OperationException {
    try {//from   w  ww. ja v a2  s  .  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.PDFPageEventHelper.java

License:Open Source License

@Override
public void onEndPage(PdfWriter writer, Document document) {
    int columnNumber;

    try {//from w ww. j a  v a  2 s  . com
        Rectangle page = document.getPageSize();
        float pageWidth = page.getWidth() - document.leftMargin() - document.rightMargin();

        /*
         * Write marks
         */
        setMarks(writer, document);

        /*
         * Define fonts
         */
        headBaseFont = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED);
        Font headFont = new Font(headBaseFont, headFontSize);

        footBaseFont = BaseFont.createFont(BaseFont.HELVETICA_OBLIQUE, BaseFont.CP1252, BaseFont.EMBEDDED);
        Font footFont = new Font(footBaseFont, footFontSize);

        /*
         * Cell fill for space between head/foot and content
         */
        PdfPCell cellFill = new PdfPCell();
        cellFill.setMinimumHeight(PDFTools.cmToPt(0.8f));
        cellFill.setBorderWidth(0);

        /*
         * Write head
         */
        if (headLogoPath != null) {
            columnNumber = 2;
        } else {
            columnNumber = 1;
        }

        PdfPTable head = new PdfPTable(columnNumber);

        Phrase phraseTitle = new Phrase(headTitle, headFont);

        PdfPCell cellTitle = new PdfPCell(phraseTitle);
        cellTitle.setHorizontalAlignment(Element.ALIGN_LEFT);
        cellTitle.setVerticalAlignment(Element.ALIGN_BOTTOM);
        cellTitle.setPaddingTop(0);
        cellTitle.setPaddingBottom(PDFTools.cmToPt(0.2f));
        cellTitle.setPaddingLeft(0);
        cellTitle.setPaddingRight(0);
        cellTitle.setBorderWidthTop(0);
        cellTitle.setBorderWidthBottom(0.5f);
        cellTitle.setBorderWidthLeft(0);
        cellTitle.setBorderWidthRight(0);

        head.addCell(cellTitle);

        if (headLogoPath != null) {
            Image headLogo = Image.getInstance(headLogoPath);
            headLogo.scaleToFit(PDFTools.cmToPt(5.0f), PDFTools.cmToPt(1.1f));

            PdfPCell cellLogo = new PdfPCell(headLogo);
            cellLogo.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cellLogo.setVerticalAlignment(Element.ALIGN_BOTTOM);
            cellLogo.setPaddingTop(0);
            cellLogo.setPaddingBottom(PDFTools.cmToPt(0.15f));
            cellLogo.setPaddingLeft(0);
            cellLogo.setPaddingRight(0);
            cellLogo.setBorderWidthTop(0);
            cellLogo.setBorderWidthBottom(0.5f);
            cellLogo.setBorderWidthLeft(0);
            cellLogo.setBorderWidthRight(0);

            head.addCell(cellLogo);

            head.addCell(cellFill);
        }

        head.addCell(cellFill);

        head.setTotalWidth(pageWidth);
        head.writeSelectedRows(0, -1, document.leftMargin(),
                page.getHeight() - document.topMargin() + head.getTotalHeight(), writer.getDirectContent());

        /*
         * Write foot
         */
        if (footText == null) {
            footText = " ";
        }

        PdfPTable foot = new PdfPTable(1);

        foot.addCell(cellFill);

        PdfPCell cellFootText = new PdfPCell(new Phrase(footText, footFont));
        cellFootText.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cellFootText.setVerticalAlignment(Element.ALIGN_TOP);
        cellFootText.setPaddingTop(PDFTools.cmToPt(0.15f));
        cellFootText.setPaddingBottom(0);
        cellFootText.setPaddingLeft(0);
        cellFootText.setPaddingRight(0);
        cellFootText.setBorderWidthTop(0.5f);
        cellFootText.setBorderWidthBottom(0);
        cellFootText.setBorderWidthLeft(0);
        cellFootText.setBorderWidthRight(0);

        foot.addCell(cellFootText);

        /*
         * Print page numbers
         */
        PdfContentByte contentByte = writer.getDirectContent();
        contentByte.saveState();

        String text = MessageFormat.format(translate("Page {0} of") + " ", writer.getPageNumber());

        float textSize = footBaseFont.getWidthPoint(text, footFontSize);
        float textBase = document.bottom() - PDFTools.cmToPt(1.26f);
        contentByte.beginText();
        contentByte.setFontAndSize(footBaseFont, footFontSize);

        float adjust;
        if (footText.trim().equals("")) {
            adjust = (pageWidth / 2) - (textSize / 2) - footBaseFont.getWidthPoint("0", footFontSize);
        } else {
            adjust = 0;
        }

        contentByte.setTextMatrix(document.left() + adjust, textBase);
        contentByte.showText(text);
        contentByte.endText();
        contentByte.addTemplate(template, document.left() + adjust + textSize, textBase);

        contentByte.stroke();
        contentByte.restoreState();

        foot.setTotalWidth(pageWidth);
        foot.writeSelectedRows(0, -1, document.leftMargin(), document.bottomMargin(),
                writer.getDirectContent());
    } catch (Exception e) {
        /*
         * Not part of unit testing because this exception is only thrown if
         * an internal error occurs.
         */
        throw new ExceptionConverter(e);
    }
}

From source file:org.sakaiproject.tool.assessment.pdf.itext.HTMLWorker.java

License:Mozilla Public License

public void startElement(String tag, HashMap h) {
    if (!tagsSupported.containsKey(tag))
        return;/* w  ww . j a v a  2 s .c  o m*/
    try {
        style.applyStyle(tag, h);
        String follow = (String) FactoryProperties.followTags.get(tag);
        if (follow != null) {
            HashMap prop = new HashMap();
            prop.put(follow, null);
            cprops.addToChain(follow, prop);
            return;
        }
        FactoryProperties.insertStyle(h);
        if (tag.equals("a")) {
            cprops.addToChain(tag, h);
            if (currentParagraph == null)
                currentParagraph = new Paragraph();
            stack.push(currentParagraph);
            currentParagraph = new Paragraph();
            return;
        }
        if (tag.equals("br")) {
            if (currentParagraph == null)
                currentParagraph = new Paragraph();
            currentParagraph.add(factoryProperties.createChunk("\n", cprops));
            return;
        }
        if (tag.equals("hr")) {

            PdfPTable hr = new PdfPTable(1);
            hr.setHorizontalAlignment(Element.ALIGN_CENTER);
            hr.setWidthPercentage(100f);
            hr.setSpacingAfter(0f);
            hr.setSpacingBefore(0f);
            PdfPCell cell = new PdfPCell();
            cell.setUseVariableBorders(true);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setBorder(PdfPCell.BOTTOM);
            cell.setBorderWidth(1f);
            cell.setPadding(0);
            cell.addElement(factoryProperties.createChunk("\n", cprops));

            hr.addCell(cell);
            // paragraphs can't have tables? really? without it hr's may be rendered a bit early..
            //if (currentParagraph != null)
            //    currentParagraph.add(hr);
            //else
            document.add(hr);
            return;

        }
        if (tag.equals("font") || tag.equals("span")) {
            cprops.addToChain(tag, h);
            return;
        }
        if (tag.equals("img")) {
            String src = (String) h.get("src");
            if (src == null)
                return;
            cprops.addToChain(tag, h);
            Image img = null;
            if (interfaceProps != null) {
                HashMap images = (HashMap) interfaceProps.get("img_static");
                if (images != null) {
                    Image tim = (Image) images.get(src);
                    if (tim != null)
                        img = Image.getInstance(tim);
                } else {
                    if (!src.startsWith("http")) { // relative src references only
                        String baseurl = (String) interfaceProps.get("img_baseurl");
                        if (baseurl != null) {
                            src = baseurl + src;
                            img = Image.getInstance(src);
                        }
                    }
                }
            }
            if (img == null) {
                if (!src.startsWith("http")) {
                    String path = cprops.getProperty("image_path");
                    if (path == null)
                        path = "";
                    src = new File(path, src).getPath();
                    img = Image.getInstance(src);
                } else {
                    byte[] buffer;
                    String srcResource = src.substring(src.indexOf("/content", 0)).replaceAll("/content", "");
                    buffer = getImageStream(URLDecoder.decode(srcResource));
                    img = Image.getInstance(buffer);
                }
            }

            String align = (String) h.get("align");
            String width = (String) h.get("width");
            String height = (String) h.get("height");
            String border = (String) h.get("border");
            String hspace = (String) h.get("hspace");
            String vspace = (String) h.get("vspace");
            String before = cprops.getProperty("before");
            String after = cprops.getProperty("after");
            float wp = 0.0f;
            float lp = 0.0f;
            if (maxWidth > 0 && ((width != null && Integer.parseInt(width) > maxWidth)
                    || (width == null && (int) img.getWidth() > maxWidth))) {
                wp = lengthParse(String.valueOf(maxWidth), (int) img.getWidth());
                lp = wp;
            } else {
                wp = lengthParse(width, (int) img.getWidth());
                lp = lengthParse(height, (int) img.getHeight());
            }
            if (wp > 0 && lp > 0)
                img.scalePercent(wp, lp);
            else if (wp > 0)
                img.scalePercent(wp);
            else if (lp > 0)
                img.scalePercent(lp);
            img.setWidthPercentage(0);
            // border
            if (border != null && !"".equals(border)) {
                try {
                    img.setBorderWidth(Integer.parseInt(border));
                    img.setBorder(Image.BOX);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            // horizonatal space
            if (hspace != null && !"".equals(hspace)) {
                try {
                    img.setSpacingAfter(Float.parseFloat(hspace));
                    img.setSpacingBefore(Float.parseFloat(hspace));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            // horizontal alignment
            if (align != null && (align.equalsIgnoreCase("left") || align.equalsIgnoreCase("right"))) {
                endElement("p");
                int ralign = Image.LEFT;
                if (align.equalsIgnoreCase("right"))
                    ralign = Image.RIGHT;
                img.setAlignment(ralign | Image.TEXTWRAP);
                Img i = null;
                boolean skip = false;
                if (interfaceProps != null) {
                    i = (Img) interfaceProps.get("img_interface");
                    if (i != null)
                        skip = i.process(img, h, cprops, document);
                }
                if (!skip)
                    document.add(img);
                cprops.removeChain(tag);
            }
            // vertical alignment (or none)
            else {
                img.setAlignment(Image.TEXTWRAP);

                float bottom = 0.0f;
                float top = img.getTop();
                float prevHeight = 0.0f;
                float prevRise = 0.0f;

                if (currentParagraph != null) {
                    ArrayList chunks = currentParagraph.getChunks();
                    Chunk sibling = null;

                    for (int k = chunks.size() - 1; k >= 0; k--) {
                        if (chunks.get(k) != null)
                            sibling = (Chunk) chunks.get(k);
                    }

                    if (sibling != null) {
                        if (sibling.hasAttributes())
                            prevRise = sibling.getTextRise();
                        prevHeight = 0.0f;
                        if (sibling.getFont() != null) {
                            prevHeight = sibling.getFont().getCalculatedSize();
                        }
                    }
                }

                if ("absMiddle".equalsIgnoreCase(align)) {
                    if (prevHeight > 0)
                        bottom += (img.getScaledHeight() / 2.0f) - (prevHeight / 2.0f);
                    else if (img.getScaledHeight() > 0)
                        bottom += img.getScaledHeight() / 2.0f;
                } else if ("middle".equalsIgnoreCase(align)) {
                    if (img.getScaledHeight() > 0)
                        bottom += (img.getScaledHeight() / 2.0f);
                } else if ("bottom".equalsIgnoreCase(align) || "baseline".equalsIgnoreCase(align)
                        || "absbottom".equalsIgnoreCase(align)) {
                    //baseline and absbottom should have some slight tweeking from bottom, but not sure what??
                } else if ("top".equalsIgnoreCase(align)) {
                    bottom += img.getScaledHeight() - prevHeight;
                } else if ("texttop".equalsIgnoreCase(align)) {
                    bottom += img.getScaledHeight() - (prevHeight - prevRise);
                }

                cprops.removeChain(tag);
                if (currentParagraph == null) {
                    currentParagraph = FactoryProperties.createParagraph(cprops);
                    bottom = 0f;
                } else if (currentParagraph.isEmpty()) {
                    bottom = 0f;
                }

                currentParagraph.setLeading(2f + bottom, 1.00f);
                currentParagraph.add(new Chunk(img, 0, 0 - bottom));
            }
            return;
        }
        if (tag.equals("blockquote")) {
            cprops.addToChain(tag, h);
            inBLOCK = true;
            if (currentParagraph != null)
                endElement("p");
            currentParagraph = FactoryProperties.createParagraph(cprops);
            currentParagraph.add(factoryProperties.createChunk("\n", cprops));
            return;
        }
        endElement("p");
        if (tag.equals("h1") || tag.equals("h2") || tag.equals("h3") || tag.equals("h4") || tag.equals("h5")
                || tag.equals("h6")) {
            if (!h.containsKey("size")) {
                int v = 8 - Integer.parseInt(tag.substring(1));
                h.put("size", Integer.toString(v));
            }
            cprops.addToChain(tag, h);
            return;
        }
        if (tag.equals("ul")) {
            if (pendingLI)
                endElement("li");
            skipText = true;
            cprops.addToChain(tag, h);
            com.lowagie.text.List list = new com.lowagie.text.List(false, 10);
            list.setListSymbol("\u2022");
            stack.push(list);
            return;
        }
        if (tag.equals("ol")) {
            if (pendingLI)
                endElement("li");
            skipText = true;
            cprops.addToChain(tag, h);
            com.lowagie.text.List list = new com.lowagie.text.List(true, 10);
            stack.push(list);
            return;
        }
        if (tag.equals("li")) {
            if (pendingLI)
                endElement("li");
            skipText = false;
            pendingLI = true;
            cprops.addToChain(tag, h);
            stack.push(FactoryProperties.createListItem(cprops));
            return;
        }
        if (tag.equals("div") || tag.equals("body")) {
            cprops.addToChain(tag, h);
            return;
        }
        if (tag.equals("pre")) {
            if (!h.containsKey("face")) {
                h.put("face", "Courier");
            }
            cprops.addToChain(tag, h);
            isPRE = true;
            return;
        }
        if (tag.equals("p")) {
            cprops.addToChain(tag, h);
            currentParagraph = FactoryProperties.createParagraph(cprops);
            if (inBLOCK) {
                currentParagraph.setIndentationLeft(currentParagraph.getIndentationLeft() + 40.0F);
            }
            return;
        }
        if (tag.equals("tr")) {
            if (pendingTR)
                endElement("tr");
            skipText = true;
            pendingTR = true;
            cprops.addToChain("tr", h);
            return;
        }
        if (tag.equals("td") || tag.equals("th")) {
            if (pendingTD)
                endElement(tag);
            skipText = false;
            pendingTD = true;
            cprops.addToChain("td", h);
            stack.push(new IncCell(tag, cprops));
            return;
        }
        if (tag.equals("table")) {
            cprops.addToChain("table", h);
            IncTable table = new IncTable(h);
            stack.push(table);
            tableState.push(new boolean[] { pendingTR, pendingTD });
            pendingTR = pendingTD = false;
            skipText = true;
            return;
        }
    } catch (Exception e) {
        e.printStackTrace();
        //throw new ExceptionConverter(e);
    }
}

From source file:org.silverpeas.components.kmelia.workflowextensions.SendInKmelia.java

License:Open Source License

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

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

        String actor = step.getUser().getFullName();

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

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

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

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

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

        document.add(pTable);
    } catch (Exception e) {
        SilverLogger.getLogger(this).error(e.getMessage(), e);
    }
}

From source file:org.tellervo.desktop.print.SeriesReport.java

License:Open Source License

private void getTableKey() throws DocumentException, IOException, IOException {
    PdfPTable mainTable = new PdfPTable(12);
    float[] widths = { 0.1f, 0.1f, 0.8f, 0.1f, 0.1f, 0.8f, 0.1f, 0.1f, 0.8f, 0.1f, 0.1f, 0.8f };
    mainTable.setWidths(widths);/*from  ww w. j a  v a  2  s .  c  o m*/
    mainTable.setWidthPercentage(100);

    PdfPTable userRemarksTable = new PdfPTable(2);
    float[] widths2 = { 0.083f, 0.92f };
    userRemarksTable.setWidths(widths2);
    userRemarksTable.setWidthPercentage(100);

    Boolean userRemarkUsed = false;

    DecadalModel model;
    model = new UnitAwareDecadalModel(s);
    int rows = model.getRowCount();
    List<TridasRemark> masterList = null;

    // Loop through rows
    for (int row = 0; row < rows; row++) {
        // Loop through columns
        for (int col = 0; col < 11; col++) {
            org.tellervo.desktop.Year year = model.getYear(row, col);
            List<TridasRemark> remarksList = null;
            remarksList = s.getRemarksForYear(year);

            // If masterlist is still null initialize it with this remarks list
            if (remarksList.size() > 0 && masterList == null)
                masterList = remarksList;

            for (TridasRemark remark : remarksList) {
                if (!masterList.contains(remark))
                    masterList.add(remark);
            }
        }
    }

    for (TridasRemark remark : masterList) {
        PdfPCell iconCell = new PdfPCell();
        PdfPCell equalsCell = new PdfPCell();
        PdfPCell descriptionCell = new PdfPCell();

        iconCell.setBorder(0);
        equalsCell.setBorder(0);
        descriptionCell.setBorder(0);

        iconCell.setVerticalAlignment(Element.ALIGN_TOP);
        equalsCell.setVerticalAlignment(Element.ALIGN_TOP);
        descriptionCell.setVerticalAlignment(Element.ALIGN_TOP);

        Image icon = null;
        String remarkStr = null;

        // Get actual icon (either tridas or tellervo)
        if (remark.isSetNormalTridas()) {
            remarkStr = remark.getNormalTridas().toString().toLowerCase();
            remarkStr = remarkStr.replace("_", " ");
            icon = getTridasIcon(remark.getNormalTridas());
            if (icon == null)
                icon = Builder.getITextImageMissingIcon();
        } else if (TELLERVO.equals(remark.getNormalStd())) {
            remarkStr = remark.getNormal();
            icon = getCorinaIcon(remark.getNormal());
            if (icon == null)
                icon = Builder.getITextImageMissingIcon();
        } else {
            if (!userRemarkUsed) {
                remarkStr = "User Remark (See Below)";
                icon = Builder.getITextImageIcon("user.png");
                userRemarkUsed = true;
            } else {
                // User remark and we already have a key for this so continue
                continue;
            }
        }

        iconCell.addElement(icon);
        equalsCell.addElement(new Phrase("=", tableBodyFont));
        descriptionCell.addElement(new Phrase(WordUtils.capitalize(remarkStr), tableBodyFont));

        mainTable.addCell(iconCell);
        mainTable.addCell(equalsCell);
        mainTable.addCell(descriptionCell);
    }

    // Pad out empty cells
    PdfPCell blankCell = new PdfPCell();
    blankCell.addElement(new Phrase(""));
    blankCell.setBorder(0);
    for (int i = 0; i < 12; i++) {
        mainTable.addCell(blankCell);
    }

    document.add(mainTable);

    if (userRemarkUsed) {
        PdfPCell yearCell = new PdfPCell();
        yearCell.setBorder(0);
        yearCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        yearCell.addElement(new Phrase("Year", tableHeaderFont));
        userRemarksTable.addCell(yearCell);

        PdfPCell remarkCell = new PdfPCell();
        remarkCell.setBorder(0);
        remarkCell.addElement(new Phrase("User ring remarks", tableHeaderFont));
        userRemarksTable.addCell(remarkCell);

        for (int row = 0; row < rows; row++) {
            // Loop through columns
            for (int col = 0; col < 11; col++) {
                org.tellervo.desktop.Year year = model.getYear(row, col);
                List<TridasRemark> remarksList = null;
                remarksList = s.getRemarksForYear(year);

                for (TridasRemark remark : remarksList) {
                    if (remark.isSetNormalTridas() || remark.isSetNormalStd())
                        continue;

                    yearCell = new PdfPCell();
                    yearCell.setBorder(0);
                    yearCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                    yearCell.addElement(new Phrase(year.toString(), tableHeaderFont));
                    userRemarksTable.addCell(yearCell);

                    remarkCell = new PdfPCell();
                    remarkCell.setBorder(0);
                    remarkCell.addElement(new Phrase(remark.getValue(), tableBodyFont));
                    userRemarksTable.addCell(remarkCell);
                }
            }
        }

        document.add(userRemarksTable);
    }
}